<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Esencia Development &#187; Software Development</title>
	<atom:link href="http://www.esenciadev.com/category/softwaredevelopment/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.esenciadev.com</link>
	<description>thoughts and solutions from software craftsmen</description>
	<lastBuildDate>Tue, 31 May 2011 21:48:50 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>MOGenerator and XCode4 integration guide</title>
		<link>http://www.esenciadev.com/2011/05/mogen-and-xcode4-integration/</link>
		<comments>http://www.esenciadev.com/2011/05/mogen-and-xcode4-integration/#comments</comments>
		<pubDate>Tue, 31 May 2011 21:45:46 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[coredata]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[mogenerator]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://www.esenciadev.com/?p=339</guid>
		<description><![CDATA[This article will not serve as an introduction to MOGenerator or it&#8217;s abilities &#8211; that subject has been covered elsewhere. The sole purpose of this guide is to provide you with the steps necessary to get MOGenerator pseudo-integrated with XCode 4, at least as much as possible at this time. To summarize, we&#8217;ll be adding custom [...]]]></description>
			<content:encoded><![CDATA[<p>This article will not serve as an introduction to MOGenerator or it&#8217;s abilities &#8211; that subject has been covered elsewhere. The sole purpose of this guide is to provide you with the steps necessary to get MOGenerator pseudo-integrated with XCode 4, at least as much as possible at this time.</p>
<p>To summarize, we&#8217;ll be adding custom build steps to your project which instruct XCode to run shell scripts to process Core Data Model files. These scripts will determine the correct model version, call mogenerator to generate/update the entity classes, and then call momc to compile the model (this is usually performed by xcode, but since we&#8217;re inserting a new build rule for model files we need to handle it). I have tested these instructions on several different iOS projects, with multiple models and model versions.</p>
<p>Step 0) Download and install <a href="https://github.com/rentzsch/mogenerator" target="_blank">MOGenerator</a> if you haven&#8217;t already. I used MOGenerator ver 1.22.</p>
<p>Step 1) Download the <a href="http://www.esenciadev.com/wp-content/uploads/2011/05/mogenScripts.zip">MOGenerator scripts</a> and copy into a location in your project. For the purposes of this tutorial, I&#8217;ll put them in a folder named &#8216;scripts&#8217; at the root of the project directory.</p>
<ul>
<li><strong>REQUIRED</strong>: Modify the script to suits your needs. You will need to change the name of the ManagedObject class your entities should inherit from, and you may want to change the output directory. For an explanation of each parameter please refer to the MOGenerator documentation.</li>
</ul>
<p>Step 2) On the &#8220;Build Rules&#8221; tab of your target in XCode, add two build rules; one for &#8220;Data model files&#8221; and another for &#8220;Data model version files&#8221;</p>
<ul>
<li>a. Change the Process dropdown to &#8220;Data Model Files&#8221;</li>
<li>b. Change the Using dropdown to &#8220;Custom Script&#8221;</li>
</ul>
<p>Step 3) Put the path to the scripts in your project. In this example, they are in a folder &#8220;scripts&#8221; in the same directory as the Project file (<a href="http://developer.apple.com/library/mac/#documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html" target="_blank">Here</a> is a list of all XCode environment variables).</p>
<p><a rel="attachment wp-att-342" href="http://www.esenciadev.com/2011/05/mogen-and-xcode4-integration/mogenbuildrules-2/"><img class="size-full wp-image-342" src="http://www.esenciadev.com/wp-content/uploads/2011/05/mogenBuildRules1.png" alt="" width="461" height="523" /></a></p>
<p>Step 4) Add the output file pattern so XCode is knows what this custom step produces.</p>
<p>Step 5) Repeat steps 2-4 for the Data Model Version files. Take note that the file type processed, script executed, and output from this step are different. Refer to the screenshot</p>
<p>Step 6) Build your project.</p>
<p>Step 7) Any entities which are new (that is, which MOGenerator has not encountered in a previous build) will need to be manually added to your project. This step only needs to be performed when you have new entities, not during updates to existing entities.</p>
<p>If you have multiple targets in your project which utilize your data model, you&#8217;ll need to add these build steps for each target to make sure the model is kept up to date for each target.</p>
<p>I&#8217;d like to thank Jean-Denis Muys for providing the XCode4 integration steps needed to make this possible, and Jonathan Rentzsch for creating mogenerator.</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F&amp;title=MOGenerator+and+XCode4+integration+guide" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F&amp;title=MOGenerator+and+XCode4+integration+guide" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F&amp;title=MOGenerator+and+XCode4+integration+guide" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F&amp;headline=MOGenerator+and+XCode4+integration+guide" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=MOGenerator+and+XCode4+integration+guide&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=MOGenerator+and+XCode4+integration+guide&amp;u=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=MOGenerator+and+XCode4+integration+guide&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=MOGenerator+and+XCode4+integration+guide&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=MOGenerator+and+XCode4+integration+guide&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F&amp;title=MOGenerator+and+XCode4+integration+guide&amp;summary=&amp;source=" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F05%2Fmogen-and-xcode4-integration%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.esenciadev.com/2011/05/mogen-and-xcode4-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Model Validation in ASP.NET MVC3</title>
		<link>http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/</link>
		<comments>http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/#comments</comments>
		<pubDate>Fri, 18 Feb 2011 05:34:38 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[MVC3]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.esenciadev.com/?p=210</guid>
		<description><![CDATA[One of the cool new features in MVC3 is enhanced support for model validation via the IValidatableObject interface. By implementing this interface, a model class signals that it is in charge of at least some of the work required to validate itself. One of the best aspects of this new feature is that it integrates [...]]]></description>
			<content:encoded><![CDATA[<p>One of the cool new features in <a href="http://www.asp.net/mvc/mvc3" target="_blank">MVC3 </a>is enhanced support for model validation via the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx" target="_blank">IValidatableObject</a> interface. By implementing this interface, a model class signals that it is in charge of at least <strong>some</strong> of the work required to validate itself. One of the best aspects of  this new feature is that it integrates seamlessly with MVC&#8217;s model state validation.</p>
<p>There are already several <a href="http://davidhayden.com/blog/dave/archive/2010/12/31/ASPNETMVC3ValidationIValidatableObject.aspx" target="_blank">examples available</a> of the basic use of this feature in MVC3, so I thought we&#8217;d take a look at a somewhat more complex scenario. In this somewhat contrived example, the user will submit a review of a restaurant meal. We&#8217;ll be asking for an overall rating from 1 to 5, and for each menu item, the user will submit the name of the item, whether or not it was acceptable, and if it was not acceptable, why. In doing so, we&#8217;ll see how to implement <span style="font-family:monospace">IValidatableObject</span> for a composite model class.</p>
<p>Here&#8217;s our basic top-level model object.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ComponentModel.DataAnnotations</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Models</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MenuRatingModel
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Overall Rating&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #008000;">&#91;</span>Required<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">byte</span> OverallRating <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> MenuRatingListEntryModel<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> ListEntries <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We&#8217;re taking advantage of some of the attributes in the <span style="font-family:monospace;font-weight:bold">System.ComponentModel.DataAnnotations</span> namespace, and later, when we look at the view, we&#8217;ll see how they come in handy. Our top-level model object contains an array of sub-items of type <span style="font-family:monospace">MenuRatingListEntryModel</span>, the initial definition of which looks like this.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ComponentModel.DataAnnotations</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Models</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MenuRatingListEntryModel
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Menu Item&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #008000;">&#91;</span>Required<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> MenuItemName <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Satisfactory?&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> WasSatisfactory <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;If not satisfactory, explain why.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Explanation <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Naturally, we&#8217;ll need a controller, so here&#8217;s the code to serve up the form.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Collections.Generic</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Web.Mvc</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">IValidatableObjectDemo.Models</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Controllers</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">partial</span> <span style="color: #6666cc; font-weight: bold;">class</span> MenuRatingController <span style="color: #008000;">:</span> Controller
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>HttpGet<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> ActionResult Index<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var model <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MenuRatingModel<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            List entries <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            model<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span>
                                    <span style="color: #008000;">&#123;</span>
                                        <span style="color: #008000;">new</span> MenuRatingListEntryModel<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,
                                        <span style="color: #008000;">new</span> MenuRatingListEntryModel<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,
                                        <span style="color: #008000;">new</span> MenuRatingListEntryModel<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>,
                                        <span style="color: #008000;">new</span> MenuRatingListEntryModel<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                                    <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span>Views<span style="color: #008000;">.</span><span style="color: #0000FF;">Index</span>, model<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>HttpPost<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> ActionResult Index<span style="color: #008000;">&#40;</span>MenuRatingModel model<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">!</span> ModelState<span style="color: #008000;">.</span><span style="color: #0000FF;">IsValid</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">return</span> View<span style="color: #008000;">&#40;</span>Views<span style="color: #008000;">.</span><span style="color: #0000FF;">Index</span>, model<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> Content<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Submission successful.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We&#8217;re creating an instance of the model pre-populated with four entries for menu items. Dynamically adding menu items is certainly doable; it&#8217;s beyond the scope of what we&#8217;re covering here, but Steve Sanderson has covered it <a href="http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/" target="_blank">on his blog</a>. Note the line that returns the <span style="font-family:monospace">ViewResult</span>; we&#8217;re using the <a href="http://mvccontrib.codeplex.com/wikipage?title=T4MVC" target="_blank">T4MVC T4 template</a>, which greatly reduces the need for magic string values to denote controller, action, and view names. If you&#8217;re not using it, you should be.</p>
<p>Here&#8217;s the first implementation of our view. We&#8217;re using the new <a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx" target="_blank">Razor View Engine</a> included with MVC3; it&#8217;s actually the default View Engine when creating a new MVC3 project, and after you use it for a while, you&#8217;ll see why. It&#8217;s much more elegant, concise, and readable than the old WebForms engine.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">@model IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Models</span><span style="color: #008000;">.</span><span style="color: #0000FF;">MenuRatingModel</span>
&nbsp;
@<span style="color: #008000;">&#123;</span>
 ViewBag<span style="color: #008000;">.</span><span style="color: #0000FF;">Title</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Menu Rating&quot;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&lt;</span>h2<span style="color: #008000;">&gt;</span>Menu Rating<span style="color: #008000;">&lt;/</span>h2<span style="color: #008000;">&gt;</span>
@<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>Html<span style="color: #008000;">.</span><span style="color: #0000FF;">BeginForm</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
 <span style="color: #008000;">&lt;</span>div id<span style="color: #008000;">=</span><span style="color: #666666;">&quot;overallRating&quot;</span><span style="color: #008000;">&gt;</span>
@Html<span style="color: #008000;">.</span><span style="color: #0000FF;">LabelFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span><span style="color: #008000;">&#41;</span>
 @<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> ratingCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> ratingCounter <span style="color: #008000;">&lt;=</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span> ratingCounter<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
 <span style="color: #008000;">&#123;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">RadioButtonFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span>, ratingCounter, <span style="color: #008000;">new</span> <span style="color: #008000;">&#123;</span> id <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;OverallRating_&quot;</span> <span style="color: #008000;">+</span> ratingCounter <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span>
 @ratingCounter
 <span style="color: #008000;">&#125;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span><span style="color: #008000;">&#41;</span>
 <span style="color: #008000;">&lt;/</span>div<span style="color: #008000;">&gt;</span>
 <span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> entryCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> entryCounter <span style="color: #008000;">&lt;</span> Model<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span><span style="color: #008000;">;</span> entryCounter<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
 <span style="color: #008000;">&#123;</span>
 <span style="color: #008000;">&lt;</span>div id<span style="color: #008000;">=</span><span style="color: #666666;">&quot;entryRating_@(entryCounter)&quot;</span><span style="color: #008000;">&gt;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">LabelFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">MenuItemName</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">EditorFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">MenuItemName</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">MenuItemName</span><span style="color: #008000;">&#41;</span>
&nbsp;
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">LabelFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">WasSatisfactory</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">EditorFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">WasSatisfactory</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">WasSatisfactory</span><span style="color: #008000;">&#41;</span>
&nbsp;
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">LabelFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Explanation</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">EditorFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Explanation</span><span style="color: #008000;">&#41;</span>
 @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#91;</span>entryCounter<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Explanation</span><span style="color: #008000;">&#41;</span>
 <span style="color: #008000;">&lt;/</span>div<span style="color: #008000;">&gt;</span>
 <span style="color: #008000;">&#125;</span>
 <span style="color: #008000;">&lt;</span>input type<span style="color: #008000;">=</span><span style="color: #666666;">&quot;submit&quot;</span> value<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Submit Rating&quot;</span> <span style="color: #008000;">/&gt;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>When we use <span style="font-family: monospace">Html.LabelFor</span>, MVC will automatically detect the <span style="font-family: monospace">[Display]</span> attribute we included in the model and use it for the label text. If you load this up and try to submit without entering any values, the <span style="font-family: monospace">[Required]</span> attribute we added will work its magic. Additionally, if you&#8217;re using jQuery Validation along with jQuery unobtrusive validation, these errors will be displayed on the client without any form post happening. Nice.</p>
<div id="attachment_238" class="wp-caption alignnone" style="width: 932px"><a rel="attachment wp-att-238" href="http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/simplepostwithvalidation/"><img class="size-full wp-image-238" src="http://www.esenciadev.com/wp-content/uploads/2011/02/SimplePostWithValidation.png" alt="" width="922" height="204" /></a><p class="wp-caption-text">Simple (attempted) postback with basic validation</p></div>
<p>This is all well and good, but we&#8217;re going to add additional levels of validation. First, we want to ensure that, if the user has not checked the &#8220;satisfactory&#8221; box for a menu item, they must enter an explanation. Here&#8217;s where <span style="font-family:monospace">IValidatableObject</span> comes into play. By implementing the <span style="font-family:monospace">IValidatableObject</span> interface, we can handle simple object-level validation in the model itself. Here&#8217;s the new definition of the <span style="font-family:monospace">MenuRatingListEntryModel</span> class.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ComponentModel.DataAnnotations</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Models</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MenuRatingListEntryModel <span style="color: #008000;">:</span> IValidatableObject
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Menu Item&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #008000;">&#91;</span>Required<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> MenuItemName <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Satisfactory?&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> WasSatisfactory <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;If not satisfactory, explain why.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">string</span> Explanation <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Collections</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Generic</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IEnumerable</span> Validate<span style="color: #008000;">&#40;</span>ValidationContext validationContext<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span><span style="color: #008000;">&#40;</span> <span style="color: #008000;">!</span> WasSatisfactory <span style="color: #008000;">&amp;&amp;</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>Explanation<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> ValidationResult<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Please explain why.&quot;</span>, <span style="color: #008000;">new</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">&#123;</span><span style="color: #666666;">&quot;Explanation&quot;</span><span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We&#8217;re implementing the <span style="font-family:monospace">IValidatableObject</span> interface and fulfilling the sole method in that interface, <span style="font-family:monospace">Validate()</span>. Within the <span style="font-family:monospace">Validate()</span> method, you can return a list of <span style="font-family:monospace">ValidationResult</span> instances, each of which has an error message and a sub-list of property names to which the error applies. In our case, we&#8217;re only checking for one error, and we&#8217;re applying it to a single property (Explanation). Note that the string value provided to the <span style="font-family:monospace">ValidationResult</span> <strong>must match the property name</strong>. This is how MVC matches up the <span style="font-family:monospace">ValidationResult</span> to a ModelState entry.</p>
<p>Now here&#8217;s the cool part. If you try to do a partial submission now (let&#8217;s say, entering menu item names, checking &#8220;Satisfactory&#8221; for only two items, and providing no explanation), here&#8217;s what you get on the POST.</p>
<p><a rel="attachment wp-att-265" href="http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/pleaseexplainwhy/"><img class="alignnone size-full wp-image-265" src="http://www.esenciadev.com/wp-content/uploads/2011/02/PleaseExplainWhy.png" alt="" width="818" height="186" /></a></p>
<p><strong>We have not altered our controller code in any way. </strong>Instead, the MVC3 Framework helpfully checks our model object(s) to see if they are <span style="font-family:monospace">IValidatableObjects</span>, and if they are, it runs the validation code and adds any ValidationResults returned as ModelState errors. Now that&#8217;s handy.</p>
<p>Let&#8217;s move on to another task. Let&#8217;s suppose we want to add a constraint that says the user can&#8217;t submit the same item twice, so we want to check that the menu item name is unique. Initially, I thought we could take care of this sort of thing in the <span style="font-family:monospace">MenuRatingListEntryModel</span> class, but we can&#8217;t. When the model binding process occurs and the <span style="font-family:monospace">Validate()</span> method is called, it&#8217;s called when the <span style="font-family:monospace">MenuRatingListEntryModel</span> instance is hydrated from the POST data and BEFORE it is attached to the parent model instance. This means we&#8217;ll have to take care of it in the parent model class. Here&#8217;s the revised definition.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.ComponentModel.DataAnnotations</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Linq</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> IValidatableObjectDemo<span style="color: #008000;">.</span><span style="color: #0000FF;">Models</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MenuRatingModel <span style="color: #008000;">:</span> IValidatableObject
    <span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>Display<span style="color: #008000;">&#40;</span>Name<span style="color: #008000;">=</span><span style="color: #666666;">&quot;Overall Rating&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
        <span style="color: #008000;">&#91;</span>Required<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">byte</span> OverallRating <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> MenuRatingListEntryModel<span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> ListEntries <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Collections</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Generic</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IEnumerable</span> Validate<span style="color: #008000;">&#40;</span>ValidationContext validationContext<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var grouping <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GroupBy</span><span style="color: #008000;">&#40;</span>listEntry <span style="color: #008000;">=&gt;</span> listEntry<span style="color: #008000;">.</span><span style="color: #0000FF;">MenuItemName</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToLowerInvariant</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            var duplicates <span style="color: #008000;">=</span> grouping<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>group <span style="color: #008000;">=&gt;</span> group<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span><span style="color: #008000;">&#40;</span>var duplicate <span style="color: #0600FF; font-weight: bold;">in</span> duplicates<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">yield</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> ValidationResult<span style="color: #008000;">&#40;</span>
                    <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;You entered {0} {1} times&quot;</span>, duplicate<span style="color: #008000;">.</span><span style="color: #0000FF;">Key</span>, duplicate<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
                    <span style="color: #008000;">new</span> <span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span><span style="color: #666666;">&quot;ListEntries&quot;</span><span style="color: #008000;">&#125;</span>
                    <span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>We&#8217;re using a bit of LINQ to find any list entries that have duplicate values entered for the menu item, regardless of casing. We&#8217;ll also add a <span style="font-family:monospace">ValidationMessageFor()</span> call to our view on line 18, which will generate a validation message for the <span style="font-family:monospace">ListEntries</span> property. Again, note that the property name returned in our <span style="font-family:monospace">ValidationResult</span> matches this property name.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&lt;</span>div<span style="color: #008000;">&gt;</span>
@Html<span style="color: #008000;">.</span><span style="color: #0000FF;">LabelFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span><span style="color: #008000;">&#41;</span>
    @<span style="color: #0600FF; font-weight: bold;">for</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">int</span> ratingCounter <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">;</span> ratingCounter <span style="color: #008000;">&lt;=</span> <span style="color: #FF0000;">5</span><span style="color: #008000;">;</span> ratingCounter<span style="color: #008000;">++</span><span style="color: #008000;">&#41;</span>
      <span style="color: #008000;">&#123;</span>
          @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">RadioButtonFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span>, ratingCounter, <span style="color: #008000;">new</span> <span style="color: #008000;">&#123;</span> id <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;OverallRating_&quot;</span> <span style="color: #008000;">+</span> ratingCounter <span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span>
          @ratingCounter
      <span style="color: #008000;">&#125;</span><span style="color: #008000;">&lt;/</span>div<span style="color: #008000;">&gt;</span>
&nbsp;
      @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">OverallRating</span><span style="color: #008000;">&#41;</span>
      @Html<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationMessageFor</span><span style="color: #008000;">&#40;</span>m <span style="color: #008000;">=&gt;</span> m<span style="color: #008000;">.</span><span style="color: #0000FF;">ListEntries</span><span style="color: #008000;">&#41;</span></pre></div></div>

<p>Here&#8217;s the result of a post with a duplicate submission.<br />
<a href="http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/duplicateentry/" rel="attachment wp-att-309"><img src="http://www.esenciadev.com/wp-content/uploads/2011/02/DuplicateEntry.png" alt="" width="696" height="192" class="alignnone size-full wp-image-309" /></a></p>
<p>While this approach streamlines things considerably, there are some definite downsides to consider.</p>
<ul>
<li>If model validation fails on the child object, the validation code on the parent object is run, but for some reason the parent <span style="font-family:monospace">ValidationResult</span>(s) returned do not get appended as errors to the model state. That is, you&#8217;ll see errors for the child object(s), but the errors for the parent object will not display until the child errors are cleared. This will probably require a deeper dive into the MVC3 source code to find out why.</li>
<li>If multiple errors are returned for the same property, only one is displayed in a single <span style="font-family:monospace">ValidationMessageFor()</span> call. This can be remedied with a ValidationSummary, but that may not fit within your design guidelines; also, if you intend to rate multiple menus on the same page, the ValidationSummary presents its own set of problems.</li>
</ul>
<p>If you&#8217;ve got solutions for these issues, let us know. Source code can be <a href="http://www.esenciadev.com/wp-content/uploads/2011/02/IValidatableObjectDemo.zip">downloaded here</a>.</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F&amp;title=Model+Validation+in+ASP.NET+MVC3" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F&amp;title=Model+Validation+in+ASP.NET+MVC3" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F&amp;title=Model+Validation+in+ASP.NET+MVC3" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F&amp;headline=Model+Validation+in+ASP.NET+MVC3" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Model+Validation+in+ASP.NET+MVC3&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Model+Validation+in+ASP.NET+MVC3&amp;u=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Model+Validation+in+ASP.NET+MVC3&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Model+Validation+in+ASP.NET+MVC3&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Model+Validation+in+ASP.NET+MVC3&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F&amp;title=Model+Validation+in+ASP.NET+MVC3&amp;summary=&amp;source=" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F02%2Fmodel-validation-in-asp-net-mvc3-2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.esenciadev.com/2011/02/model-validation-in-asp-net-mvc3-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting rid of Magic Strings in Entity Framework 4 Includes</title>
		<link>http://www.esenciadev.com/2011/01/getting-rid-of-magic-strings-in-entity-framework-4-includes/</link>
		<comments>http://www.esenciadev.com/2011/01/getting-rid-of-magic-strings-in-entity-framework-4-includes/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 16:30:44 +0000</pubDate>
		<dc:creator>Matt</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Entity Framework 4]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://www.esenciadev.com/?p=169</guid>
		<description><![CDATA[One way to optimize Entity Framework queries is to gather all the information you KNOW you will need at the time the query is executed, to avoid additional deferred queries. A common way of doing this is by using the .Include() method, which specifies additional tables/entities to be pulled at the time the query is [...]]]></description>
			<content:encoded><![CDATA[<p>One way to optimize Entity Framework queries is to gather all the information you KNOW you will need at the time the query is executed, to avoid additional deferred queries. A common way of doing this is by using the <a href="http://msdn.microsoft.com/en-us/library/bb738708.aspx" target="_blank">.Include()</a> method, which specifies additional tables/entities to be pulled at the time the query is run. There’s a minor problem with this; the .Include() method takes a string to indicate the objects to retrieve. This presents a significant problem for Agile developers, or any situation where your database or object schema is likely to undergo any significant amount of churn or refactoring. Consider the following excerpt from an Entity Framework 4 EDMX file, where we have a Job Entity and a parent JobType entity.</p>
<p><a href="http://www.esenciadev.com/wp-content/uploads/2011/01/edmx.png" class="highslide-image" onclick="return hs.expand(this);"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border: 0px" src="http://www.esenciadev.com/wp-content/uploads/2011/01/edmx_thumb.png" border="0" alt="edmx" width="274" height="255" /></a></p>
<p>When we retrieve a job and want to include the job type information as part of the same query, the initial implementation would look something like this.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #000080;color: #fff;font-family: Verdana, Tahoma, Arial, sans-serif;font-weight: bold;padding: 2px 5px">Not so hot</div>
<div style="background: #fff;overflow: auto">
<ol style="background: #ffffff;margin: 0;padding: 0 0 0 5px">
<li><span style="color: #2b91af">Job</span> job = entityContext.Jobs</li>
<li> .Include(<span style="color: #a31515">&#8220;JobType&#8221;</span>)</li>
<li> .SingleOrDefault(j =&gt; j.JobId == jobId);</li>
</ol>
</div>
</div>
</div>
<p>I don’t know about you, but the use of a magic string value to represent the parent table leaves me with a feeling of impending doom. If you decide to rename your parent entity to JobCategory, or introduce another entity between JobType and Job, <strong>your code will fail</strong> and you won’t catch it until execution time.</p>
<p>Magic strings are undergoing something of a renaissance in Microsoft technologies, and it’s a little disconcerting. <a href="http://www.asp.net/mvc" target="_blank">ASP.NET MVC</a> is riddled with them, and a group of like-minded developers have come up with the wonderful <a href="http://mvccontrib.codeplex.com/wikipage?title=T4MVC" target="_blank">T4MVC</a> template to eliminate or greatly reduce the need for these pesky buggers. It’s a tremendous boon to insulate your code against refactoring.</p>
<p>In our current project, we are using the <a href="http://msdn.microsoft.com/en-us/library/ff477604.aspx" target="_blank">ADO.NET Self-Tracking Entity Generator Template</a> to create entities that keep track of their own changes but which are ignorant of their storage mechanism. Our application server tier is implemented in WCF, and this template is well-suited to architectures where the consuming application and the application server are both .NET-based.</p>
<p>Eliminating the magic strings requires a minor modification to the T4 template that generates the entities. Our insertion begins after line 194 of this template, which ends the region that generates complex properties for our entities, and before navigation properties are generated. Here’s what we’re inserting.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #fff;overflow: auto">
<ol style="background: #ffffff;margin: 0;padding: 0 0 0 5px">
<li> region.Begin(&#8220;Include Reference Names&#8221;);</li>
<li>#&gt;</li>
<li> public static &lt;#=(entity.BaseType == null ? &#8220;&#8221; : &#8220;new &#8220;)#&gt;class IncludeReferences</li>
<li> {</li>
<li>&lt;#</li>
<li> foreach (NavigationProperty navProperty in entity.NavigationProperties.Where(np =&gt; np.DeclaringType == entity))</li>
<li> {</li>
<li>#&gt;</li>
<li> public static readonly string For&lt;#=code.Escape(navProperty)#&gt; = &#8220;&lt;#=code.Escape(navProperty)#&gt;&#8221;;</li>
<li>&lt;#</li>
<li> }</li>
<li>#&gt;</li>
<li> }</li>
<li>&lt;#</li>
<li> region.End();</li>
</ol>
</div>
</div>
</div>
<p>When T4 is run again, we get something like the following added to our entity definition for the Job class.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #fff;overflow: auto">
<ol style="background: #ffffff;margin: 0;padding: 0 0 0 5px">
<li><span style="color: #0000ff">#region</span> Include Reference Names</li>
<li><span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">class</span> <span style="color: #2b91af">IncludeReferences</span></li>
<li>{</li>
<li> <span style="color: #0000ff">public</span> <span style="color: #0000ff">static</span> <span style="color: #0000ff">readonly</span> <span style="color: #0000ff">string</span> ForJobType = <span style="color: #a31515">&#8220;JobType&#8221;</span>;</li>
<li>}</li>
<li></li>
<li><span style="color: #0000ff">#endregion</span></li>
</ol>
</div>
</div>
</div>
<p>A public static inner class is generated for each entity, allowing us to rewrite our EF query like so:</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #000080;color: #fff;font-family: Verdana, Tahoma, Arial, sans-serif;font-weight: bold;padding: 2px 5px">Feels Better</div>
<div style="background: #fff;overflow: auto">
<ol style="background: #ffffff;margin: 0;padding: 0 0 0 5px">
<li><span style="color: #2b91af">Job</span> job = entityContext.Jobs</li>
<li> .Include(<span style="color: #2b91af">Job</span>.<span style="color: #2b91af">IncludeReferences</span>.ForJobType)</li>
<li> .SingleOrDefault(j =&gt; j.JobId == jobId);</li>
</ol>
</div>
</div>
</div>
<p>Are the magic strings still there? Absolutely. But they’re defined in such a way that if your database schema or entity model change significantly, your code will break at compile time, which is vastly preferable to a run-time code bomb.</p>
<p>OK, what about those queries where we need to retrieve entities that are more than one level away? Consider the following additional excerpt from the EDMX. A job is at a location, and a location is tied to a state/province.</p>
<p><a href="http://www.esenciadev.com/wp-content/uploads/2011/01/edmx1.png" class="highslide-image" onclick="return hs.expand(this);"><img style="padding-left: 0px;padding-right: 0px;padding-top: 0px;border: 0px" src="http://www.esenciadev.com/wp-content/uploads/2011/01/edmx_thumb1.png" border="0" alt="edmx" width="431" height="285" /></a></p>
<p>No problem.</p>
<div class="wlWriterEditableSmartContent" style="margin: 0px;float: none;padding: 0px">
<div style="border: #000080 1px solid;color: #000;font-family: 'Courier New', Courier, Monospace;font-size: 10pt">
<div style="background: #fff;overflow: auto">
<ol style="background: #ffffff;margin: 0;padding: 0 0 0 5px">
<li><span style="color: #2b91af">Job</span> job = entityContext.Jobs</li>
<li> .Include(<span style="color: #2b91af">Job</span>.<span style="color: #2b91af">IncludeReferences</span>.ForJobType)</li>
<li> .Include(<span style="color: #2b91af">Job</span>.<span style="color: #2b91af">IncludeReferences</span>.ForLocation)</li>
<li> .Include(<span style="color: #2b91af">Job</span>.<span style="color: #2b91af">IncludeReferences</span>.ForLocation + <span style="color: #a31515">&#8220;.&#8221;</span> + <span style="color: #2b91af">Location</span>.<span style="color: #2b91af">IncludeReferences</span>.ForStateProvince)</li>
<li> .FirstOrDefault(j =&gt; j.JobId == jobId);</li>
</ol>
</div>
</div>
</div>
<p>This can now devolve into a heated debate vis-à-vis the relative merits of appending strings vs. <a href="http://msdn.microsoft.com/en-us/library/system.string.format.aspx" target="_blank">String.Format()</a> vs. <a href="http://msdn.microsoft.com/en-us/library/57a79xd0.aspx" target="_blank">String.Join()</a>. Nothing like bringing a gun to a knife-fight.</p>
<p><strong>FINAL NOTE:</strong></p>
<p>Hey, what’s with the “new”? Well, if you are using any sort of entity inheritance, your child entities will use the <strong>new</strong> keyword to mask any references from the parent class. This will come up if you are using either of the inheritance schemes available in EF4, which are table-per-hierarchy (<a href="http://msdn.microsoft.com/en-us/library/bb738443.aspx" target="_blank">TPH</a>) and table-per-type (<a href="http://msdn.microsoft.com/en-us/library/bb738685.aspx" target="_blank">TPT</a>). If you are using TPT, be aware that there are <a href="http://samscode.com/index.php/2010/01/the-entity-framework-v1-and-v4-deal-breaker-tpt-inheritance/" target="_blank">significant performance considerations</a>.</p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F&amp;title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F&amp;title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F&amp;title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F&amp;headline=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;u=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F&amp;title=Getting+rid+of+Magic+Strings+in+Entity+Framework+4+Includes&amp;summary=&amp;source=" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.esenciadev.com%2F2011%2F01%2Fgetting-rid-of-magic-strings-in-entity-framework-4-includes%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.esenciadev.com/2011/01/getting-rid-of-magic-strings-in-entity-framework-4-includes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Dependency Injected Action Filters in ASP.NET MVC2</title>
		<link>http://www.esenciadev.com/2010/05/dependency-injected-action-filters-in-asp-net-mvc2/</link>
		<comments>http://www.esenciadev.com/2010/05/dependency-injected-action-filters-in-asp-net-mvc2/#comments</comments>
		<pubDate>Thu, 06 May 2010 18:25:01 +0000</pubDate>
		<dc:creator>ryan</dc:creator>
				<category><![CDATA[Software Development]]></category>
		<category><![CDATA[ASP.NET MVC2]]></category>
		<category><![CDATA[DI]]></category>

		<guid isPermaLink="false">http://www.esenciadev.com/?p=93</guid>
		<description><![CDATA[On one of our current projects utilizing all the latest Microsoft has to offer (MVC2, EF4, Unity, .NET 4) we found ourselves creating a number of Action Filters for encapsulating often used behavior, such as Auditing, Authorization, and temp data management. Action filters are an incredibly powerful tool in MVC, capable of manipulating any piece [...]]]></description>
			<content:encoded><![CDATA[<p>On one of our current projects utilizing all the latest Microsoft has to offer (MVC2, EF4, Unity, .NET 4) we found ourselves creating a number of <a title="Action Filters" href="http://msdn.microsoft.com/en-us/library/dd410056(VS.90).aspx" target="_blank">Action Filters</a> for encapsulating often used behavior, such as Auditing, Authorization, and temp data management. Action filters are an incredibly powerful tool in MVC, capable of manipulating any piece of the request/response and making that behavior easy to reuse. The problem with Action Filters, on the surface, is that there is no immediately apparent method of injecting dependencies into those filters &#8211; they&#8217;re just attributes on a method in your controller, or on the class of the controller itself, such as below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>Authorized<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> WidgetController <span style="color: #008000;">:</span> MyControllerBase
<span style="color: #008000;">&#123;</span>
 <span style="color: #008000;">&#91;</span>Audit<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Doing something&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>
 <span style="color: #0600FF; font-weight: bold;">public</span> ActionResult DoSomething<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
 <span style="color: #008000;">&#123;</span>
 <span style="color: #008000;">...</span>
 <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In the case where your attribute has dependencies that should be resolved by your DI container, you may find yourself manually resolving those dependencies every time, which can get tedious and error prone. The answer to this lies in the Controller, but first we need a little background on how the Action Filters are actually executed.</p>
<p>When the MVC routing system finds the Controller for the current request, it uses an instance of that controller create to an ActionInvoker, which will be used in executing the action(s) on the controller. This <a title="ControllerActionInvoker" href="http://aspnet.codeplex.com/sourcecontrol/network/Show?projectName=aspnet&amp;changeSetId=23011#266452" target="_blank">ControllerActionInvoker</a> is responsible for finding the appropriate action given the route on that controller, as well as invoking the action AND the actions filters. Since the ControllerActionInvoker is responsible for actually creating instances of the Filters, it&#8217;s the ideal location to put code responsible for building up the dependencies of any Filters on your action methods. With a minimal amount of code, we should be able to usurp the ActionFilter creation process and inject our dependencies before the filter executes.</p>
<p>First, we&#8217;ll need a DI wrapper. The one below is a snippet from mine which acts as a shell around Unity:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">class</span> ServiceResolver
<span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">static</span> T InjectDependencies<span style="color: #008000;">&#40;</span>T instance<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">&#40;</span>T<span style="color: #008000;">&#41;</span>_container<span style="color: #008000;">.</span><span style="color: #0000FF;">BuildUp</span><span style="color: #008000;">&#40;</span>instance<span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>, instance<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
 <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now, the custom action invoker, which for these purposes only needs to override GetFilters(&#8230;), since this is the method responsible for getting the filters on a given Action:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> MyActionInvoker <span style="color: #008000;">:</span> ControllerActionInvoker
<span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> FilterInfo GetFilters<span style="color: #008000;">&#40;</span>ControllerContext controllerContext, 
            ActionDescriptor actionDescriptor<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var filters <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">base</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetFilters</span><span style="color: #008000;">&#40;</span>controllerContext, actionDescriptor<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            filters<span style="color: #008000;">.</span><span style="color: #0000FF;">ActionFilters</span><span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">ForEach</span><span style="color: #008000;">&#40;</span>
               f <span style="color: #008000;">=&gt;</span> ServiceResolver<span style="color: #008000;">.</span><span style="color: #0000FF;">InjectDependencies</span><span style="color: #008000;">&#40;</span>f<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            filters<span style="color: #008000;">.</span><span style="color: #0000FF;">AuthorizationFilters</span><span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">ForEach</span><span style="color: #008000;">&#40;</span>
               f <span style="color: #008000;">=&gt;</span> ServiceResolver<span style="color: #008000;">.</span><span style="color: #0000FF;">InjectDependencies</span><span style="color: #008000;">&#40;</span>f<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            filters<span style="color: #008000;">.</span><span style="color: #0000FF;">ExceptionFilters</span><span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">ForEach</span><span style="color: #008000;">&#40;</span>
               f <span style="color: #008000;">=&gt;</span> ServiceResolver<span style="color: #008000;">.</span><span style="color: #0000FF;">InjectDependencies</span><span style="color: #008000;">&#40;</span>f<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            filters<span style="color: #008000;">.</span><span style="color: #0000FF;">ResultFilters</span><span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">ForEach</span><span style="color: #008000;">&#40;</span>
               f <span style="color: #008000;">=&gt;</span> ServiceResolver<span style="color: #008000;">.</span><span style="color: #0000FF;">InjectDependencies</span><span style="color: #008000;">&#40;</span>f<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> filters<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Note that we iterate over all the different filter collections that are returned as a result of the call to base.GetFilters(&#8230;). This ensures that any filters we create for any part of the action process will have dependencies resolved. Now you need to make sure your custom ActionInvoker is used any time MVC is trying to invoke an action on your controllers, so you&#8217;ll need a common base Controller class that <strong>all</strong> of your controllers will inherit from.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> abstract <span style="color: #6666cc; font-weight: bold;">class</span> MyControllerBase <span style="color: #008000;">:</span> Controller
<span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">protected</span> <span style="color: #0600FF; font-weight: bold;">override</span> IActionInvoker CreateActionInvoker<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> MyActionInvoker<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Now any ActionFilters which have property-based dependencies will be automatically fulfilled by the new ActionInvoker, such as the AuditAttribute show below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> AuditAttribute <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span></span><span style="color: #008000;">.</span><span style="color: #0000FF;">Mvc</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ActionFilterAttribute</span>
<span style="color: #008000;">&#123;</span>
        <span style="color: #008000;">&#91;</span>Dependency<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> IUserRepository UserRepository <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#91;</span>Dependency<span style="color: #008000;">&#93;</span>
        <span style="color: #0600FF; font-weight: bold;">public</span> ILogger Logger <span style="color: #008000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F&amp;title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F&amp;title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F&amp;title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F&amp;headline=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;u=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F&amp;title=Dependency+Injected+Action+Filters+in+ASP.NET+MVC2&amp;summary=&amp;source=" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.esenciadev.com%2F2010%2F05%2Fdependency-injected-action-filters-in-asp-net-mvc2%2F" target="_blank"><img class="lightsocial_img" src="http://www.esenciadev.com/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div>]]></content:encoded>
			<wfw:commentRss>http://www.esenciadev.com/2010/05/dependency-injected-action-filters-in-asp-net-mvc2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

