<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Technical Jargon</title>
	
	<link>http://www.jeremyskinner.co.uk</link>
	<description>Did you notice the information bar?</description>
	<lastBuildDate>Mon, 08 Feb 2010 16:18:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/TechnicalJargon" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="technicaljargon" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>FluentValidation C4mvc presentation</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/08/fluentvalidation-c4mvc-presentation/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/08/fluentvalidation-c4mvc-presentation/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 07:59:44 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=355</guid>
		<description><![CDATA[
This Wednesday I&#8217;m going to be giving a live presentation on using FluentValidation for the c4mvc virtual usergroup.


The session will be live from 18:00 GMT (12:00 CST) and will last about 40 minutes. I&#8217;ll be covering the basics of using FluentValidation as well as how you can integrate it with ASP.NET MVC applications.
]]></description>
			<content:encoded><![CDATA[<p>
This Wednesday I&#8217;m going to be giving a live presentation on using <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> for the <a href="http://www.c4mvc.net/">c4mvc virtual usergroup</a>.
</p>
<p>
The session will be live from 18:00 GMT (12:00 CST) and will last about 40 minutes. I&#8217;ll be covering the basics of using FluentValidation as well as how you can integrate it with ASP.NET MVC applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/08/fluentvalidation-c4mvc-presentation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>FluentValidation 1.2 Beta 2 and MVC2 RC2</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 12:03:12 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=343</guid>
		<description><![CDATA[
FluentValidation 1.2 beta 2 is now available to download. This release focuses mainly on integration with ASP.NET MVC 2.


Since my post on Limitations of MVC2&#8217;s ModelValidatorProviders ASP.NET MVC2 RC2 has been released which addresses some of the issues that I raised in the post.


Firstly, validation in MVC2 RC2 now performs model-validation rather than input validation. [...]]]></description>
			<content:encoded><![CDATA[<p>
FluentValidation 1.2 beta 2 <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">is now available to download</a>. This release focuses mainly on integration with ASP.NET MVC 2.
</p>
<p>
Since my post on <a href="http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/">Limitations of MVC2&#8217;s ModelValidatorProviders</a> ASP.NET MVC2 RC2 has been released which addresses some of the issues that I raised in the post.
</p>
<p>
Firstly, validation in MVC2 RC2 <a href="http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html">now performs model-validation rather than input validation</a>. This is much more in line with how FluentValidation works which makes the FluentValidation integration much more consistent with the built-in validation.
</p>
<p>
Secondly, it is now possible to disable the DataAnnotationsModelValidatorProvider&#8217;s &#8220;greedy&#8221; required rule. Out of the box, the DataAnnotationsModelValidatorProvider will *always* validate non-nullable value types, irrespective of whether the property is decorated with a [Required] attribute. This meant that you had to un-register the DataAnnotations provider if you didn&#8217;t want to get duplicate errors. It is now possible to turn this off by calling <strong>DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;</strong> in your application startup routine.
</p>
<p>
Finally, I added the ability to be able to execute some of FluentValidation&#8217;s Property Validators without needing to validate the entire object. This means it is now possible to stop the default &#8220;A value was required&#8221; message from being added to ModelState.
</p>
<h3>Enabling the FluentValidationModelValidatorProvider</h3>
<p>
After <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">downloading the 1.2 beta 2 release</a> you&#8217;ll need to add a reference to FluentValidation.dll and FluentValidation.Mvc.dll
</p>
<p>
To enable the FluentValidationModelValidatorProvider you will need to add it to the ModelValidatorProviders collection in your application startup routine:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	DataAnnotationsModelValidatorProvider
		.<span style="color: #0000FF;">AddImplicitRequiredAttributeForValueTypes</span> <span style="color: #008000;">=</span> false<span style="color: #008000;">;</span>
&nbsp;
	ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that you need to pass an IValidatorFactory to the FluentValidationModelValidatorProvider so that it knows how to create your validator instances. I&#8217;m using the AttributedValidatorFactory in this example, but in a real application you would probably use an implementation that wraps an IoC container instead.
</p>
<p>
Next, you can create your model object and associated validator:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Validator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>PersonValidator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Name <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Email <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Age <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> PersonValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">10</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Email</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">EmailAddress</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Age</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">InclusiveBetween</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">18</span>, <span style="color: #FF0000;">60</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Finally, you can create the controller and associated view:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PeopleController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Person person<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
&nbsp;
		<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span> ModelState.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Create&quot;</span>, person<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		TempData<span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;notice&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Person successfully created&quot;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationSummary</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">&lt;%</span> using <span style="color: #006600; font-weight:bold;">&#40;</span>Html.<span style="color: #9900cc;">BeginForm</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #006600; font-weight:bold;">&#123;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	Id: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Id</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	&lt;br /&gt;
	Name: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Name</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>			
	&lt;br /&gt;
	Email: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span>Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Email</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Email</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
	&lt;br /&gt;
	Age: <span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">TextBoxFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Age</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span><span style="color: #000000; font-weight: bold;">&lt;%</span><span style="color: #006600; font-weight: bold;">=</span> Html.<span style="color: #9900cc;">ValidationMessageFor</span><span style="color: #006600; font-weight:bold;">&#40;</span>x <span style="color: #006600; font-weight: bold;">=&gt;</span> x.<span style="color: #9900cc;">Age</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span>
&nbsp;
	&lt;br /&gt;&lt;br /&gt;
&nbsp;
	&lt;input type=&quot;submit&quot; value=&quot;submit&quot; /&gt;
<span style="color: #000000; font-weight: bold;">&lt;%</span> <span style="color: #006600; font-weight:bold;">&#125;</span> <span style="color: #000000; font-weight: bold;">%&gt;</span></pre></div></div>

<p>
Now when you post the form MVC&#8217;s DefaultModelBinder will validate the Person object using the FluentValidationModelValidatorProvider.
</p>
<h3>Clientside Validation</h3>
<p>
This release also has preliminary support for clientside validation. This is enabled by calling <strong>&lt;% Html.EnableClientValidation(); %&gt;</strong> in your views. At the moment, only the NotNull, NotEmpty, RegularExpression and Length validators are supported.
</p>
<p>
Note that if you try to use the clientside validation support with the default error messages, you will see error messages like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #666666;">'{PropertyName}'</span> must not be empty.</pre></div></div>

<p>
This is because FluentValidation uses templated error messages but the MVC Framework&#8217;s clientside validation runner does not know how to correctly format these. For now, the only workaround is to explicitly specify the error message:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">WithMessage</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;'Surname' must not be empty&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
For FluentValidation 1.3 I will consider providing a customised version of MVC&#8217;s MicrosoftMvcValidation.js that knows how to properly format FluentValidation error templates.
</p>
<h3>
Metadata Support<br />
</h3>
<p>
Out of the box, MVC2 allows you to use the DataAnnotations attributes to provide <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html">metadata for editor/display templates</a>. This release of FluentValidation allows you to use extra extension methods on your validator classes to define metadata using method chaining.
</p>
<p>
Firstly, you will need to replace the DataAnnotationsModelMetadataProvider with the new FluentValidationModelMetadataProvider in your Application_Start:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ModelMetadataProviders.<span style="color: #0000FF;">Current</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationModelMetadataProvider<span style="color: #000000;">&#40;</span>
	<span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
Now you can start using the metadata extension in your validator classes (you will need to import the FluentValidation.Mvc.MetadataExtensions namespace):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//regular validator</span>
      .<span style="color: #0000FF;">UIHint</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//MVC Metadata</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The FluentValidationModelMetadataProvider currently supports the following metadata-related extension methods which correspond to the DataAnnotations attributes with the same name:</p>
<ul>
<li>HiddenInput</li>
<li>UIHint</li>
<li>Scaffold</li>
<li>DataType</li>
<li>DisplayName</li>
<li>DisplayFormat</li>
<li>ReadOnly</li>
</ul>
<p>
<strong>Edit: 8th Feb</strong>Note that there is a bug in the current beta build where MetaData won&#8217;t work in some circumstances. This is already fixed for the next beta, so you may want to use the latest binaries from <a href="http://build.jeremyskinner.co.uk/repository/download/bt2/.lastSuccessful/FluentValidation.zip?guest=1">the build server</a>.
</p>
<p>
As usual, binaries are <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=40035">on CodePlex</a> and the source is <a href="http://github.com/JeremySkinner/FluentValidation">on GitHub</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/06/fluentvalidation-1-2-beta-2-and-mvc2-rc2/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC – DataLoadOptions per Request</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 13:47:30 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=329</guid>
		<description><![CDATA[
This is the third in a series of posts on using ASP.NET MVC with Linq to Sql:


Part 1 &#8211; DataContext Per Request
Part 2 &#8211; AutoCommit and the RoutePreParser
Part 3 &#8211; DataLoadOptions per Request


Code for this series is available here.


One common problem when using an ORM is the issue of &#8220;select n+1&#8243;. For example, take the [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the third in a series of posts on using ASP.NET MVC with Linq to Sql:
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
One common problem when using an ORM is the issue of &#8220;select n+1&#8243;. For example, take the following Linq to Sql query:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var context <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var posts <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var post <span style="color: #0600FF;">in</span> posts<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var comment <span style="color: #0600FF;">in</span> post.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     var commenter <span style="color: #008000;">=</span> comment.<span style="color: #0000FF;">Commenter</span>.<span style="color: #0000FF;">Name</span><span style="color: #008000;">;</span>
     Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;User {0} commented on post {1}&quot;</span>, commenter, post.<span style="color: #0000FF;">Title</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This might look fine on the surface, but by default Linq to Sql will lazily-load all associations. This means that for each post loaded from the database Linq to Sql will issue a query to load the comments, and for each comment Linq to Sql will issue another query to load the commenter. So if you have 10 posts, and each post has 5 comments then you&#8217;ll end up making 61 queries to the database (1 for the posts, 1 for each post to get the comments, and 1 for each comment to get the user)
</p>
<p>
This can be mitigated by using DataLoadOptions to eagerly load all of the data in a single query:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var context <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
var options <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> options<span style="color: #008000;">;</span>
&nbsp;
var posts <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var post <span style="color: #0600FF;">in</span> posts<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
 <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>The Problem</h3>
<p>
However, once a query has been executed, the LoadOptions property of a DataContext is frozen &#8211; you cannot then specify any additional eager loading paths.*
</p>
<p>
If you&#8217;re using a DataContext per request <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">as per my previous post</a> then this can be a problem. For example, imagine you have the following controller action:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostsController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> PostsController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//injected via our IoC container</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var options <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> options<span style="color: #008000;">;</span>
&nbsp;
    var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;then this will work as expected. But now imagine your action is decorated by an ActionFilter:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>LoadCurrentUser<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span> 
  <span style="color: #008080; font-style: italic;">//...</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and let&#8217;s assume that our LoadCurrentUser filter attempts to load the details of the current user from the database and store them in ViewData:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> LoadCurrentUserAttribute <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuting<span style="color: #000000;">&#40;</span>ActionExecutingContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var context <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		var identity <span style="color: #008000;">=</span> filterContext.<span style="color: #0000FF;">HttpContext</span>.<span style="color: #0000FF;">User</span>.<span style="color: #0000FF;">Identity</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>identity.<span style="color: #0000FF;">IsAuthenticated</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var currentUser <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Users</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">UserName</span> <span style="color: #008000;">==</span> identity.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span><span style="color: #000000;">&#91;</span><span style="color: #666666;">&quot;CurrentUser&quot;</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> currentUser<span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now when the controller is executed we will get the following error:
</p>
<p>
<em><br />
 Setting load options is not allowed after results have been returned from a query.<br />
</em>
</p>
<p>
This happens because we&#8217;re trying to set the LoadOptions for the Post after the LoadCurrentUser filter already executed a query.
</p>
<h3>The Solution</h3>
<p>
The approach I use to work around this problem is to use a custom AuthorizationFilter in conjunction with an eager loading specification.
</p>
<p>
First, we define an interface for eager loading specifications:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IEagerLoadingSpecification <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next, we can write some classes that implement IEagerLoadingSpecification that define particular specifications for eager loading. Using the example above, we have PostWithComments and CommentWithCommenter:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostWithComments <span style="color: #008000;">:</span> IEagerLoadingSpecification <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Post<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Comments</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CommentWithCommenter <span style="color: #008000;">:</span> IEagerLoadingSpecification  <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Build<span style="color: #000000;">&#40;</span>DataLoadOptions options<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     options.<span style="color: #0000FF;">LoadWith</span><span style="color: #008000;">&lt;</span>Comment<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> c.<span style="color: #0000FF;">Commenter</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next, we write an EagerlyLoadAttribute which implements IAuthorizationFilter and takes an array of Types in its constructor:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> EagerlyLoadAttribute <span style="color: #008000;">:</span> FilterAttribute, IAuthorizationFilter <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">private</span> Type<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> types<span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> EagerlyLoadAttribute<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">params</span> Type<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> types<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">types</span> <span style="color: #008000;">=</span> types<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> OnAuthorization<span style="color: #000000;">&#40;</span>AuthorizationContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var loadOptions <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataLoadOptions<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    var context <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var type <span style="color: #0600FF;">in</span> types<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       <span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span> <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>IEagerLoadingSpecification<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">IsAssignableFrom</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
          <span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> InvalidOperationException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span>.<span style="color: #0000FF;">Format</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Type {0} does not implement IEagerLoadingSpecification&quot;</span>, type<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
       <span style="color: #000000;">&#125;</span>
&nbsp;
      var spec <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span>IEagerLoadingSpecification<span style="color: #000000;">&#41;</span>Activator.<span style="color: #0000FF;">CreateInstance</span><span style="color: #000000;">&#40;</span>type<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
      spec.<span style="color: #0000FF;">Build</span><span style="color: #000000;">&#40;</span>loadOptions<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
   context.<span style="color: #0000FF;">LoadOptions</span> <span style="color: #008000;">=</span> loadOptions<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
So what does this filter do? Firstly, because it implements IAuthorizationFilter this means it will be invoked before any action filters that decorate your controller action. When OnAuthorization is invoked, it loops over each of the Types that we&#8217;ve passed to its constructor, instantiates them and casts them to IEagerLoadingSpecification. Next, a single DataLoadOptions instance is passed to each of the specifications in turn so they can build up the required eager loading paths.
</p>
<p>
The end result is that you can now define your actions like this:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">  <span style="color: #000000;">&#91;</span>EagerlyLoad<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>PostWithComments<span style="color: #000000;">&#41;</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>CommentWithCommenter<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
  <span style="color: #000000;">&#91;</span>LoadCurrentUser<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>p <span style="color: #008000;">=&gt;</span> p.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Because the EagerlyLoadAttribute is an IAuthorizationFilter, it will be invoked before anything else meaning that by the time both our LoadCurrentUser filter and the Show action are invoked the DataLoadOptions have already been set on our DataContext.
</p>
<p>
* Note that other ORMs like NHibernate, LLBLGen and the Entity Framework don&#8217;t have this problem because they allow eager loading paths to be specified at the query level.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Search 1.0 Released</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/01/sql-search-1-released/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/01/sql-search-1-released/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 13:52:57 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[RedGate]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=320</guid>
		<description><![CDATA[
If you haven&#8217;t tried out Red Gate&#8217;s SQL Search yet, be sure to grab the v1.0 which was released today. I&#8217;ve been running the beta for the last couple of weeks and have been finding it quite useful when navigating around large SQL Server databases.


If you&#8217;ve used JetBrains&#8217; ReSharper before, you can think of SQL [...]]]></description>
			<content:encoded><![CDATA[<p>
If you haven&#8217;t tried out Red Gate&#8217;s <a href="http://www.red-gate.com/products/SQL_Search/">SQL Search</a> yet, be sure to grab the v1.0 which was released today. I&#8217;ve been running the beta for the last couple of weeks and have been finding it quite useful when navigating around large SQL Server databases.
</p>
<p>
If you&#8217;ve used JetBrains&#8217; <a href="http://www.jetbrains.com/resharper/">ReSharper</a> before, you can think of SQL Search like ReSharper&#8217;s <a href="http://www.jetbrains.com/resharper/features/navigation_search.html#Go_to_Type">Go to Type</a> functionality, but for SQL Server objects rather than classes. When you hit Ctrl+Alt+D you can begin typing the first few characters of an object name and it will list all the matches for you:</p>
<p>
<a href="http://www.jeremyskinner.co.uk/wp-content/uploads/2010/02/SqlSearch11.jpg"><img src="http://www.jeremyskinner.co.uk/wp-content/uploads/2010/02/SqlSearch11.jpg" alt="" title="SqlSearch1" width="623" height="496" class="alignnone size-full wp-image-324" /></a>
</p>
<p>
Hitting &#8216;enter&#8217; will take you to the selected object in the Object Explorer.
</p>
<p>
As a heavy keyboard user, I find this much more usable than navigating the Object Explorer with a mouse (especially for larger databases).
</p>
<p>
The only complaint I&#8217;d have is that the filtering options aren&#8217;t fine-grained enough. At the moment, you can filter the list on one of the following options:
</p>
<p><a href="http://www.jeremyskinner.co.uk/wp-content/uploads/2010/02/SqlSearch2.jpg"><img src="http://www.jeremyskinner.co.uk/wp-content/uploads/2010/02/SqlSearch2.jpg" alt="" title="SqlSearch2" width="80" height="132" class="alignnone size-full wp-image-322" /></a></p>
<p>
&#8230;but I&#8217;d find it more useful if you could pick multiple criteria (for example, I&#8217;d like to search the names of Tables, Views and Procedures, but not include Constraints and Triggers). Hopefully this will be added for the next version.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/01/sql-search-1-released/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC – AutoCommit and the RoutePreParser</title>
		<link>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 12:28:53 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=298</guid>
		<description><![CDATA[
This is the second in a series of posts on using ASP.NET MVC with Linq to Sql:


Part 1 &#8211; DataContext Per Request
Part 2 &#8211; AutoCommit and the RoutePreParser
Part 3 &#8211; DataLoadOptions per Request


Code for this series is available here.


In my previoust post, I demonstrated how you could scope a Linq to Sql DataContext to a [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the second in a series of posts on using ASP.NET MVC with Linq to Sql:
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
In my previoust post, I demonstrated how you could scope a Linq to Sql DataContext to a single HTTP Request by using StructureMap to manage the lifetime of the DataContext instance. This often works well, but has a couple of gotchas. Let&#8217;s take a look at an example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> PostController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
	<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post.<span style="color: #0000FF;">Id</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Show<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">SingleOrDefault</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>post <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">throw</span> <span style="color: #008000;">new</span> HttpException<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">404</span>, <span style="color: #666666;">&quot;The post could not be found.&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
In this example, we have a Post controller for our fictional Blog database. The Create action renders a view where the user can create a new Post and then sends an HTTP POST to the other overload to the Create action (decorated with AcceptVerbs(HttpVerbs.Post)).
</p>
<p>
This action is decorated with the AutoCommit attribute from my <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">previous post</a> so that SubmitChanges will automatically be called on our DataContext. We then redirect to the &#8220;Show&#8221; action passing the Id of the newly created post in the route data.
</p>
<p>
The Show action loads the Post from the database with the corresponding Id and displays it to the user. If a post with the specified Id could not be found, it will throw a 404 exception.
</p>
<p>
There is a bug here that may not be immediately obvious. Assume that the Post&#8217;s Id property is generated by an auto-incrementing Identity field in the database. If you were to run this application and create a new Post, the Show action <strong>will always throw 404 even though the Post has been successfully created.</strong></p>
<p>This happens because of when SubmitChanges is called. Our AutoCommit filter is invoked <strong>after the action has finished executing</strong> this means that at the time we call RedirectToAction(&#8220;Show&#8221;, new{ id = post.Id }) the new post <strong>has not yet been saved, so its Id will be 0</strong>.</p>
<p>Linq to Sql will not update the Id property until after SubmitChanges is called, which is too late in the process. The user will end up being redirected to Post/Show/0 instead of using the Id of the newly created post.
</p>
<p>
The simple workaround is to call SubmitChanges directly inside the action:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>ModelState.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>var transaction <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransactionScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			context.<span style="color: #0000FF;">SubmitChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			transaction.<span style="color: #0000FF;">Complete</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post.<span style="color: #0000FF;">Id</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;but this then makes our AutoCommit attribute useless and also makes the controller action significantly more complex.
</p>
<p>
However, there is another approach we could use which still allows us to use the AutoCommit attribute. To understand this, we first need to look at the order in which things are happening when our action is invoked:
</p>
<ol>
<li>The IoC container creates our DataContext</li>
<li>The controller is instantiated and the DataContext is passed to its constructor</li>
<li>The Create action is invoked with a Post instance created by MVC&#8217;s DefaultModelBinder</li>
<li>The post is attached to the DataContext by calling InsertOnSubmit</li>
<li>A RedirectToRouteResult is created by calling &#8220;RedirectToAction&#8221; with a dictionary of route values</li>
<li>The AutoCommit attribute calls SubmitChanges to our DataContext</li>
<li>The Post is written to the database</li>
<li>ExecuteResult on RedirectToRouteResult is invoked</li>
<li>The Redirect URL is generated by the RouteCollection</li>
<li>The user&#8217;s browser is redirected to this URL</li>
</ol>
<p>
Instead of passing the Post Id (which will be 0) to RedirectToAction, <strong>we could pass the entire post instance.</strong> After the post has been saved we can then *replace* the post instance in the RouteValueDictionary with the post&#8217;s Id before the URL is generated. This can be done by intercepting the RouteValueDictionary just before the URL is generated.
</p>
<h3>Introducing the RoutePreParser</h3>
<p>
The first thing we need is a way to identify how an object (in this case, our Post) should be converted to a route value. To do this, we can create an interface, IUrlRoutable:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">interface</span> IUrlRoutable <span style="color: #000000;">&#123;</span>
	<span style="color: #FF0000;">object</span> GetRouteParameter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and we can implement this interface in our Post class:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">partial</span> <span style="color: #FF0000;">class</span> Post <span style="color: #008000;">:</span> IUrlRoutable <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">object</span> GetRouteParameter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> Id<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Next we can create a &#8220;fake&#8221; route. This route never generates a URL or handles a request &#8211; it is merely used to intercept the RouteValueDictionary before a URL is generated:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> RoutePreParser <span style="color: #008000;">:</span> RouteBase <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> RouteData GetRouteData<span style="color: #000000;">&#40;</span>HttpContextBase httpContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> VirtualPathData GetVirtualPath<span style="color: #000000;">&#40;</span>RequestContext requestContext, RouteValueDictionary values<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var query <span style="color: #008000;">=</span> from pair <span style="color: #0600FF;">in</span> values
				where pair.<span style="color: #0000FF;">Value</span> <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span>
				let routable <span style="color: #008000;">=</span> pair.<span style="color: #0000FF;">Value</span> <span style="color: #0600FF;">as</span> IUrlRoutable
				where routable <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span>
				select <span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> pair.<span style="color: #0000FF;">Key</span>, Value <span style="color: #008000;">=</span> routable.<span style="color: #0000FF;">GetRouteParameter</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>var pair <span style="color: #0600FF;">in</span> query.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			values<span style="color: #000000;">&#91;</span>pair.<span style="color: #0000FF;">Key</span><span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> pair.<span style="color: #0000FF;">Value</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> null<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here we loop through each key-value pair in the RouteValueDictionary. If the value implements IUrlRoutable then we call GetRouteParameter on that object and <strong>replace the original value in the RouteValueDictionary with the result of this method.</strong>
</p>
<p>
Next, we have to add the fake route to the RouteCollection in Application_Start. Note that this <strong>must be the first route added so that it gets a chance to intercept the RouteValueDictionary.</strong>
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> RegisterRoutes<span style="color: #000000;">&#40;</span>RouteCollection routes<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">//Add our fake route first</span>
	routes.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> RoutePreParser<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	routes.<span style="color: #0000FF;">IgnoreRoute</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;{resource}.axd/{*pathInfo}&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	routes.<span style="color: #0000FF;">MapRoute</span><span style="color: #000000;">&#40;</span>
		<span style="color: #666666;">&quot;Default&quot;</span>, <span style="color: #008080; font-style: italic;">// Route name</span>
		<span style="color: #666666;">&quot;{controller}/{action}/{id}&quot;</span>, <span style="color: #008080; font-style: italic;">// URL with parameters</span>
		<span style="color: #008000;">new</span> <span style="color: #000000;">&#123;</span> controller <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Home&quot;</span>, action <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Index&quot;</span>, id <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;&quot;</span> <span style="color: #000000;">&#125;</span> <span style="color: #008080; font-style: italic;">// Parameter defaults</span>
	<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, in our controller action we change the Create action to store the Post instance in the route values:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Show&quot;</span>, <span style="color: #008000;">new</span><span style="color: #000000;">&#123;</span> id <span style="color: #008000;">=</span> post <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
&#8230;and everything now works as expected.
</p>
<p>
To recap, this is the new chain of events:
</p>
<ol>
<li>The IoC container creates our DataContext</li>
<li>The controller is instantiated and the DataContext is passed to its constructor</li>
<li>The Create action is invoked with a Post instance created by MVC&#8217;s DefaultModelBinder</li>
<li>The post is attached to the DataContext by calling InsertOnSubmit</li>
<li>A RedirectToRouteResult is created by calling &#8220;RedirectToAction&#8221; with a dictionary of route values. (The &#8220;Id&#8221; parameter is our new Post instance.)
</li>
<li>The AutoCommit attribute calls SubmitChanges to our DataContext</li>
<li>The Post is written to the database</li>
<li>The Post instance stored in the RouteValueDictionary automatically has its Id property updated</li>
<li>ExecuteResult on RedirectToRouteResult is invoked</li>
<li>Our RoutePreParser inspects the RouteValueDictionary.</li>
<li>GetRouteParameter on Post is invoked, returning the now-populated Post Id</li>
<li>The RoutePreParser removes the Post instance from the RouteValueDictionary</li>
<li>The RoutePreParser inserts the Post Id as the &#8220;id&#8221; in the RouteValueDictionary</li>
<li>The (now correct) redirect URL is generated by the RouteCollection</li>
<li>The user&#8217;s browser is redirected to this URL</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Linq to Sql and ASP.NET MVC – DataContext Per Request</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 11:45:23 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=292</guid>
		<description><![CDATA[
This is the first in a series of posts about using Linq to Sql with ASP.NET MVC.


Part 1 &#8211; DataContext Per Request
Part 2 &#8211; AutoCommit and the RoutePreParser
Part 3 &#8211; DataLoadOptions per Request


Code for this series is available here.


When using an ORM tool within a web application, it&#8217;s often common to scope a unit of [...]]]></description>
			<content:encoded><![CDATA[<p>
This is the first in a series of posts about using Linq to Sql with ASP.NET MVC.
</p>
<ul>
<li>Part 1 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/">DataContext Per Request</a></li>
<li>Part 2 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/01/linq-to-sql-and-asp-net-mvc-autocommit-and-the-routepreparser/">AutoCommit and the RoutePreParser</a></li>
<li>Part 3 &#8211; <a href="http://www.jeremyskinner.co.uk/2010/02/02/linq-to-sql-and-asp-net-mvc-dataloadoptions-per-request/">DataLoadOptions per Request</a></li>
</ul>
<p>
Code for this series is <a href="http://cloud.github.com/downloads/JeremySkinner/Experiments/LinqToSqlWithMvc.zip">available here</a>.
</p>
<p>
When using an ORM tool within a web application, it&#8217;s often common to scope a unit of work to the lifetime of an HTTP Request. If you&#8217;re using Linq to Sql and ASP.NET MVC, you can achieve this by using an Inversion of Control container in conjunction with an ActionFilter.
</p>
<p>
For this example, I&#8217;m going to be using the <a href="http://structuremap.sourceforge.net/Default.htm">StructureMap</a> IoC container alongside a fictional &#8220;Blog&#8221; database.
</p>
<p>
Firstly, you&#8217;ll need to configure StructureMap by calling ObjectFactory.Configure inside your Global.asax passing in a custom Registry instance:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ObjectFactory.<span style="color: #0000FF;">Configure</span><span style="color: #000000;">&#40;</span>cfg <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
		cfg.<span style="color: #0000FF;">AddRegistry</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The code for MyRegistry looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MyRegistry <span style="color: #008000;">:</span> Registry <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">For</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">HttpContextScoped</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
			.<span style="color: #0000FF;">Use</span><span style="color: #000000;">&#40;</span>c <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">new</span> BlogDataContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		Scan<span style="color: #000000;">&#40;</span>scan <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
			scan.<span style="color: #0000FF;">AddAllTypesOf</span><span style="color: #008000;">&lt;</span>Controller<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here I&#8217;m telling StructureMap to create one instance of my BlogDataContext per HTTP Request as well as registering each Controller instance with the container.
</p>
<p>
Next, we need to tell MVC to use StructureMap to instantiate our controllers. This can be done by creating a custom ControllerFactory:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> StructureMapControllerFactory <span style="color: #008000;">:</span> DefaultControllerFactory <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> IController GetControllerInstance<span style="color: #000000;">&#40;</span>RequestContext requestContext, Type controllerType<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>IController<span style="color: #000000;">&#41;</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #000000;">&#40;</span>controllerType<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
We can then replace the DefaultControllerFactory with the StructureMapControllerFactory in our Application_Start:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ObjectFactory.<span style="color: #0000FF;">Configure</span><span style="color: #000000;">&#40;</span>cfg <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
		cfg.<span style="color: #0000FF;">AddRegistry</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> MyRegistry<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ControllerBuilder.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">SetControllerFactory</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> StructureMapControllerFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, if we create a PostController (for creating and editing Posts in our fictional blog), we can now take a BlogDataContext in the constructor (for better testability, you&#8217;d probably want to hide the DataContext behind an interface):
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PostController <span style="color: #008000;">:</span> Controller <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">readonly</span> BlogDataContext context<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> PostController<span style="color: #000000;">&#40;</span>BlogDataContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">context</span> <span style="color: #008000;">=</span> context<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> ActionResult Edit<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> id<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var post <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span> <span style="color: #008000;">==</span> id<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF;">return</span> View<span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Now, visiting http://mysite/Post/Edit/1 would return a view to display a post with the Id of 1 (assuming the appropriate Post exists in the database).
</p>
<h3>Automatically Submitting Changes</h3>
<p>
We can take this a stage further by adding an ActionFilter to our application that will automatically call SubmitChanges on our DataContext at the end of the HTTP Request:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> AutoCommitAttribute <span style="color: #008000;">:</span> ActionFilterAttribute <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> <span style="color: #0600FF;">void</span> OnActionExecuted<span style="color: #000000;">&#40;</span>ActionExecutedContext filterContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>filterContext.<span style="color: #0000FF;">Controller</span>.<span style="color: #0000FF;">ViewData</span>.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">IsValid</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var currentDataContext <span style="color: #008000;">=</span> ObjectFactory.<span style="color: #0000FF;">GetInstance</span><span style="color: #008000;">&lt;</span>BlogDataContext<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #0600FF;">using</span> <span style="color: #000000;">&#40;</span>var transaction <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> TransactionScope<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				currentDataContext.<span style="color: #0000FF;">SubmitChanges</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
				transaction.<span style="color: #0000FF;">Complete</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Here we call into StructureMap to retrieve our current DataContext and commit any changes back to the database inside a transaction. Note that this will only happen if the ModelState is valid (ie there are no validation errors). </p>
<p>Another thing to keep in mind that using an IoC container as a Service Locator (as we&#8217;re doing in this filter) is generally considered bad practice. There are ways <a href="http://www.jeremyskinner.co.uk/2008/11/08/dependency-injection-with-aspnet-mvc-action-filters/">around</a> <a href="http://www.iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx">this</a> but these are outside the scope of this post.
</p>
<p>
Now, whenever we make a change to one of our entities the change will automatically be committed to the database provided the action is decorated with the AutoCommit attribute:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>AcceptVerbs<span style="color: #000000;">&#40;</span>HttpVerbs.<span style="color: #0000FF;">Post</span><span style="color: #000000;">&#41;</span>, AutoCommit<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> ActionResult Create<span style="color: #000000;">&#40;</span>Post post<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	context.<span style="color: #0000FF;">Posts</span>.<span style="color: #0000FF;">InsertOnSubmit</span><span style="color: #000000;">&#40;</span>post<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF;">return</span> RedirectToAction<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Index&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/31/linq-to-sql-and-asp-net-mvc-datacontext-per-request/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>FluentValidation 1.2 beta 1 available</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/23/fluentvalidation-1-2-beta-1-available/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/23/fluentvalidation-1-2-beta-1-available/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 10:47:17 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=283</guid>
		<description><![CDATA[
FluentValidation 1.2 beta 1 is now available to download.


This release contains several new features:

Setting the validator cascade mode

In v1.1, if you have multiple validators defined on a single property then all of those validators will be executed even if the first one fails. This can be changed by calling the Cascade method:


RuleFor&#40;x =&#62; x.Surname&#41;
  [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://fluentvalidation.codeplex.com">FluentValidation</a> 1.2 beta 1 is <a href="http://fluentvalidation.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=39334">now available to download</a>.
</p>
<p>
This release contains several new features:
</p>
<h3>Setting the validator cascade mode</h3>
<p>
In v1.1, if you have multiple validators defined on a single property then all of those validators will be executed even if the first one fails. This can be changed by calling the Cascade method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Cascade</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">StopOnFirstFailure</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">250</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
In this case, the Length validator would not be run on the Surname property if the NotNull validator fails.
</p>
<p>
This is customisable globally by setting the static property ValidatorOptions.CascadeMode.
</p>
<h3>MVC2 Support</h3>
<p>The FluentValidationModelBinder has been modified to work with ASP.NET MVC2 RC. Note that if you want to use FluentValidation with MVC1, you will need to use the older 1.1 release.</p>
<p>
FluentValidation 1.2 Beta 1 does not currently include the custom ModelMetadataProvider and ModelValidatorProvider that I mentioned <a href="http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/">in this post</a>.
</p>
<p>In its current state, the MVC2 metadata API is not extensible enough to work well with FluentValidtion (see <a href="http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/">this post</a> for details) so I&#8217;ve omitted them from this beta. If MVC2&#8217;s support for external frameworks is improved before RTM, then I will consider re-adding these features for the next release.
</p>
<h3>Custom user state</h3>
<p>
Custom user state can be stored alongside validation failures:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> person.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">WithState</span><span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> <span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span></pre></div></div>

<p>
This state can then be retrieved from the ValidationFailure object if the rule fails:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var result <span style="color: #008000;">=</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>model<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var error <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">Errors</span><span style="color: #000000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
var customState<span style="color: #008000;">=</span> error.<span style="color: #0000FF;">CustomState</span><span style="color: #008000;">;</span></pre></div></div>

<h3>OnAnyFailure</h3>
<p>
Rules can define a callback method that will be invoked if any of the validators associated with a particular rule fail:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> person.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">OnAnyFailure</span><span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> <span style="color: #000000;">&#123;</span>
   Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;#fail&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>WithPropertyName</h3>
<p>The WithPropertyName method can be used to override the name of the property that will be used when associating an error message with a particular property:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> PersonValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    RuleFor<span style="color: #000000;">&#40;</span>person <span style="color: #008000;">=&gt;</span> person.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">WithPropertyName</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;foo&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
var validator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> PersonValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var result <span style="color: #008000;">=</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080; font-style: italic;">//property name is 'foo' instead of 'Surname'</span>
<span style="color: #FF0000;">string</span> propertyName <span style="color: #008000;">=</span> result.<span style="color: #0000FF;">Errors</span>.<span style="color: #0000FF;">Single</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">PropertyName</span><span style="color: #008000;">;</span></pre></div></div>

<h3>InlineValidator</h3>
<p>
The InlineValidator can be used to define rules without creating a dedicated validator class:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var validator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> InlineValidator<span style="color: #008000;">&lt;</span>Person<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
  v <span style="color: #008000;">=&gt;</span> v.<span style="color: #0000FF;">RuleFor</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  v <span style="color: #008000;">=&gt;</span> v.<span style="color: #0000FF;">RuleFor</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Age</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GreaterThan</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h3>ValidateAndThrow</h3>
<p>The ValidateAndThrow extension method can be used to throw an exception when validation fails rather than returning a ValidationResult.</p>
<h3>Experimental xVal integration</h3>
<p>
Thanks to <a href="http://schotime.net/blog/">Adam Schroder</a>, FluentValidation now includes experimental support for generating xVal rules. I&#8217;ve labelled this as &#8220;Experimental&#8221; as there is currently no support for custom validation messages or some of the more complex FluentValidation rules. The future of the FluentValidation xVal integration also depends on what happens with MVC2&#8217;s validation providers and whether xVal will continue to be developed after the MVC2 release.
</p>
<h3>New PropertyValidator base class (potentially breaking change)</h3>
<p>
In FluentValidation 1.x, all property validators implemented the IPropertyValidator&lt;T,TProperty&gt; interface. As of v1.2 this has been deprecated in favour of the PropertyValidator base class. Note that property validators themselves are no longer generic, which makes them easier to work with if you need to gather metadata about a validator.
</p>
<p>For example, in v1.1 the NotNullValidator looked like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ValidationMessage<span style="color: #000000;">&#40;</span>Key <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;notnull_error&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> NotNullValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> <span style="color: #008000;">:</span> IPropertyValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> PropertyValidatorResult Validate<span style="color: #000000;">&#40;</span>PropertyValidatorContext<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span> context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">PropertyValue</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var formatter <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MessageFormatter<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">AppendProperyName</span><span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">PropertyDescription</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #FF0000;">string</span> error <span style="color: #008000;">=</span> context.<span style="color: #0000FF;">GetFormattedErrorMessage</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>NotNullValidator<span style="color: #008000;">&lt;</span>T, TProperty<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#41;</span>, formatter<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			<span style="color: #0600FF;">return</span> PropertyValidatorResult.<span style="color: #0000FF;">Failure</span><span style="color: #000000;">&#40;</span>error<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0600FF;">return</span> PropertyValidatorResult.<span style="color: #0000FF;">Success</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>&#8230;while in v1.2 it now looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> NotNullValidator <span style="color: #008000;">:</span> PropertyValidator, INotNullValidator <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> NotNullValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">:</span> <span style="color: #0600FF;">base</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> Messages.<span style="color: #0000FF;">notnull_error</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		SupportsStandaloneValidation <span style="color: #008000;">=</span> true<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">override</span> <span style="color: #FF0000;">bool</span> IsValid<span style="color: #000000;">&#40;</span>PropertyValidatorContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>context.<span style="color: #0000FF;">PropertyValue</span> <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			<span style="color: #0600FF;">return</span> false<span style="color: #008000;">;</span>
		<span style="color: #000000;">&#125;</span>
		<span style="color: #0600FF;">return</span> true<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The use of a base class helps keep the validator definitions simple. Also note that the ValidationMessage attribute has been removed &#8211; localised error messages can now be specified either by passing a resource type and key to the base PropertyValidator constructor or by using a lambda expression.
</p>
<p>
If you have written any custom property validators, it is recommended that you change them to inherit from PropertyValidator. However, <strong>there is a backwards compatibility layer in place which should allow old-style property validators to continue working.</strong>
</p>
<h3>DefaultResourceManager has been removed (breaking change)</h3>
<p>
In order to add better localization support, the DefaultResourceManager has been removed in favour of Visual Studio&#8217;s default generated &#8220;Messages&#8221; class. If you need to replace this with your own Messages class, you can set the static ResourceProviderType property on the ValidatorOptions class.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/23/fluentvalidation-1-2-beta-1-available/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Limitations of MVC2’s ModelValidatorProviders</title>
		<link>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/</link>
		<comments>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/#comments</comments>
		<pubDate>Wed, 13 Jan 2010 11:08:40 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>
		<category><![CDATA[aspnetmvc]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=274</guid>
		<description><![CDATA[
One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when they are passed to action parameters.


I wanted to try and write one of these for FluentValidation (see this post) but after trying this [...]]]></description>
			<content:encoded><![CDATA[<p>
One of the new features in ASP.NET MVC 2 is the ability the ability to define multiple validation providers. These are used by the DefaultModelBinder to automatically validate your model objects when they are passed to action parameters.
</p>
<p>
I wanted to try and write one of these for <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> (see <a href="http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/">this post</a>) but after trying this it has become quite clear that the ModelValidatorProvider API does have some limitations which have caused me some problems.
</p>
<h3>Problem 1: Property-level validation</h3>
<p>
To understand this problem, first we need to look at how different validation frameworks perform their work.
</p>
<p>
When using FluentValidation, the validators work against a pre-populated object. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CustomerValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Customer<span style="color: #000000;">&#123;</span> 
  <span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">CreditLimit</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">GreaterThanOrEqualTo</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
var customer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Customer <span style="color: #000000;">&#123;</span> CreditLimit <span style="color: #008000;">=</span> <span style="color: #008000;">-</span><span style="color: #FF0000;">1</span>, Surname <span style="color: #008000;">=</span> <span style="color: #0600FF;">null</span> <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
var validator <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
var results <span style="color: #008000;">=</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>customer<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
You cannot reliably validate individual properties by themselves because they may have dependencies on *other* properties being set. For example:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEqual</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Forename</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
This rule says tht the Surname and Forename properties must not be equal. In this case, you cannot validate the surname property by itself without having first set the value for the Forename property. Other validation frameworks (eg the Castle Project&#8217;s validation attributes) work in a similar way.
</p>
<p>
The MVC Framework&#8217;s DefaultModelBinder is primarily designed to work with the System.ComponentModel.DataAnnotations attributes. These work in a different way &#8211; they validate individual values, not the entire object.  To support this, the DefaultModelBinder allows validating both the individual property values (in the OnPropertyValidated method) as well as validating the entire instance (in the OnModelUpdated method).
</p>
<p>
Here are the relevant methods from DefaultModelBinder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnPropertyValidated - called for each property being bound.</span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnPropertyValidated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, <span style="color: #FF0000;">object</span> value<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    ModelMetadata propertyMetadata <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">PropertyMetadata</span><span style="color: #000000;">&#91;</span>propertyDescriptor.<span style="color: #0000FF;">Name</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    propertyMetadata.<span style="color: #0000FF;">Model</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
    <span style="color: #FF0000;">string</span> modelStateKey <span style="color: #008000;">=</span> CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, propertyMetadata.<span style="color: #0000FF;">PropertyName</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// run validation</span>
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> propertyMetadata.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">Model</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>modelStateKey, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// only add a &quot;value was required&quot; error message if there were no validation errors</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">IsValidField</span><span style="color: #000000;">&#40;</span>modelStateKey<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>value <span style="color: #008000;">==</span> <span style="color: #0600FF;">null</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>TypeHelpers.<span style="color: #0000FF;">TypeAllowsNullValue</span><span style="color: #000000;">&#40;</span>propertyDescriptor.<span style="color: #0000FF;">PropertyType</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>modelStateKey, GetValueRequiredResource<span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">//OnModelUpdated - called once the entire object has been bound. </span>
<span style="color: #0600FF;">protected</span> <span style="color: #0600FF;">virtual</span> <span style="color: #0600FF;">void</span> OnModelUpdated<span style="color: #000000;">&#40;</span>ControllerContext controllerContext, ModelBindingContext bindingContext<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
    IDataErrorInfo errorProvider <span style="color: #008000;">=</span> bindingContext.<span style="color: #0000FF;">Model</span> <span style="color: #0600FF;">as</span> IDataErrorInfo<span style="color: #008000;">;</span>
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>errorProvider <span style="color: #008000;">!=</span> <span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
         <span style="color: #FF0000;">string</span> errorText <span style="color: #008000;">=</span> errorProvider.<span style="color: #0000FF;">Error</span><span style="color: #008000;">;</span>
         <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #FF0000;">String</span>.<span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #000000;">&#40;</span>errorText<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, errorText<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
          <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span><span style="color: #008000;">!</span>IsModelValid<span style="color: #000000;">&#40;</span>bindingContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        return<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidator validator <span style="color: #0600FF;">in</span> bindingContext.<span style="color: #0000FF;">ModelMetadata</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>controllerContext<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span>ModelValidationResult validationResult <span style="color: #0600FF;">in</span> validator.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span><span style="color: #0600FF;">null</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
            bindingContext.<span style="color: #0000FF;">ModelState</span>.<span style="color: #0000FF;">AddModelError</span><span style="color: #000000;">&#40;</span>CreateSubPropertyName<span style="color: #000000;">&#40;</span>bindingContext.<span style="color: #0000FF;">ModelName</span>, validationResult.<span style="color: #0000FF;">MemberName</span><span style="color: #000000;">&#41;</span>, validationResult.<span style="color: #0000FF;">Message</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
On first glance, this looks like it will work. When OnPropertyValidated calls GetValidators, I can return an empty collection of validators and do all of my work in a single validator in OnModelUpdated. Unfortunately, this does not work.
</p>
<p>
See the end of OnPropertyValidated? Here, it checks if there have been any validation errors for the property and if not then it <strong>will go ahead and run its own built-in field validation anyway for non-nullable value types</strong> &#8211; it will put a message saying &#8220;A value was required&#8221; into ModelState. And you can&#8217;t turn this off. The *only way* to stop this built-in validation is to support property-level validation in your custom ValidatorProvider. Not very useful if the underlying framework does not support this.
</p>
<p>
To work around the above issue, I ended up adding property-level validation to FluentValidation, but this is not a completely reliable solution because of the issues related to cross-property validation I mentioned above.
</p>
<h3>Problem 2: The DataAnnotationsModelValidatorProvider is greedy</h3>
<p>
The next problem that I ran into is that the DataAnnotationsModelValidatorProvider will always run required field validation, even if you&#8217;re not using the DataAnnotations attributes!
</p>
<p>Here is an example that uses FluentValidation to validate an object where a null value is being bound to a non-nullable value type:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Validator<span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>FooValidator<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Foo <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">int</span> Id <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> FooValidator <span style="color: #008000;">:</span> AbstractValidator<span style="color: #008000;">&lt;</span>Foo<span style="color: #008000;">&gt;</span> <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> FooValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Id</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NotEmpty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
		<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
	<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//fails - 2 instead of 1</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This test fails because there are two error messages rather than one:
</p>
<pre>The Id field is required.
'Id' should not be empty.
</pre>
<p>
&#8230;the first of these errors comes from the DataAnnotationsModelValidatorProvider <strong>even though I have NOT decorated the Id property with a [Required] attribute</strong>.
</p>
<p>
Why does this happen? The answer is in DataAnnotationsModelValidatorProvider&#8217;s GetValidators method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #0600FF;">if</span> <span style="color: #000000;">&#40;</span>metadata.<span style="color: #0000FF;">IsRequired</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #008000;">!</span>attributes.<span style="color: #0000FF;">Any</span><span style="color: #000000;">&#40;</span>a <span style="color: #008000;">=&gt;</span> a <span style="color: #008000;">is</span> RequiredAttribute<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
       attributes <span style="color: #008000;">=</span> attributes.<span style="color: #0000FF;">Concat</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> <span style="color: #000000;">&#123;</span> <span style="color: #008000;">new</span> RequiredAttribute<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#125;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
 <span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This checks to see if the property is a non-nullable type and it does not have a RequiredAttribute, <strong>then it assumes that the property should have a RequiredAttribute anyway!</strong><br />
You can work around this by removing the DataAnnotationsModelValidatorProvider:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span>
	<span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
&#8230;and the test now passes.
</p>
<p>
Unfortunately, this is far from ideal. This means you cannot use the DataAnnotations attributes to validate one model and a custom provider for a different model. You have to choose one or the other.
</p>
<p>
One way to work around this problem is to use a composite validator provider that wraps the underlying providers:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> CompositeValidatorProvider <span style="color: #008000;">:</span> ModelValidatorProvider <span style="color: #000000;">&#123;</span>
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> Bootstrap<span style="color: #000000;">&#40;</span>ModelValidatorProviderCollection providerCollection, <span style="color: #0600FF;">params</span> ModelValidatorProvider<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> customProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		var validators <span style="color: #008000;">=</span> customProviders.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		validators.<span style="color: #0000FF;">AddRange</span><span style="color: #000000;">&#40;</span>providerCollection<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Clear</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
		providerCollection.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>validators<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">readonly</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerInnerProviders<span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF;">protected</span> CompositeValidatorProvider<span style="color: #000000;">&#40;</span>IEnumerable<span style="color: #008000;">&lt;</span>ModelValidatorProvider<span style="color: #008000;">&gt;</span> innerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">innerInnerProviders</span> <span style="color: #008000;">=</span> innerProviders<span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">override</span> IEnumerable<span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span> GetValidators<span style="color: #000000;">&#40;</span>ModelMetadata metadata, ControllerContext context<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
		<span style="color: #0600FF;">foreach</span><span style="color: #000000;">&#40;</span>var provider <span style="color: #0600FF;">in</span> innerInnerProviders<span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
			var validators <span style="color: #008000;">=</span> provider.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>metadata, context<span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #0600FF;">if</span><span style="color: #000000;">&#40;</span>validators.<span style="color: #0000FF;">Count</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
				<span style="color: #0600FF;">return</span> validators<span style="color: #008000;">;</span>	
			<span style="color: #000000;">&#125;</span>
		<span style="color: #000000;">&#125;</span>
&nbsp;
		<span style="color: #0600FF;">return</span> Enumerable.<span style="color: #0000FF;">Empty</span><span style="color: #008000;">&lt;</span>ModelValidator<span style="color: #008000;">&gt;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This custom provider can be used to wrap the built-in providers (including the DataAnnotations provider) as well as your own custom providers. In its GetValidators method, it iterates over each of the inner providers and asks each one to create a collection of validators. <strong>It only returns validators from the first provider that returns a non-empty collection</strong>. This means that if your custom provider can validate the object then the DataAnnotations provider will not be executed.</p>
<p>
Now, the following test passes:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>Test<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddsOneError<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
	var foo <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Foo<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    	var fluentProvider <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	CompositeValidatorProvider.<span style="color: #0000FF;">Bootstrap</span><span style="color: #000000;">&#40;</span>ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>, fluentProvider<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var meta <span style="color: #008000;">=</span> ModelMetadataProviders.<span style="color: #0000FF;">Current</span>.<span style="color: #0000FF;">GetMetadataForProperty</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&gt;</span> <span style="color: #0600FF;">null</span>, <span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>Foo<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;Id&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
	var validators <span style="color: #008000;">=</span> ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">GetValidators</span><span style="color: #000000;">&#40;</span>meta, <span style="color: #008000;">new</span> ControllerContext<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var results <span style="color: #008000;">=</span> validators.<span style="color: #0000FF;">SelectMany</span><span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Validate</span><span style="color: #000000;">&#40;</span>foo<span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">ToList</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	Assert.<span style="color: #0000FF;">AreEqual</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, results.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
This raises the question: <strong>if you have to resort to doing this, what is the point in allowing multiple validation providers to be registered in the first place?</strong>
</p>
<p>
I am really hoping that the MVC team will fix this fairly significant problem before RTM, but as MVC2 is already at the RC stage I think this will be unlikely.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2010/01/13/limitations-of-mvc2s-modelvalidatorproviders/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Phantom 0.2 Released</title>
		<link>http://www.jeremyskinner.co.uk/2009/12/30/phantom-0-2-released/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/12/30/phantom-0-2-released/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 15:29:06 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[Phantom]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=267</guid>
		<description><![CDATA[
Phantom 0.2 is now available to download. A big thanks goes to Andrey Shchekin for this release who contributed the NAnt integration and the Runnable syntax.


For those not familiar with Phantom, this is a build system written in C# and Boo.


Binaries
Documentation
Source

This release includes:
NAnt Integration
You can now execute NAnt tasks from within Phantom build scripts. In [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="http://github.com/JeremySkinner/Phantom">Phantom</a> 0.2 is now <a href="http://http://cloud.github.com/downloads/JeremySkinner/Phantom/Phantom-0.2.zip">available to download</a>. A big thanks goes to <a href="http://blog.ashmind.com/">Andrey Shchekin</a> for this release who contributed the NAnt integration and the Runnable syntax.
</p>
<p>
For those not familiar with Phantom, this is a build system written in C# and Boo.
</p>
<ul>
<li><a href="http://github.com/JeremySkinner/Phantom/downloads">Binaries</a></li>
<li><a href="http://wiki.github.com/JeremySkinner/Phantom">Documentation</a></li>
<li><a href="http://github.com/JeremySkinner/Phantom">Source</a></li>
</ul>
<p>This release includes:</p>
<h2>NAnt Integration</h2>
<p>You can now execute NAnt tasks from within Phantom build scripts. In order for this to work, you&#8217;ll need to drop Phantom.Integration.Nant.dll and NAnt.Core.dll into the same directory as Phantom.exe. Once in place, you can import the NAnt tasks. This example executes the &#8216;echo&#8217; task which is part of NAnt.Core.dll:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> tasks <span style="color: #ff7700;font-weight:bold;">from</span> NAnt.<span style="color: black;">Core</span>
target default:
   echo<span style="color: black;">&#40;</span>message : <span style="color: #483d8b;">&quot;Hello from NAnt!&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<h2>Runnables</h2>
<p>With v0.1 of Phantom, a lot of options were passed to helper methods via Hashes. For example, if you wanted tell msbuild to compile a project with a particular configuration and verbosity, you&#8217;d have to do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">msbuild<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;foo.sln&quot;</span>, <span style="color: black;">&#123;</span> <span style="color: #483d8b;">&quot;configuration&quot;</span>: <span style="color: #483d8b;">&quot;release&quot;</span>, <span style="color: #483d8b;">&quot;verbosity&quot;</span>: <span style="color: #483d8b;">&quot;normal&quot;</span> <span style="color: black;">&#125;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>
With Phantom 0.2, most of these methods have been converted to classes that define regular properties. You can use Boo&#8217;s object initializer syntax they can still be declared on one line:
</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">msbuild<span style="color: black;">&#40;</span><span style="color: #008000;">file</span>: <span style="color: #483d8b;">&quot;foo.sln&quot;</span>, configuration: <span style="color: #483d8b;">&quot;release&quot;</span>, verbosity: <span style="color: #483d8b;">&quot;normal&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>
This is called a &#8216;runnable&#8217; as the msbuild class implements the IRunnable interface. When Phantom sees an instance of an IRunnable type being created, it will automatically call the &#8216;Run&#8217; method (in this case, to kick off MSbuild). This syntax is equivalent to the following:
</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">m = msbuild<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
m.<span style="color: #008000;">file</span> = <span style="color: #483d8b;">&quot;foo.sln&quot;</span>
m.<span style="color: black;">configuration</span> = <span style="color: #483d8b;">&quot;release&quot;</span>
m.<span style="color: black;">verbosity</span> = <span style="color: #483d8b;">&quot;normal&quot;</span>
m.<span style="color: black;">Run</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Runnables can also be used inside a <a href="http://wiki.github.com/JeremySkinner/Phantom/with-syntax">with block</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">with</span> msbuild<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
  .<span style="color: #008000;">file</span> = <span style="color: #483d8b;">&quot;foo.sln&quot;</span>
  .<span style="color: black;">verbosity</span> = <span style="color: #483d8b;">&quot;normal&quot;</span>
  .<span style="color: black;">configuration</span> = <span style="color: #483d8b;">&quot;release&quot;</span></pre></div></div>

<p>&#8230;and the &#8216;Run&#8217; method will automatically be called at the end of the block. This is particularly useful if you have lots of properties that you want to set that cannot all fit on one line.</p>
<h2>Improved FileList support</h2>
<p>
The 0.1 version of <a href="http://wiki.github.com/JeremySkinner/Phantom/file-lists">FileLists</a> were rather limited. With 0.2 they now support exclusion patterns as well as recursively copying subdirectories:
</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">with</span> FileList<span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;path/to/bin/debug&quot;</span><span style="color: black;">&#41;</span>:
  .<span style="color: black;">Include</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;**/*&quot;</span><span style="color: black;">&#41;</span>
  .<span style="color: black;">ForEach</span> <span style="color: #ff7700;font-weight:bold;">def</span><span style="color: black;">&#40;</span><span style="color: #008000;">file</span><span style="color: black;">&#41;</span>:
    <span style="color: #008000;">file</span>.<span style="color: black;">CopyToDirectory</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">&quot;directoryToPackage&quot;</span><span style="color: black;">&#41;</span></pre></div></div>

<h2>NCover Integration</h2>
<p>
Phantom 0.2 now includes runnables for executing <a href="http://www.ncover.com">NCover</a> and NCoverExplorer. At present, these only work with the free Community Edition of NCover.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/12/30/phantom-0-2-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>FluentValidation moved to GitHub and what’s coming in v1.2</title>
		<link>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/</link>
		<comments>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/#comments</comments>
		<pubDate>Sun, 20 Dec 2009 22:19:18 +0000</pubDate>
		<dc:creator>Jeremy Skinner</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[FluentValidation]]></category>

		<guid isPermaLink="false">http://www.jeremyskinner.co.uk/?p=265</guid>
		<description><![CDATA[After several months of increasing frustration with CodePlex&#8217;s svn integration, I have moved the source code for FluentValidation to GitHub.

Continuous builds can still be downloaded from my build server.


Documentation, discussions and the issue tracker will still remain on the CodePlex site, but if you want to play with the source code then you&#8217;ll need to [...]]]></description>
			<content:encoded><![CDATA[<p>After several months of increasing frustration with <a href="http://www.codeplex.com/">CodePlex&#8217;s</a> svn integration, I have moved the source code for <a href="http://fluentvalidation.codeplex.com">FluentValidation</a> to <a href="http://github.com/JeremySkinner/FluentValidation">GitHub</a>.</p>
<p>
Continuous builds can still be downloaded <a href="http://build.jeremyskinner.co.uk">from my build server.</a>
</p>
<p>
Documentation, discussions and the issue tracker will still remain on the CodePlex site, but if you want to play with the source code then you&#8217;ll need to <a href="http://github.com/JeremySkinner/FluentValidation">head over to GitHub</a> instead. If you have not used Git before then I recommend reading my <a href="http://mvccontrib.github.com/MvcContrib/">Git Guide</a> (the guide was written for the MvcContrib project, but all the concepts apply to FluentValidation too).
</p>
<h2>What&#8217;s coming with v1.2?</h2>
<p>
The upcoming release of FluentValidation (v1.2) will have several changes including the following:
</p>
<h3>A custom ModelMetadataProvider</h3>
<p>
The FluentValidationModelMetadataProvider will allow you to define ASP.NET MVC Metadata inside your validator classes, eg:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> CustomerValidator<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
   RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
      .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008080; font-style: italic;">//regular validator</span>
      .<span style="color: #0000FF;">UIHint</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Surname&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">//MVC Metadata</span>
&nbsp;
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
The FluentValidationModelMetadataProvider will support the following metadata-related extension methods:</p>
<ul>
<li>HiddenInput</li>
<li>UIHint</li>
<li>Scaffold</li>
<li>DataType</li>
<li>DisplayName</li>
<li>DisplayFormat</li>
<li>ReadOnly</li>
</ul>
<h3>A custom ModelValidatorProvider</h3>
<p>
Previous versions of FluentValidation had a custom IModelBinder implementation that allowed you to use FluentValidation to validate ASP.NET MVC action parameters. This will no longer be necessary in v1.2 as ASP.NET MVC 2&#8217;s ModelValidatorProvider infrastructure means FluentValidation can now be plugged in to MVC&#8217;s DefaultModelBinder:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> MvcApplication <span style="color: #008000;">:</span> HttpApplication <span style="color: #000000;">&#123;</span>
   <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Application_Start<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #000000;">&#123;</span>
      RegisterRoutes<span style="color: #000000;">&#40;</span>RouteTable.<span style="color: #0000FF;">Routes</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
      ModelValidatorProviders.<span style="color: #0000FF;">Providers</span>.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> FluentValidationModelValidatorProvider<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> AttributedValidatorFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
   <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>
Note that the FluentValidationModelValidatorProvider will only support server-side validation, not client-side validation. FluentValidation&#8217;s validation mechanism is not compatible with how ASP.NET MVC 2 generates clientside validation rules.
</p>
<h3>Customisable Validator Cascade Mode</h3>
<p>
The validator cascade mode will be customisable in v1.2. Currently, if you have multiple validators defined on a single property then all of those validators will be executed even if the first one fails. This can be changed by calling the Cascade method:
</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">RuleFor<span style="color: #000000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x.<span style="color: #0000FF;">Surname</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Cascade</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">StopOnFirstFailure</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">NotNull</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  .<span style="color: #0000FF;">Length</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">1</span>, <span style="color: #FF0000;">250</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>
In this case, the Length validator would not be run on the Surname property if the NotNull validator fails.
</p>
<p>
This will also be customisable globally by setting the static property ValidatorOptions.CascadeMode.
</p>
<p>
I hope to release a first beta of v1.2 in the next couple of weeks. The final release should coincide with the release of ASP.NET MVC 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jeremyskinner.co.uk/2009/12/20/fluentvalidation-moved-to-github-and-whats-coming-in-v1-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
