<?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>blog.jorrit salverda.nl</title>
	<atom:link href="http://blog.jorritsalverda.nl/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jorritsalverda.nl</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 06:12:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>MSBuild-by-Convention</title>
		<link>http://blog.jorritsalverda.nl/2012/05/18/msbuild-by-convention/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=msbuild-by-convention</link>
		<comments>http://blog.jorritsalverda.nl/2012/05/18/msbuild-by-convention/#comments</comments>
		<pubDate>Fri, 18 May 2012 06:12:18 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=458</guid>
		<description><![CDATA[I&#8217;ve recently open sourced a set of build scripts on Github to assist you in automating compilation, running tests, creating release artifacts and deploying those artifacts for .NET development: https://github.com/JorritSalverda/msbuild-by-convention In this article I describe how to use them on your workstation, in your Continuous Integration/Delivery server and what parts still need a bit more attention. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently open sourced a set of build scripts on Github to assist you in automating compilation, running tests, creating release artifacts and deploying those artifacts for .NET development:</p>
<blockquote><p><a title="https://github.com/JorritSalverda/msbuild-by-convention" href="https://github.com/JorritSalverda/msbuild-by-convention" target="_blank">https://github.com/JorritSalverda/msbuild-by-convention</a></p></blockquote>
<p>In this article I describe how to use them on your workstation, in your Continuous Integration/Delivery server and what parts still need a bit more attention.</p>
<h2>What are the goals?</h2>
<ul>
<li>To be able to set up a new project with as little effort as possible to avoid having any projects that live without CI, because of the lack of time to set it up. To reduce setup time the scripts favor convention over configuration.</li>
<li>To be able to run all actions equally well from your workstation as from the build server.</li>
</ul>
<h2>What does it automate for you?</h2>
<p>The scripts are continuously improving, currently they do quite a lot:</p>
<p><em><strong>Compilation</strong></em></p>
<ul>
<li>Versions all your compiled assemblies with parameter BuildVersion, which needs a major.minor.build.revision (1.5.13.859 for example) version number.</li>
<li>For both MVC and WebForms applications it compiles views using AspNetCompiler.</li>
<li>Outputs your generated assemblies to a set directory, so solutions can reference assemblies generated in another solution within the same repository.</li>
</ul>
<p><em><strong>Testing</strong></em></p>
<ul>
<li>Runs test created with both NUnit and Machine.Specification.</li>
<li>Runs JMeter tests.</li>
</ul>
<p><em><strong>Creating release artifacts</strong></em></p>
<ul>
<li>Minifies CSS and Javascript grouped per directory with YUI Compressor and versions the filename to avoid any caching issues after deploy.</li>
<li>Compiles Flash with Flex, outputs it to your web project and versions the filename.</li>
<li>Applies config transforms for any config file (where the original is called [a-z]+.config and the transform [a-z]+.[a-z]+.config).</li>
<li>Creates artifacts for each environment you have a config transform for.</li>
<li>Updates filenames with 1.0.0.0 in them to reflect the build version to avoid caching issues and updates all references to them in css and js.</li>
<li>Precompiles asp.net websites.</li>
<li>Removes any files that shouldn&#8217;t be part of the release.</li>
<li>Optimizes pngs.</li>
<li>Optimizes jpegs.</li>
</ul>
<p><em><strong>Deploying release artifacts</strong></em></p>
<ul>
<li>Deploys websites using MSDeploy.</li>
<li>Deploys database projects.</li>
<li>Deploys data-tier-applications (supported by Azure).</li>
<li>Deploys Azure packages to staging, then swaps to production and removing staging afterwards; which of these steps is executed can be parameterized.</li>
</ul>
<p><em><strong>Various</strong></em></p>
<ul>
<li>Delete Azure instances.</li>
<li>Analyze code using FXCop.</li>
</ul>
<p>Which actions are taken for what projects is automatically handled by sticking to the project naming conventions. More about these below.</p>
<p>Read on to learn how the build files are structured, how to use them and how to configure them in your favorite CI server.</p>
<p><span id="more-458"></span></p>
<h2>Structure</h2>
<p>The project has the following MSBuild files:</p>
<ol>
<li>properties-convention-based.msbuild</li>
<li>properties-repository-specific.msbuild</li>
<li>targets.msbuild</li>
<li>targets-repository-specific.msbuild</li>
</ol>
<p>The first and third are the ones that continuously get improved so are best left untouched after you first start using them except for updating them to the newest version; the second and fourth allow you to override any defaults as defined in the other two files and have no need to be updated to the newest version.</p>
<p>The other scripts used from targets.msbuild are</p>
<ul>
<li>AzureDelete.ps1</li>
<li>AzureDeploy.ps1</li>
<li>DacDeploy.ps1</li>
</ul>
<p>If you inspect <em>properties-convention-based.msbuild</em> you can see that the directory structure as used in the repository is defined there and that the following conventions for project names are used:</p>
<ul>
<li>*.<strong>Website</strong>.csproj</li>
<li>*.<strong>WebService</strong>.csproj</li>
<li>*.<strong>Console</strong>.csproj</li>
<li>*.<strong>Service</strong>.csproj</li>
<li>*.<strong>Database</strong>.dbproj</li>
<li>*.<strong>Worker</strong>.csproj</li>
<li>*.<strong>Azure</strong>.ccproj</li>
<li>*.<strong>UnitTests</strong>.csproj</li>
<li>*.<strong>IntegrationTests</strong>.csproj</li>
</ul>
<p>For the location of your css and javascript within a Website project the following conventions are used:</p>
<ul>
<li><strong>static\css</strong></li>
<li><strong>static\js</strong></li>
</ul>
<p>Within these directories the contents of each sub-directory will be merged and minified. In the case of css the resulting file is stored in the sub-directory (so all relative paths stay intact), for javascript it&#8217;s stored in the static/js directory.</p>
<p>Any of the conventions can be overridden, this is best done in the <em>properties-repository-specific.msbuild </em>file, so you can still easily update properties-convention-based.msbuild and targets.msbuild to the newest version.</p>
<h2>Getting started</h2>
<p>To get this stuff on the road the following steps need to be taken:</p>
<ol>
<li>Make sure you have Visual Studio 2010 SP1 installed.</li>
<li>Fork <a title="https://github.com/JorritSalverda/msbuild-by-convention" href="https://github.com/JorritSalverda/msbuild-by-convention" target="_blank">https://github.com/JorritSalverda/msbuild-by-convention</a> or download as a zip and extract to your repository.</li>
<li>Get at least the following tools and add their files in the respective /Build/Tools/ sub-directory:</li>
<li>Compile &#8211; MSBuild.Community.Tasks.v1.2.0.306</li>
<li>Compile - MSBuild.ExtensionPack.Binaries.v4.0.2.0</li>
<li>Run unit/integration tests &#8211; NUnit-2.6.0.12051</li>
<li>Run unit/integration tests - Machine.Specifications.0.5.6.0</li>
<li>Create release - Yahoo.Yui.Compressor.v1.6.0.2</li>
<li>Create release - optipng-0.7.1-win32</li>
<li>Create release - Jpegtran</li>
<li>Create release - VS2010WebPublishing</li>
<li>Create release - Windows.Azure.Tools.v1.6</li>
<li>Deploy vs2010 studio database projects - Vs2010DbCmd</li>
<li>Deploy data-tier applications - SqlPowershell-10.50.1600.1</li>
<li>Deploy websites via MSDeploy - MsDeploy.v2</li>
<li>Deploy websites to Azure &#8211; install Azure powershell commandlets.</li>
<li>Run Jmeter tests - apache-jmeter-2.6</li>
<li>Analyze code quality - FxCop.v10.0</li>
</ol>
<p>I&#8217;ll soon check which of these tools can be included in the repository without being in conflict with their license in order to avoid step 3 and following.</p>
<p>Deploying to Azure and deploying data-tier applications both use Powershell scripts. As these aren&#8217;t signed they would normally be blocked for execution. To enable unsigned scripts to be executed start the Powershell and run the following command:</p>
<blockquote><p>set-executionpolicy unrestricted</p></blockquote>
<p>This does put your machine at risk, but it&#8217;s currently the only way I know how to enable the execution of those scripts.</p>
<h2>Running the scripts</h2>
<p>Okay, after all this work it is time to really get started. From a visual studio command line navigate to the /Build/Scripts/ directory and use the following commands.</p>
<p>To <strong>compile</strong> all solutions in the /Source/Csharp/ directory and subdirectories perform the following command:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:Build</p></blockquote>
<p>To run all <strong>unit test</strong> projects:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:RunUnitTests</p></blockquote>
<p>To <strong>create release</strong> artifacts for all your projects in the /Build/Releases/ directory:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:Release</p></blockquote>
<p>To run all <strong>integration test</strong> projects:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:RunIntegrationTests</p></blockquote>
<p>To <strong>deploy VS2010 database projects</strong> or <strong>Data-Tier Applications</strong>:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:Deploy /p:ReleaseConfiguration=&#8221;PROD&#8221; /p:ProjectToDeploy=&#8221;Projectname.Database&#8221; /p:DeployServer=&#8221;database-server-name&#8221; /p:DeployTargetName=&#8221;database-name&#8221; /p:DeployUsername=&#8221;db-admin-name&#8221; /p:DeployPassword=&#8221;db-admin-password&#8221;</p></blockquote>
<p>To <strong>deploy a website with MSDeploy</strong> to an IIS server:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:Deploy /p:ReleaseConfiguration=&#8221;ACC&#8221; /p:ProjectToDeploy=&#8221;Projectname.Website&#8221; /p:DeployServer=&#8221;iis-server-name&#8221; /p:DeployTargetName=&#8221;iis-website-name&#8221; /p:DeployUsername=&#8221;deploy-user-name&#8221; /p:DeployPassword=&#8221;deploy-user-password&#8221;</p></blockquote>
<p>To <strong>deploy an Azure web role</strong> or worker role:</p>
<blockquote><p>msbuild.exe targets.msbuild /t:Deploy /p:DeployEnvironment=&#8221;PROD&#8221; /p:ProjectToDeploy=&#8221;Projectname.Azure&#8221; /p:AzureSubscriptionID=&#8221;subscription-id&#8221; /p:AzureCertificatePassword=&#8221;management-certificate-password&#8221; /p:AzureHostedServiceName=&#8221;hosted-service-name&#8221; /p:AzureStorageAccountName=&#8221;storage-account-name&#8221; /p:AzureSwapToProductionAfterDeploy=&#8221;True&#8221; /p:AzureRemoveStagingAfterSwap=&#8221;True&#8221; /p:AzureDisallowMultipleActiveInstances=&#8221;False&#8221;</p></blockquote>
<p>To enable deployments to Azure you need to store a management certificate at /Build/Scripts/AzureManagementCertificate.pfx. The RunUnitTests and Release targets depend on the Build target being executed; the Deploy targets depend on the Release target. With these separate commands you can easily set up a pipeline within your CI server.</p>
<h2>Setting up a Continuous Delivery pipeline</h2>
<p>A possible pipeline set up can look like the one pictured below.</p>
<p style="text-align: center;"><a href="http://blog.jorritsalverda.nl/wp-content/uploads/2012/05/continuous-delivery-pipeline.png"><img class="aligncenter  wp-image-467" title="continuous-delivery-pipeline" src="http://blog.jorritsalverda.nl/wp-content/uploads/2012/05/continuous-delivery-pipeline.png" alt="" width="672" height="504" /></a></p>
<p>To implement this you would call the following targets and actions:</p>
<p><strong><em>1 Compile</em></strong></p>
<ul>
<li>target: Build</li>
</ul>
<p><strong><em>2 Run unit tests</em></strong></p>
<ul>
<li>target: RunUnitTests</li>
</ul>
<p><strong><em>3 Create release</em></strong></p>
<ul>
<li>target: Release</li>
<li>save Release artifacts from directory /Build/Releases/</li>
</ul>
<p><strong><em>4 Deploy to INTEGRATION + run integration tests</em></strong></p>
<ul>
<li>fetch Release artifacts</li>
<li>target: Deploy for database</li>
<li>target: Deploy for website (using MSDeploy or deploy to Azure)</li>
<li>target: RunIntegrationTests</li>
<li>target: RunJMeterTests</li>
</ul>
<p><strong><em>5 Deploy to ACCEPTANCE</em></strong></p>
<ul>
<li>fetch Release artifacts</li>
<li>target: Deploy for database</li>
<li>target: Deploy for website (using MSDeploy or deploy to Azure)</li>
</ul>
<p><strong><em>6 Deploy to PRODUCTION</em></strong></p>
<ul>
<li>fetch Release artifacts</li>
<li>target: Deploy for database</li>
<li>target: Deploy for website (using MSDeploy or deploy to Azure)</li>
</ul>
<p>When you set this up in Teamcity you would like to make sure the separate steps have a snapshot dependency on the previous step, the same version number is used for every step (use %dep&#8230; as version number, after setting up the snapshot dependency) and the steps that use the Release artifacts have an artifact dependency to step 3.</p>
<p>In Bamboo you have no such thing as a snapshot dependency, so in that case I save the whole working copy as an artifact in step 1 and have every following step import this artifact. From step 3 and further it also has a dependency on the Release artifact.</p>
<p>Where Teamcity and CruiseControl automatically pass their version numbers to the scripts in Bamboo you have to do this explicitly by adding the following parameter:</p>
<blockquote><p>/p:BuildVersion=1.0.0.${bamboo.buildNumber}</p></blockquote>
<h2>What needs to be improved?</h2>
<p>Of course there are still a lot of improvements on the wish list:</p>
<ul>
<li>Reduce the &#8216;getting started&#8217; to 2 steps by adding the necessary /Build/Tools to the repository where their respective licenses allow for that.</li>
<li>Remove the need for Visual Studio and SQL Server to be installed on a build agent.</li>
<li>Support Robocopy.</li>
<li>Handle first time deploy to Azure, not needing a first manual deploy.</li>
<li>Deploy certificates to Azure.</li>
<li>Add Selenium testing.</li>
<li>Make it more extendable.</li>
<li>Determine code coverage.</li>
</ul>
<p>Let me know if any parts of the setup are unclear so I can document them into more depth. I can also provide you with the /Build/Tools directory zipped up, until I&#8217;ve figured that out, license-wise.</p>
<p>Cheers, Jorrit</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2012/05/18/msbuild-by-convention/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC: Binding</title>
		<link>http://blog.jorritsalverda.nl/2010/03/16/maintainable-mvc-binding/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-binding</link>
		<comments>http://blog.jorritsalverda.nl/2010/03/16/maintainable-mvc-binding/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 22:17:49 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=360</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. By using the form models as spoken about in View Model and Form Model the need for custom binding doesn&#8217;t arise to often anymore. But every now and then we have some duplicate code doing something with incoming parameters. Perhaps we can move this logic into [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>By using the <em>form models</em> as spoken about in <a href="http://blog.jorritsalverda.nl/2010/03/03/maintainable-mvc-series-viewmodel-and-formmodel/">View Model and Form Model</a> the need for custom binding doesn&#8217;t arise to often anymore.</p>
<p>But every now and then we have some duplicate code doing something with incoming parameters. Perhaps we can move this logic into a binder to be more DRY. Or if our form model has types that MVC can&#8217;t bind automatically &#8211; like enumerations &#8211; custom binding comes into play.</p>
<p>MVC is extensible on the part of binding form data or get parameters to your method parameters. You can define your own binders and have them work for certain types.</p>
<p><span id="more-360"></span></p>
<h2>SmartBinder</h2>
<p>Jimmy Bogard wrote a very helpful class called SmartBinder, which you can read all about <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/11/19/a-better-model-binder-addendum.aspx" target="_blank">over here</a>. We use it for all our custom binders. You can see the neccessary code below:</p>
<pre class="brush: csharp; title: ; notranslate">
public interface IFilteredModelBinder : IModelBinder
{
	bool IsMatch(Type modelType);

	new BindResult BindModel(ControllerContext controllerContext,
							 ModelBindingContext bindingContext);
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
public class SmartBinder : DefaultModelBinder
{
	private readonly IFilteredModelBinder[] filteredModelBinders;

	public SmartBinder(IFilteredModelBinder[] filteredModelBinders)
	{
		this.filteredModelBinders = filteredModelBinders;
	}

	public override object BindModel(ControllerContext controllerContext,
									 ModelBindingContext bindingContext)
	{
		foreach (var filteredModelBinder in filteredModelBinders)
		{
			if (filteredModelBinder.IsMatch(bindingContext.ModelType))
			{
				BindResult result = filteredModelBinder.BindModel(controllerContext,
																  bindingContext);
				bindingContext.ModelState.SetModelValue(bindingContext.ModelName,
														result.ValueProviderResult);

				return result.Value;
			}
		}

		return base.BindModel(controllerContext, bindingContext);
	}
}
</pre>
<pre class="brush: csharp; title: ; notranslate">
public class BindResult
{
	public object Value { get; private set; }

	public ValueProviderResult ValueProviderResult { get; private set; }

	public BindResult(object value, ValueProviderResult valueProviderResult)
	{
		Value = value;
		ValueProviderResult = valueProviderResult ??
								new ValueProviderResult(null,
														string.Empty,
														CultureInfo.CurrentCulture);
	}
}
</pre>
<h2>Setting it up with StructureMap</h2>
<p>To have MVC use this SmartBinder as the default binder we add the following line to the Application_Start method in the global.asax.cs:</p>
<pre class="brush: csharp; light: true; title: ; notranslate">
ModelBinders.Binders.DefaultBinder = ObjectFactory.GetInstance&lt;SmartBinder&gt;();
</pre>
<p>And for setting up the list of binders implementing the <em>IFilteredModelBinder</em> interface neccessary for them to work from within the <em>SmartBinder</em> we add the following StructureMap registry:</p>
<pre class="brush: csharp; title: ; notranslate">
public class BinderRegistry : Registry
{
	public BinderRegistry()
	{
		For&lt;IFilteredModelBinder&gt;().Add&lt;EnumBinder&lt;SomeEnumeration&gt;&gt;()
		 .Ctor&lt;SomeEnumeration&gt;().Is(SomeEnumeration.FirstValue);
		For&lt;IFilteredModelBinder&gt;().Add&lt;EnumBinder&lt;AnotherEnumeration&gt;&gt;()
		 .Ctor&lt;AnotherEnumeration&gt;().Is(AnotherEnumeration.FifthValue);
	}
}
</pre>
<p>Because the SmartBinder is instantiated with <em>ObjectFactory.GetInstance&lt;SmartBinder&gt;()</em> and it expects an array of IFilteredModelBinders, the <em>For&lt;IFilteredModelBinder&gt;().Add&lt;&#8230;&gt;()</em> makes sure StructureMap returns all defined binders if an IEnumerable of IFilteredModelBinder is needed for instantiating a class.</p>
<p>For a simple example of an IFilteredModelBinder I&#8217;ll show you the very useful EnumBinder.</p>
<h2>EnumBinder</h2>
<p>For binding enumerations Rupert Bates has this <a href="http://eliasbland.wordpress.com/2009/08/08/enumeration-model-binder-for-asp-net-mvc/" target="_blank">custom binder</a>, which<br />
looks as follows when having it implement the IFilteredModelBinder interface:</p>
<pre class="brush: csharp; title: ; notranslate">
public class EnumBinder&lt;T&gt; : DefaultModelBinder, IFilteredModelBinder
{
	private readonly T defaultValue;

	public EnumBinder(T defaultValue)
	{
		this.defaultValue = defaultValue;
	}

	public bool IsMatch(Type modelType)
	{
		return modelType == typeof (T);
	}

	BindResult IFilteredModelBinder.BindModel(ControllerContext controllerContext,
											  ModelBindingContext bindingContext)
	{
		T result = bindingContext.ValueProvider[bindingContext.ModelName] == null
					? defaultValue
					: GetEnumValue(defaultValue,
				bindingContext.ValueProvider[bindingContext.ModelName].AttemptedValue);

		return new BindResult(result, null);
	}

	private static T GetEnumValue(T defaultValue, string value)
	{
		T enumType = defaultValue;

		if ((!String.IsNullOrEmpty(value)) &amp;&amp; (Contains(typeof (T), value)))
		{
			enumType = (T) Enum.Parse(typeof (T), value, true);
		}

		return enumType;
	}

	private static bool Contains(Type enumType, string value)
	{
		return Enum.GetNames(enumType).Contains(value,
												StringComparer.OrdinalIgnoreCase);
	}
}
</pre>
<p>For <strong>MVC 2</strong> the EnumBinder looks a bit different:</p>
<pre class="brush: csharp; highlight: [19,22]; title: ; notranslate">
public class EnumBinder&lt;T&gt; : DefaultModelBinder, IFilteredModelBinder
{
	private readonly T defaultValue;

	public EnumBinder(T defaultValue)
	{
		this.defaultValue = defaultValue;
	}

	public bool IsMatch(Type modelType)
	{
		return modelType == typeof(T);
	}

	BindResult IFilteredModelBinder.BindModel(ControllerContext controllerContext,
											  ModelBindingContext bindingContext)
	{
		T result =
			bindingContext.ValueProvider.GetValue(bindingContext.ModelName) == null
			? defaultValue
			: GetEnumValue(defaultValue,
		bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue);

		return new BindResult(result, null);
	}

	private static T GetEnumValue(T defaultValue, string value)
	{
		T enumType = defaultValue;

		if ((!String.IsNullOrEmpty(value)) &amp;&amp; (Contains(typeof(T), value)))
		{
			enumType = (T)Enum.Parse(typeof(T), value, true);
		}

		return enumType;
	}

	private static bool Contains(Type enumType, string value)
	{
		return Enum.GetNames(enumType).Contains(value,
												StringComparer.OrdinalIgnoreCase);
	}
}
</pre>
<p>We don&#8217;t have to explicitly add the binder in Application_Start like Rupert does, because StructureMap handles it for us through the BinderRegistry.</p>
<h2>Testing the binder</h2>
<p>Of course testing the binder is hard again, because of the ControllerContext and ModelBindingContext, but it can be done with the following code:</p>
<pre class="brush: csharp; title: ; notranslate">
[TestFixture]
public class EnumBinderTests
{
	private IFilteredModelBinder binder;

	[SetUp]
	public void Setup()
	{
		binder = new EnumBinder&lt;TestEnum&gt;(TestEnum.ValueB);
	}

	[Test]
	public void IsMatchShouldReturnTrueIfTypeIsSameAsGenericType()
	{
		// act
		bool isMatch = binder.IsMatch(typeof(TestEnum));

		// assert
		Assert.That(isMatch, Is.True);
	}

	[Test]
	public void IsMatchShouldReturnFalseIfTypeIsNotSameAsGenericType()
	{
		// act
		bool isMatch = binder.IsMatch(typeof(string));

		// assert
		Assert.That(isMatch, Is.False);
	}

	[Test]
	public void BindModelShouldReturnEnumValueForWhichValueAsStringIsPosted()
	{
		// arrange
		ControllerContext controllerContext = GetControllerContext();
		ModelBindingContext bindingContext = GetModelBindingContext(
									new ValueProviderResult(null, &quot;ValueA&quot;, null));

		// act
		BindResult bindResult = binder.BindModel(controllerContext, bindingContext);

		// assert
		Assert.That(bindResult.Value, Is.EqualTo(TestEnum.ValueA));
	}

	[Test]
	public void BindModelShouldReturnDefaultValueIfNoValueIsPosted()
	{
		// arrange
		ControllerContext controllerContext = GetControllerContext();
		ModelBindingContext bindingContext = GetModelBindingContext(null);

		// act
		BindResult bindResult = binder.BindModel(controllerContext, bindingContext);

		// assert
		Assert.That(bindResult.Value, Is.EqualTo(TestEnum.ValueB));
	}

	[Test]
	public void BindModelShouldReturnDefaultValueIfUnknownValueIsPosted()
	{
		// arrange
		ControllerContext controllerContext = GetControllerContext();
		ModelBindingContext bindingContext = GetModelBindingContext(
									new ValueProviderResult(null, &quot;Unknown&quot;, null));

		// act
		BindResult bindResult = binder.BindModel(controllerContext, bindingContext);

		// assert
		Assert.That(bindResult.Value, Is.EqualTo(TestEnum.ValueB));
	}

	[Test]
	public void BindModelShouldReturnDefaultValueIfDefaultValueAsStringIsPosted()
	{
		// arrange
		ControllerContext controllerContext = GetControllerContext();
		ModelBindingContext bindingContext = GetModelBindingContext(
									new ValueProviderResult(null, &quot;ValueB&quot;, null));

		// act
		BindResult bindResult = binder.BindModel(controllerContext, bindingContext);

		// assert
		Assert.That(bindResult.Value, Is.EqualTo(TestEnum.ValueB));
	}

	private static ControllerContext GetControllerContext()
	{
		return new ControllerContext
			{
				HttpContext = MockRepository.GenerateMock&lt;HttpContextBase&gt;()
			};
	}

	private static ModelBindingContext GetModelBindingContext(
										ValueProviderResult valueProviderResult)
	{
		ValueProviderDictionary dictionary = new ValueProviderDictionary(null)
		{
			{&quot;enum&quot;, valueProviderResult}
		};

		return new ModelBindingContext
			{
				ModelName = &quot;enum&quot;,
				ValueProvider = dictionary
			};
	}
}

public enum TestEnum
{
	ValueA,
	ValueB
}
</pre>
<p>You&#8217;ll probably want to make some shared methods in a unit test library for mocking different types of contexts, because you&#8217;ll need them often when testing an attribute or binder.</p>
<p>If your custom binder has some dependencies it&#8217;s also useful to do the unit test setup with AutoMocker, as shown in <em><a href="http://blog.jorritsalverda.nl/2010/03/08/maintainable-mvc-series-poor-man%E2%80%99s-renderaction/">Poor Man&#8217;s RenderAction</a></em>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/03/16/maintainable-mvc-binding/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC: Post-Redirect-Get pattern</title>
		<link>http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-post-redirect-get-pattern</link>
		<comments>http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 20:47:49 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[MvcContrib]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=311</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. It keeps amazing me that every time I see some example MVC code from Scott Guthrie, Phil Haack or one of our other MVC heroes, it keeps looking like this: The big problem with this code is that it returns a view (on the highlighted line), [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>It keeps amazing me that every time I see some example MVC code from Scott Guthrie, Phil Haack or one of our other MVC heroes, it keeps looking like this:</p>
<pre class="brush: csharp; highlight: [10]; title: ; notranslate">
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(BlogItem blogItem)
{
	if (ModelState.IsValid)
	{
		...
		return RedirectToAction(&quot;OtherAction&quot;);
	}

	return View(blogItem);
}
</pre>
<p>The big problem with this code is that it returns a view (on the highlighted line), while the method handles a POST. It seems like a very bad practice, because it disrupts the natural flow of your website. It makes it impossible to make use of your browser history (the back button) without running into a <em>&#8216;this page is expired&#8217;</em> warning. Or your user could post the same data multiple times.</p>
<p>It is an annoyance which will definitely cost your website some visitors! So no more <em>return View</em> in a post method!</p>
<p><span id="more-311"></span></p>
<p>The simple pattern that makes these warnings something of the past is the <em>Post-Redirect-Get</em> pattern (PRG); it just states that a post should always be followed by a browser redirect.</p>
<pre class="brush: csharp; title: ; notranslate">
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(BlogItem blogItem)
{
	if (ModelState.IsValid)
	{
		...
		return RedirectToAction(&quot;OtherAction&quot;);
	}

	return RedirectToAction(&quot;Create&quot;);
}
</pre>
<p>If it is this simple, why do the MVC gurus return a view in their example? Well, to keep your form filled with the input the user just entered and to show the validation errors, after a redirect, takes a little extra effort. By default, MVC doesn&#8217;t remember your ModelState from one request to the next.</p>
<p>To make sure the ModelState is ported to the next request we use the <em>ModelStateToTempDataAttribute</em> from the <a href="http://www.codeplex.com/MVCContrib">MvcContrib project</a>. If a controller is decorated with this attribute you no longer have to worry about showing validation errors in a form when using the PRG pattern.</p>
<h2>ModelStateToTempDataAttribute </h2>
<pre class="brush: csharp; title: ; notranslate">
public class ModelStateToTempDataAttribute : ActionFilterAttribute
{
	public const string TempDataKey = &quot;__MvcContrib_ValidationFailures__&quot;;

	public override void OnActionExecuted(ActionExecutedContext filterContext)
	{
		ModelStateDictionary modelState = filterContext.Controller.ViewData.ModelState;

		ControllerBase controller = filterContext.Controller;

		if(filterContext.Result is ViewResult)
		{
			// If there are failures in tempdata, copy them to the modelstate
			CopyTempDataToModelState(controller.ViewData.ModelState,
									 controller.TempData);
			return;
		}

		// If we're redirecting and there are errors, put them in tempdata instead
		// (so they can later be copied back to modelstate)
		if((filterContext.Result is RedirectToRouteResult
            || filterContext.Result is RedirectResult) &amp;&amp; !modelState.IsValid)
		{
			CopyModelStateToTempData(controller.ViewData.ModelState,
									 controller.TempData);
		}
	}

	private void CopyTempDataToModelState(ModelStateDictionary modelState,
										  TempDataDictionary tempData)
	{
		if(!tempData.ContainsKey(TempDataKey))
		{
			return;
		}

		ModelStateDictionary fromTempData = tempData[TempDataKey]
												as ModelStateDictionary;
		if(fromTempData == null)
		{
			return;
		}

		foreach(KeyValuePair&lt;string,ModelState&gt; pair in fromTempData)
		{
			if (modelState.ContainsKey(pair.Key))
			{
				modelState[pair.Key].Value = pair.Value.Value;

				foreach(ModelError error in pair.Value.Errors)
				{
					modelState[pair.Key].Errors.Add(error);
				}
			}
			else
			{
				modelState.Add(pair.Key, pair.Value);
			}
		}
	}

	private static void CopyModelStateToTempData(ModelStateDictionary modelState,
												 TempDataDictionary tempData)
	{
		tempData[TempDataKey] = modelState;
	}
}
</pre>
<p>The attribute only saves ModelState to TempData if there are validation errors. And if the next action returns a view, the ModelState is retrieved from TempData. TempData itself is a wrapper around Session-State in which objects are only present until the next request.</p>
<p>All we have to do now is to make use of this attribute is to apply it to each controller where needed:</p>
<pre class="brush: csharp; title: ; notranslate">
[ModelStateToTempData]
public HomeController : Controller
{
</pre>
<p>I&#8217;ve read some comments from people who want to have more control and split the attribute in one writing to TempData and the other retrieving it. But this leads to a proliferation of attributes throughout your code. I can&#8217;t think of single moment I ever had need for finer-grained control than just applying the one attribute to the controller as a whole.</p>
<h2>The drawback</h2>
<p>Of course there is one caveat for the use of this attribute. It saves data in TempData, which is saved in Session-State. If the sites you build run on multiple machines behind a load balancer you can&#8217;t handle subsequent requests by different machines, unless they share their Session-State.</p>
<p>For the smaller sites we choose to set the load balancer in <em>sticky</em> mode, so a user will be coupled to the same server during his/her session. In this case, having multiple servers doesn&#8217;t really increase availability, in that a user will still hit the same server after it has crashed.</p>
<p>For storing Session-State <a href="http://msdn.microsoft.com/en-us/library/ms178586.aspx">MSDN</a> shows us we have the following options:</p>
<ul>
<li><strong>InProc</strong> mode, which stores session state in memory on the Web server. This is the default.</li>
<li><strong>StateServer</strong> mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.</li>
<li><strong>SQLServer</strong> mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.</li>
<li><strong>Custom</strong> mode, which enables you to specify a custom storage provider.</li>
<li><strong>Off</strong> mode, which disables session state.</li>
</ul>
<p>If we don&#8217;t take the <em>sticky</em> road and need to share Session-State between multiple servers we&#8217;ll have to go for the <em>StateServer</em> or <em>SQLServer</em> option. Both necessitate that the items stored in session are serializable.</p>
<p>More on how we encapsulate Session-State in a later part.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC Series: Poor man’s RenderAction</title>
		<link>http://blog.jorritsalverda.nl/2010/03/08/maintainable-mvc-series-poor-man%e2%80%99s-renderaction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-poor-man%25e2%2580%2599s-renderaction</link>
		<comments>http://blog.jorritsalverda.nl/2010/03/08/maintainable-mvc-series-poor-man%e2%80%99s-renderaction/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 14:41:58 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[StructureMap]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=222</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. Soon &#8211; once that MVC 2 is finalized and released &#8211; we will have access to the new Html.Action command with which we can easily render partials for shared functionality, like navigation structure or other parts of the master page that need dynamic data. As Phil [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>Soon &#8211; once that MVC 2 is finalized and released &#8211; we will have access to the new <em>Html.Action</em> command with which we can easily render partials for shared functionality, like navigation structure or other parts of the master page that need dynamic data. As Phil Haack shows in <a href="http://haacked.com/archive/2009/11/18/aspnetmvc2-render-action.aspx" target="_blank">this post</a> it&#8217;s a very powerful and urgently needed feature.</p.</p>
<p>In the master view you will have a call like this:</p>
<pre class="brush: csharp; light: true; title: ; notranslate">

&lt;%= Html.Action(&quot;Menu&quot;) %&gt;
</pre>
<p>This will directly call a method in one of your controllers to supply the partial view with its data:</p>
<pre class="brush: csharp; title: ; notranslate">
[ChildActionOnly]
public ActionResult Menu() {

	NavigationData navigationData = navigationService.GetNavigationData();
	MenuViewModel menuViewModel = mapper.GetMenuViewModel(navigationData);

	return PartialView(menuViewModel);
}
</pre>
<p>Unfortunately in MVC 1 we have to make use of a more elaborate trick to get the data to the partial view.</p>
<p><span id="more-222"></span></p>
<p>In the earlier post about <a href="http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/">view hierarchy</a> I showed you what our master view looks like and how partial views are included:</p>
<pre class="brush: csharp; light: true; title: ; notranslate">

	&lt;% Html.RenderPartial(&quot;Menu&quot;, ViewData.Eval(&quot;DataForMenu&quot;)); %&gt;
</pre>
<h3>The attribute</h3>
<p>But how do we make sure the data is present in ViewData? We do this through the use of attributes. For each partial there is an attribute that puts the view data into ViewData.</p>
<pre class="brush: csharp; highlight: [8]; title: ; notranslate">
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
				AllowMultiple = false)]
public sealed class DataForMenuAttribute : ActionFilterAttribute
{
	public override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		// Work only for GET request
		if (filterContext.RequestContext.HttpContext.Request.RequestType != &quot;GET&quot;)
			return;

		// Do not work with AjaxRequests
		if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
			return;

		NavigationData navigationData = navigationService.GetNavigationData();
		MenuViewModel menuViewModel = mapper.GetMenuViewModel(navigationData);

		filterContext.Controller.ViewData[&quot;DataForMenu&quot;] = menuViewModel;
	}
}
</pre>
<p>This attribute sets the data for the partial view. As you can see from the highlighted line we don&#8217;t set data for POST requests. To make this possible we have to make sure we never render views for POST requests. We do this by upholding the Post-Redirect-Get pattern. More on that in a future part.</p>
<p>Of course, we have to make sure that every controller that makes use of the master view, which includes the <em>Menu</em> partial view, has this attribute set.</p>
<pre class="brush: csharp; title: ; notranslate">
[DataForMenu]
public HomeController : Controller
{
</pre>
<p>The trouble with attributes in MVC is that you have no control over the creation of their instances. This makes it hard to use dependency injection, but not completely impossible. We have to make sure there&#8217;s a parameterless constructor for MVC to instantiate them, but we can make an overloaded constructor, that is called from the parameterless one to make use of dependency injection:</p>
<pre class="brush: csharp; highlight: [7,8]; title: ; notranslate">
public sealed class DataForMenuAttribute : ActionFilterAttribute
{
	private readonly INavigationService navigationService;
	private readonly IViewModelMapper mapper;

	public DataForMenuAttribute() :
		this(ObjectFactory.GetInstance&lt;INavigationService&gt;(),
			 ObjectFactory.GetInstance&lt;IViewModelMapper&gt;())
	{}

	public DataForMenuAttribute(INavigationService navigationService,
								IViewModelMapper mapper)
	{
		this.navigationService = navigationService;
		this.mapper = mapper;
	}
</pre>
<p>Until now we succeeded to limit the use of StructureMap to only one line in the ControllerFactory, however attributes are the one part of MVC that makes it impossible to limit usage of <em>ObjectFactory.GetInstance</em> to just a single occurrence.</p>
<h3>Unit testing the attribute</h3>
<p>Fortunately, with the overloaded constructor in place, we are able to make use of AutoMocker for unit testing the attribute.</p>
<pre class="brush: csharp; title: ; notranslate">
[TestFixture]
public class DataForMenuAttributeTests
{
	private RhinoAutoMocker&lt;DataForMenuAttribute&gt; autoMocker;
	private DataForMenuAttribute attribute;

	private SomeController controller;
	private ActionExecutingContext context;
	private HttpRequestBase httpRequestMock;
	private HttpContextBase httpContextMock;

	[SetUp]
	public void Setup()
	{
		StructureMapBootstrapper.Restart();

		autoMocker = new RhinoAutoMocker&lt;DataForMenuAttribute&gt;(MockMode.AAA);
		attribute = autoMocker.ClassUnderTest;

		controller = new SomeController();
		httpRequestMock = MockRepository.GenerateMock&lt;HttpRequestBase&gt;();
		httpContextMock = MockRepository.GenerateMock&lt;HttpContextBase&gt;();
		httpContextMock.Expect(x =&gt; x.Request).Repeat.Any().Return(httpRequestMock);

		context = new ActionExecutingContext(
					new ControllerContext(httpContextMock ,
										  new RouteData(),
										  controller),
                                        MockRepository.GenerateMock&lt;ActionDescriptor&gt;(),
					new Dictionary&lt;string, object&gt;());
	}

	[Test]
	public void DataForMenuAttributeShouldNotSetViewDataForPostRequest()
	{
		//Arrange
		httpRequestMock.Expect(r =&gt; r.RequestType).Return(&quot;POST&quot;);

		//Act
		attribute.OnActionExecuting(context);

		//Assert
		Assert.That(controller.ViewData[&quot;DataForMenu&quot;], Is.Null);
	}

	[Test]
	public void DataForMenuAttributeShouldNotSetViewDataForAjaxRequest()
	{
		//Arrange
		httpRequestMock.Expect(r =&gt; r.RequestType).Return(&quot;GET&quot;);
		httpRequestMock.Expect(r =&gt; r[&quot;X-Requested-With&quot;]).Return(&quot;XMLHttpRequest&quot;);

		//Act
		attribute.OnActionExecuting(context);

		//Assert
		Assert.That(controller.ViewData[&quot;DataForMenu&quot;], Is.Null);
	}

	[Test]
	public void DataForMenuAttributeShouldCallGetNavigationData()
	{
		//Arrange
		httpRequestMock.Expect(r =&gt; r.RequestType).Return(&quot;GET&quot;);
		httpRequestMock.Expect(r =&gt; r[&quot;X-Requested-With&quot;]).Return(string.Empty);

		NavigationData navigationData = new NavigationData();
		autoMocker.Get&lt;INavigationService&gt;()
			.Expect(x =&gt; x.GetNavigationData()).Return(navigationData);

		//Act
		attribute.OnActionExecuting(context);

		//Assert
		autoMocker.Get&lt;INavigationService&gt;().VerifyAllExpectations();
	}

	[Test]
	public void DataForMenuAttributeShouldCallGetMenuViewModel()
	{
		//Arrange
		httpRequestMock.Expect(r =&gt; r.RequestType).Return(&quot;GET&quot;);
		httpRequestMock.Expect(r =&gt; r[&quot;X-Requested-With&quot;]).Return(string.Empty);

		NavigationData navigationData = new NavigationData();
		MenuViewModel menuViewModel = new MenuViewModel();
		autoMocker.Get&lt;INavigationService&gt;()
			.Expect(x =&gt; x.GetNavigationData()).Return(navigationData);
		autoMocker.Get&lt;IViewModelMapper&gt;()
			.Expect(x =&gt; x.GetMenuViewModel(navigationData)).Return(menuViewModel);

		//Act
		attribute.OnActionExecuting(context);

		//Assert
		autoMocker.Get&lt;IViewModelMapper&gt;().VerifyAllExpectations();
	}

	[Test]
	public void DataForMenuAttributeShouldSetMenuViewDataToGetMenuViewModelResult()
	{
		//Arrange
		httpRequestMock.Expect(r =&gt; r.RequestType).Return(&quot;GET&quot;);
		httpRequestMock.Expect(r =&gt; r[&quot;X-Requested-With&quot;]).Return(string.Empty);

		MenuViewModel menuViewModel = new MenuViewModel();
		autoMocker.Get&lt;IViewModelMapper&gt;()
			.Expect(x =&gt; x.GetMenuViewModel(Arg&lt;NavigationData&gt;.Is.Anything))
			.Return(menuViewModel);

		//Act
		attribute.OnActionExecuting(context);

		//Assert
		Assert.That(controller.ViewData[&quot;DataForMenu&quot;], Is.EqualTo(menuViewModel));
	}
}
</pre>
<p>As you can see, it&#8217;s quite a lot of work setting up expectations and especially the context for testing an attribute.</p>
<p>Also, notice that for each test I try to arrange and assert just what&#8217;s needed to verify that the code does what the name of the test says it should do.</p>
<p>Having multiple assertions in every test makes it much more difficult to alter the code under test. Ideally you would want to ditch the tests that verify functionality that&#8217;s no longer wanted and create new tests to verify new functionality.<br />
For example, if you decide not to use the <em>INavigationService</em> any longer for returning data to feed to the <em>IViewModelMapper</em>, the <em>DataForMenuAttributeShouldCallGetNavigationData</em> test can be removed and <em>DataForMenuAttributeShouldCallGetMenuViewModel</em> has to be altered slightly.</p>
<p>One last thing we have to test is the presence of the attribute on the controllers where it&#8217;s necessary. This can be done in the following manner:</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void ExampleControllerShouldHaveDataForMenuAttribute()
{
	Assert.That(Attribute.GetCustomAttribute(typeof(ExampleController),
											 typeof(DataForMenuAttribute)),
				Is.Not.Null);
}
</pre>
<p>Make sure you have this test for every controller that needs the attribute!</p>
<p>Concluding, as you can see by the amount of work that&#8217;s needed to test the attribute itself and its presence on the controllers, you can imagine we&#8217;re really looking forward to MVC 2&#8242;s RenderAction.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/03/08/maintainable-mvc-series-poor-man%e2%80%99s-renderaction/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC Series: View Model and Form Model</title>
		<link>http://blog.jorritsalverda.nl/2010/03/03/maintainable-mvc-series-viewmodel-and-formmodel/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-viewmodel-and-formmodel</link>
		<comments>http://blog.jorritsalverda.nl/2010/03/03/maintainable-mvc-series-viewmodel-and-formmodel/#comments</comments>
		<pubDate>Wed, 03 Mar 2010 21:57:48 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[AutoMapper]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[Separation of Concerns]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=178</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. As mentioned in the previous post all views are strongly typed and every view has it&#8217;s own View Model. Although this results in quite a lot of classes the upside is maintainability in that it&#8217;s very straightforward. Every bit of data displayed in the view has [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>As mentioned in the <a href="http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/">previous post</a> all views are strongly typed and every view has it&#8217;s own <em>View Model</em>. Although this results in quite a lot of classes the upside is maintainability in that it&#8217;s very straightforward. Every bit of data displayed in the view has a corresponding property in the View Model. As soon as it&#8217;s no longer needed in the view we remove the property as well.</p>
<p>Of course, it sounds like it&#8217;s in opposition with the DRY principle (Don&#8217;t Repeat Yourself). However the data in the properties of the view models stems from the domain model, meaning the business rules are still in one place. To get the data from the domain model to the view models we have <em>mapper</em> classes in the presentation layer.</p>
<p><span id="more-178"></span></p>
<h2>View model mapper</h2>
<p>A simple example of how a controller action will call the mapper to convert a domain model into a view model can be seen below:</p>
<pre class="brush: csharp; highlight: [5]; title: ; notranslate">
public ActionResult ShowItem(int id)
{
	DomainModel item = repository.GetItem(id);

	ViewModel viewModel = mapper.MapToViewModel(item);

	return View(&quot;ShowItem&quot;, viewModel);
}
</pre>
<p>Inside the MapToViewModel method we can have something like the following:</p>
<pre class="brush: csharp; title: ; notranslate">
public ViewModel MapToViewModel(DomainModel domainModel)
{
	ViewModel viewModel = new ViewModel
	{
		Id = domainModel.Id,
		Name = domainModel.Name,
		Description = domainModel.Description
	};

	return viewModel;
}
</pre>
<p>But wait, writing this code is a dull job and it&#8217;s easy to make a mistake. Therefore we make use of the <a href="http://www.codeplex.com/AutoMapper" target="_blank">AutoMapper</a> library by <a href="http://www.lostechies.com/blogs/jimmy_bogard/" target="_blank">Jimmy Bogard</a> as much as possible.</p>
<h2>AutoMapper</h2>
<p>AutoMapper is a library with the purpose of mapping properties of a complex type to a simple type like a view model. It&#8217;s not meant to be used the other way around, going from a poor model to a richer model with more properties.</p>
<p>Besides saving you of writing lots of code it also has test facilities to warn you if your target model (the view model) has new properties which have no counterpart in the source model (the domain model). An example of how we could use AutoMapper in the MapToViewModel method:</p>
<pre class="brush: csharp; title: ; notranslate">
public ViewModel MapToViewModel(DomainModel domainModel)
{
	Mapper.CreateMap&lt;DomainModel, ViewModel&gt;();

	ViewModel viewModel = Mapper.Map&lt;DomainModel, ViewModel&gt;(domainModel);

	return viewModel;
}
</pre>
<p>If ViewModel gets richer and new properties are present in DomainModel no single line of code will have to be altered in the mapper.</p>
<p>For testing if all properties of ViewModel (that have a setter) can be mapped by AutoMapper we move the CreateMap line to a AutoMapperBootstrapper class:</p>
<pre class="brush: csharp; title: ; notranslate">
public class AutoMapperBootstrapper
{
	public void BootstrapAutoMapper()
	{
		Mapper.CreateMap&lt;DomainModel, ViewModel&gt;();
		Mapper.CreateMap&lt;DomainModel, OtherViewModel&gt;();
	}

	public static void Bootstrap()
	{
		new AutoMapperBootstrapper().BootstrapAutoMapper();
	}
}
</pre>
<p>Having this code in a separate bootstrapper instead of the mapper classes is in order to have configuration centralized and because now testing of all these mappings is very easy. Just one test suffices for all mappings:</p>
<pre class="brush: csharp; title: ; notranslate">
[Test]
public void CheckIfConfigurationIsValid()
{
	AutoMapperBootstrapper.Bootstrap();

	Mapper.AssertConfigurationIsValid();
}
</pre>
<p>This test will fail as soon as there&#8217;s a property in one of the target models that can&#8217;t be mapped from the source model.</p>
<p>But what if our view model has to have a property that doesn&#8217;t get it&#8217;s value from the domain model? Well, we can chain some extra options to the CreateMap method to let AutoMapper ignore this property when mapping and when testing as well:</p>
<pre class="brush: csharp; title: ; notranslate">
Mapper.CreateMap&lt;DomainModel, ViewModel&gt;()
	.ForMember(x =&gt; x.NoDomainProperty, opt =&gt; opt.Ignore());
</pre>
<p>Now we can set this property after mapping DomainModel to ViewModel:</p>
<pre class="brush: csharp; highlight: [4]; title: ; notranslate">
public ViewModel MapToViewModel(DomainModel domainModel)
{
	ViewModel viewModel = Mapper.Map&lt;DomainModel, ViewModel&gt;(domainModel);
	viewModel.NoDomainProperty = repository.GetOtherData();

	return viewModel;
}
</pre>
<p>AutoMapper has a lot more in store like converting between types &#8211; for which you can even specify a custom converter &#8211; and other nice stuff. For more specifics visit the <a href="http://www.codeplex.com/AutoMapper" target="_blank">AutoMapper</a> site.</p>
<h2>Form Model</h2>
<p>In going from the controller to the view we make use of <em>view models</em>. But what about going the other way? Do we post view models? No, to keep things clear we only post <em>form models</em>.</p>
<p>So are they different from view models? Not really. In code they are pretty much equal to view models, however it&#8217;s more of a convention to name all models going outwards (towards the view) a <em>view model</em> and all models going inwards a <em>form model</em>. Also we try to make sure all properties can and will be filled by posted data. So no select lists and other presentation stuff in the form model.</p>
<p>In the last blog post I showed you how we pass the form model to the view containing the form. It is passed as a property of the view model for the specific view containing the form:</p>
<pre class="brush: csharp; title: ; notranslate">
public class ViewModel {

	public FormModel Data { get; set; }

	public string NameLabel { get; set; }

	public string DescriptionLabel { get; set; }

	public string CountryLabel { get; set; }

	public SelectList Countries { get; set; }

	public string CountryChooseOption { get; set; }

}
</pre>
<p>In the form view the data will be used like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;% using(Html.BeginForm()) {%&gt;
	&lt;%= Html.AntiForgeryToken() %&gt;
	&lt;label&gt;
		&lt;%= Html.Encode(Model.NameLabel) %&gt;:
		&lt;%= Html.TextArea(&quot;Name&quot;, Model.Data.Name) %&gt;
	&lt;/label&gt;
	&lt;label&gt;
		&lt;%= Html.Encode(Model.DescriptionLabel) %&gt;:
		&lt;%= Html.TextArea(&quot;Description&quot;, Model.Data.Description) %&gt;
	&lt;/label&gt;
	&lt;label&gt;
		&lt;%= Html.Encode(Model.CountryLabel) %&gt;:
		&lt;%= Html.DropDownList(&quot;Country&quot;, Model.Countries, Model.CountryChooseOption) %&gt;
	&lt;/label&gt;
	&lt;input type=&quot;submit&quot; value=&quot;Save&quot;&gt;
&lt;% } %&gt;
</pre>
<p>As you can see the values of the input fields are populated from the form model, while representation data like the dropdown list items and labels come from the viewmodel.</p>
<h3>Posting the form model</h3>
<p>A bonus of having all properties correspond to a form field is that all of them will be binded automatically by MVC.  No need for custom binding here.</p>
<p>Usage of the form model will look like this:</p>
<pre class="brush: csharp; title: ; notranslate">
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult UpdateItem(int id, FormModel formModel)
{
	DomainModel item = repository.GetItem(id);

	item.Name = formModel.Name;
	item.Description = formModel.Description;

	repository.SaveItem(item);

	return RedirectToAction(&quot;UpdateItem&quot;, new{ id });
}
</pre>
<p>Of course the code above is just an example. The method will soon start to bloat if we add validation and other aspects (like setting success or error message to display on the page redirected to). So in order to keep the controller thin we&#8217;ll move the highlighted lines into a separate <em>form handler</em>.</p>
<h2>Form handler</h2>
<p>The form handler handles updating the domain model from the form model. It does checks to make sure the item to be updated belongs to the user posting the data. Etc, etc. It&#8217;s the beating heart if it comes to processing the commands coming in from the end user&#8217;s browser.</p>
<p>Just like in the view model mapper there is at least one method for each form model to handle either creation of a new item or updating an existing one. Or handling other commands than the usual CRUD. It fits the CQRS (Command Query Responsibility Segregation) principle nicely. View models and mapping for query&#8217;ing, form models and form handlers for command handling. More on CQRS <a href="http://jonathan-oliver.blogspot.com/2009/10/dddd-why-i-love-cqrs.html" target="_blank">over here</a>.</p>
<h2>Validation</h2>
<p>One last thing to talk about is validation. Validation is done on multiple levels. Our form models have their own validation, to make sure the posted data is what we want in terms of being required, being numeric or being an e-mail address. No difficult validation to see if shipping an order to a certain country is allowed. This belongs in the domain, because it&#8217;s core business logic.</p>
<p>Another benefit of having validation on the form model is that client-side validation is done easily.</p>
<p>Handling the first level protection of validating the form model can be done in the controller or in the form handler. Additional levels of validation are fed back to the controller by the form handler. Probably in the form of a result object with a property indicating if handling was successful and a property with a list of failed validation and more properties if we want to be able to have a complex page flow in the site.</p>
<p>I&#8217;m still thinking of ways to have the (simple) validation rules of the domain model automatically being used for the form model as well. But for now we have some duplication over here, which &#8211; I know &#8211; is an issue regarding maintainability. But it isn&#8217;t very often that a field being required one day stops being required the other day. Just simple validation over here. And the domain model validation is always there to back up the form model validation.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/03/03/maintainable-mvc-series-viewmodel-and-formmodel/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC Series: View hierarchy</title>
		<link>http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-view-hierarchy</link>
		<comments>http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 18:10:37 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=116</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. The view system of ASP.NET MVC knows the followings types of views: Master views Page views Partial views The regular page view contains the specific html and presentation of data for each rendered page. For html shared by multiple pages &#8211; like navigation, header and footer [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>The view system of ASP.NET MVC knows the followings types of views:</p>
<ul>
<li>Master views</li>
<li>Page views</li>
<li>Partial views</li>
</ul>
<p>The regular page view contains the specific html and presentation of data for each rendered page. For html shared by multiple pages &#8211; like navigation, header and footer &#8211; every page has a master page. </p>
<p>Both of these types can include partial views for small parts, that can be reused from multiple views. For example page navigation for display of results covering multiple pages, or widgets. Even if they&#8217;re not reused it is useful to separate parts of your page view or master view to partial views, to keep the (master) view itself comprehensible and maintainable.</p>
<p>For using partial views in the master view we have a special way to provide them with data (which is sometimes specific to the page requested, like which menu item is active). This is explained in the future part <em>Poor Man&#8217;s RenderAction</em>.</p>
<p><span id="more-116"></span></p>
<h2>Master view</h2>
<p>In the following diagram you can see the master page and it&#8217;s partial views. A page view is shown in more detail later on.</p>
<p><img src="http://blog.jorritsalverda.nl/wp-content/uploads/2010/02/mvc-view-hierarchy.png" alt="" title="mvc-view-hierarchy" width="400" height="373" class="aligncenter size-full wp-image-122" /></p>
<p>The code for the <em>Site.Master</em> looks something like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@ Master Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewMasterPage&quot; %&gt;
&lt;%@ Import Namespace=&quot;ClientX.Website.Models&quot;%&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;meta charset=&quot;utf-8&quot;&gt;
	&lt;title&gt;Site title - &lt;asp:ContentPlaceHolder ID=&quot;TitleContent&quot; runat=&quot;server&quot; /&gt;&lt;/title&gt;
&lt;% #if DEBUG %&gt;
	&lt;% Html.RenderPartial(&quot;CssDebug&quot;, ViewData.Eval(&quot;DataForCss&quot;)); %&gt;
&lt;% #else %&gt;
	&lt;% Html.RenderPartial(&quot;CssRelease&quot;, ViewData.Eval(&quot;DataForCss&quot;)); %&gt;
&lt;% #endif %&gt;
&lt;/head&gt;
&lt;body&gt;

	&lt;% Html.RenderPartial(&quot;Header&quot;, ViewData.Eval(&quot;DataForHeader&quot;)); %&gt;

	&lt;% Html.RenderPartial(&quot;PostBackForm&quot;, ViewData.Eval(&quot;DataForPostBackForm&quot;)); %&gt;

	&lt;% Html.RenderPartial(&quot;Messages&quot;, ViewData.Eval(&quot;DataForMessages&quot;)); %&gt;

	&lt;div class=&quot;content&quot;&gt;

		&lt;asp:ContentPlaceHolder ID=&quot;MainContent&quot; runat=&quot;server&quot; /&gt;

	&lt;/div&gt;&lt;!-- /content --&gt;

	&lt;% Html.RenderPartial(&quot;Footer&quot;, ViewData.Eval(&quot;DataForFooter&quot;)); %&gt;

&lt;% #if DEBUG %&gt;
	&lt;% Html.RenderPartial(&quot;JavascriptDebug&quot;, ViewData.Eval(&quot;DataForJavascript&quot;)); %&gt;
&lt;% #else %&gt;
	&lt;% Html.RenderPartial(&quot;JavascriptRelease&quot;, ViewData.Eval(&quot;DataForJavascript&quot;)); %&gt;
&lt;% #endif %&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the code above you can identify the inclusion of multiple partial views and the placeholders where the page view descending from the master view can show their html. This quite straightforward.</p>
<p>More specific to our master is the way we select the javascript and css partial views. The <em>DEBUG</em> switches make sure the right css and javascript is included on the production server. For development you&#8217;ll want to use your original javascript files, while the production servers will serve minified and merged javascript files.</p>
<p>The data supplied to the to the partial views makes it look like these partial views aren&#8217;t strongly type, however they certainly are. Perhaps it&#8217;s possible to provide the master view itself with a strongly typed model, however the effort is probably not worth it, because production issues rarely arise within the master view.</p>
<p>If your site uses multiple different layouts (1, 2 or 3 columns for example) it is advisable to have nested master pages. The top one still keeps the css, javascript and navigation, where the nested master pages will only contain the html that differs between the different layouts.</p>
<h2>Page view</h2>
<p><img src="http://blog.jorritsalverda.nl/wp-content/uploads/2010/02/mvc-page-and-partial-views.png" alt="" title="mvc-page-and-partial-views" width="400" height="456" class="aligncenter size-full wp-image-129" /></p>
<pre class="brush: xml; title: ; notranslate">
&lt;%@ Page Title=&quot;&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Views/Shared/Site.Master&quot; Inherits=&quot;System.Web.Mvc.ViewPage&lt;OverviewViewModel&gt;&quot; %&gt;
&lt;%@ Import Namespace=&quot;ClientX.Website.Models&quot;%&gt;

&lt;asp:Content ID=&quot;TitleContentPlaceHolder&quot; ContentPlaceHolderID=&quot;TitleContent&quot; runat=&quot;server&quot;&gt;
	Page title
&lt;/asp:Content&gt;

&lt;asp:Content ID=&quot;MainContentPlaceHolder&quot; ContentPlaceHolderID=&quot;MainContent&quot; runat=&quot;server&quot;&gt;

	&lt;% Html.RenderPartial(&quot;Heading&quot;, Model.Heading); %&gt;

	&lt;div&gt;
		&lt;% Html.RenderPartial(&quot;OverviewSearchForm&quot;, Model.OverviewSearchForm); %&gt;

		&lt;% Html.RenderPartial(&quot;Pager&quot;, Model.Pager); %&gt;

		&lt;table&gt;
			&lt;% Html.RenderPartial(&quot;TableHeader&quot;, Model.TableHeader); %&gt;
			&lt;%foreach (TableRowViewModel item in Model.ItemList){
				Html.RenderPartial(&quot;TableRow&quot;, item);
			} %&gt;
		&lt;/table&gt;

		&lt;% Html.RenderPartial(&quot;Pager&quot;, Model.Pager); %&gt;
	&lt;/div&gt;
&lt;/asp:Content&gt;
</pre>
<p>The page view is a little bit different from the master view. For one, it actually contains the content for the placeholders present in the master view. The other difference with the master view is that the included partial views are called strongly-typed.</p>
<p>Also notice, in the first line, that the view is strongly typed. All of our page views and partial views are strongly typed, no exceptions made.</p>
<p>Furthermore, our rule is never (and I mean never) to share a view model between multiple views. Each view has it&#8217;s own tailor made view model.</p>
<p>The view model only has properties which are actually used in the view. Also, it is totally flat (only simple properties) and quite dumb. You wouldn&#8217;t want to put too much logic in the view model, because it discourages reuse of the logic in question.</p>
<p>To fill the view models from the domain model we use <a href="http://www.codeplex.com/AutoMapper" target="_blank">AutoMapper</a> by <a href="http://www.lostechies.com/blogs/jimmy_bogard/" target="_blank">Jimmy Bogard</a> where possible and for the rest set it by hand in our presentation mapper classes. More on that in future part <em>ViewModel and FormModel</em>.</p>
<p>The only view models that aren&#8217;t completely flattened are the ones containing form data. The view model itself contains data that is just for view purposes, like select lists and descriptions for radio button options, etc. The form data itself is contained in a form model, which is accessible through the view model. Something like the code below:</p>
<pre class="brush: csharp; highlight: [3]; title: ; notranslate">
public class SearchFormViewModel {

	public SearchFormModel FormData { get; set; }

	public SelectList Countries { get; set; }

	public SelectList OtherDropDownData { get; set; }

}
</pre>
<p>Okay, enough for now. More on view models and form models in the next part.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC Series: Inversion of Control Container &#8211; StructureMap</title>
		<link>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-inversion-of-control-container-structuremap</link>
		<comments>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 21:22:23 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[StructureMap]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=57</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. To make your code testable the pattern to use is that of Dependency Injection. DI is nothing more than injecting all dependencies of a class instance through the constructor (or setters if you wish, but less intuitive when reading the code, and doesn&#8217;t guarantee all dependencies [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>To make your code testable the pattern to use is that of Dependency Injection. DI is nothing more than injecting all dependencies of a class instance through the constructor (or setters if you wish, but less intuitive when reading the code, and doesn&#8217;t guarantee all dependencies are set). For example if you have a controller that uses a factory and a repository you can both inject them into the constructor as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Controller
{
	private readonly IFactory factory;
	private readonly IRepository repository;

	public Controller(IFactory factory, IRepository repository)
	{
		this.factory = factory;
		this.repository = repository;
	}
}
</pre>
<p><span id="more-57"></span></p>
<p>When looking at the constructor you immediately see on which components this class depends. Using interfaces makes testing even more simple, because then we can easily mock the dependencies. Creating an instance of the controller will look as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
IFactory factory = new Factory();
IRepository repository = new Repository();

Controller controller = new Controller(factory, repository);
</pre>
<p>Once your nesting of dependencies gets bigger, setting up your instances becomes quite cumbersome. This causes you to rethink before you add another dependency to a class. This hinders testability, so you would really want adding another dependency to be a piece of cake.</p>
<p>Enters Inversion Of Control container. The IOC container is some software that handles initialization of all your dependencies. StructureMap is on of the longest available ones for .Net. Others are Castle Windsor, Spring.NET, Unity, Ninject and others. What makes StructureMap very pleasant to work with is it&#8217;s extra facilities for testing.</p>
<p>First an example of how you use StructureMap to initialize your instances.</p>
<p>To setup which classes to use for which interfaces you do the following initialization once:</p>
<pre class="brush: csharp; title: ; notranslate">
ObjectFactory.Initialize(x =&gt;
	{
		x.For&lt;IFactory&gt;().Use&lt;Factory&gt;();
		x.For&lt;IRepository&gt;().Use&lt;Repository&gt;();
	});
</pre>
<p>Then every time you need an instance of your controller you can use the following code:</p>
<pre class="brush: csharp; title: ; notranslate">
Controller controller = ObjectFactory.GetInstance&lt;Controller&gt;();
</pre>
<p>StructureMap looks at the constructor of class Controller and sees it&#8217;s dependent on an IFactory and IRepository. It knows which concrete classes to use for these interfaces, so it creates those first and then creates the Controller instance by injecting them into the constructor.</p>
<h2>StructureMap in MVC</h2>
<p>In a standard MVC project your controllers are required to have a parameterless constructor, which is used to initialize them. Of course this is in conflict with the Dependency Injection we want to use the make our code testable and easy to setup with StructureMap. However MVC is extensible on this point, and we can provide our own ControllerFactory, which looks as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class StructureMapControllerFactory : DefaultControllerFactory
{
	protected override IController GetControllerInstance(Type controllerType)
	{
		if (controllerType == null)
		{
			return base.GetControllerInstance(controllerType);
		}

		try
		{
			return ObjectFactory.GetInstance(controllerType) as Controller;
		}
		catch (StructureMapException exception)
		{
			// log an error with the exception and ObjectFactory.WhatDoIHave()
			throw;
		}
	}
}
</pre>
<p>In <strong>MVC 2</strong> the signature of method <em>GetControllerInstance</em> looks a little different, so our StructureMapControllerFactory will be adjusted correspondingly:</p>
<pre class="brush: csharp; highlight: [3,4,8]; title: ; notranslate">
public class StructureMapControllerFactory : DefaultControllerFactory
{
	protected override IController GetControllerInstance(RequestContext requestContext,
														 Type controllerType)
	{
		if (controllerType == null)
		{
			return base.GetControllerInstance(requestContext, controllerType);
		}

		try
		{
			return ObjectFactory.GetInstance(controllerType) as Controller;
		}
		catch (StructureMapException exception)
		{
			// log an error with the exception and ObjectFactory.WhatDoIHave()
			throw;
		}
	}
}
</pre>
<p>This factory makes sure that StructureMap initializes your controllers. Now to make MVC use this factory we add the following code to the Global.asax.cs:</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Application_Start()
{
	// initialize structuremap container
	StructureMapBootstrapper.Bootstrap();

	// let structuremap handle creating controllers
	ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
</pre>
<p>On the last line we set the factory. The first line calls the bootstrapper, which does the initialization of StructureMap.</p>
<pre class="brush: csharp; highlight: [9,10,11,12,13,14,15,16]; title: ; notranslate">
public class StructureMapBootstrapper : IBootstrapper
{
	private static bool hasStarted;

	public void BootstrapStructureMap()
	{
		ObjectFactory.Initialize(x =&gt;
		{
			x.For&lt;ISessionHandler&gt;().Use&lt;SessionHandler&gt;();
			x.For&lt;ITempDataHandler&gt;().Use&lt;TempDataHandler&gt;();

			x.ForSingletonOf&lt;ICacheHandler&gt;().Use&lt;CacheHandler&gt;();

			x.AddRegistry&lt;FactoryRegistry&gt;();
			x.AddRegistry&lt;RepositoryRegistry&gt;();
			x.AddRegistry&lt;ServiceRegistry&gt;();
		});
	}

	public static void Restart()
	{
		if (hasStarted)
		{
			ObjectFactory.ResetDefaults();
		}
		else
		{
			Bootstrap();
			hasStarted = true;
		}
	}

	public static void Bootstrap()
	{
		new StructureMapBootstrapper().BootstrapStructureMap();
	}
}
</pre>
<p>The highlighted <em>ObjectFactory.Initialize</em> part in the code above is the part that is custom for your project. Here you specify which concrete class to use for which interface. The initialization isn&#8217;t very fast, but only performed once in production code. For testing purposes this is to costly, so the restart action is provided.</p>
<p>You can also see the lines with AddRegistry: the registries that are added are a way to group your code, because otherwise the bootstrapper can become quite long. A definition of a registry:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FactoryRegistry : Registry
{
	public FactoryRegistry()
	{
		For&lt;IInputModelFactory&gt;().Use&lt;InputModelFactory&gt;();
		For&lt;IViewModelFactory&gt;().Use&lt;ViewModelFactory&gt;();
	}
}
</pre>
<p>The specific StructureMap code in your project only consists of the BootStrapper, the registries and the ControllerFactory. It&#8217;s best to try and avoid the use of ObjectFactory.GetInstance throughout your code as much as possible. It makes it harder to replace StructureMap if you want to, but more importantly it makes your code harder to test. One case where you&#8217;ll probably won&#8217;t manage without is in the case of attributes. The creation of attribute instances is done by MVC and needs a parameterless constructor as well. However we can&#8217;t replace the factory in this case.</p>
<p>Unfortunately we need an extra use of ObjectFactory.GetInstance, but we can do it within the constructor to keep it testable:</p>
<pre class="brush: csharp; title: ; notranslate">
public class CustomAttribute : ActionFilterAttribute
{
	private readonly ISessionHandler sessionHandler;

	public CustomAttribute()
	: this(ObjectFactory.GetInstance&lt;ISessionHandler&gt;())
	{
	}

	public CustomAttribute(ISessionHandler sessionHandler)
	{
		this.sessionHandler = sessionHandler;
	}
</pre>
<p>If a class is created by StructureMap it defaults to the constructor with the most parameters.</p>
<h2>Testing with AutoMocker</h2>
<p>Okay, on to the reason I prefer StructureMap as an IOC container: AutoMocker. The RhinoAutoMocker creates an instance of the class under test and creates a Rhino Mock object for all (interfaced) dependencies. No more creation of mock objects yourself. And even more important you can add another dependency to a class without having to fix all tests that create an instance.</p>
<p>A test fixture will look as follows:</p>
<pre class="brush: csharp; highlight: [21,27]; title: ; notranslate">
[TestFixture]
public class AdvertsControllerTests
{
	private RhinoAutoMocker&lt;Controller&gt; autoMocker;
	private Controller controller;

	[SetUp]
	public void Setup()
	{
		StructureMapBootstrapper.Restart();

		autoMocker = new RhinoAutoMocker&lt;Controller&gt;(MockMode.AAA);
		controller = autoMocker.ClassUnderTest;
	}

	[Test]
	public void CreatePostShouldCallFormHandlerForValidPost()
	{
		//Arrange
		FormEditModel editModel = new FormEditModel();
		autoMocker.Get&lt;IFormHandler&gt;().Expect(p =&gt; p.CreatePost(Arg&lt;FormEditModel&gt;.Is.Anything)).Return(true);

		//Act
		controller.CreatePost(editModel);

		//Assert
		autoMocker.Get&lt;IFormHandler&gt;().VerifyAllExpectations();
	}
</pre>
<p>The highlighted <em>autoMocker.Get&lt;IFormHandler&gt;()</em> lines retrieve a mock object and set expectations. So, per test you only have to set the dependencies neccessary for the code under test. A controller often has a lot of dependencies, but they&#8217;re not used by every action.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Maintainable MVC Series: Introduction</title>
		<link>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-introduction</link>
		<comments>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 21:22:07 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=55</guid>
		<description><![CDATA[I&#8217;m going to do a series on how I&#8217;ve set up a number of ASP.NET MVC projects for customers with very high-traffic sites and continuously changing functional requirements. In these projects the design evolved to the one that I&#8217;m going to describe in detail. The following subjects will be handled in oncoming blogs: Inversion of [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m going to do a series on how I&#8217;ve set up a number of ASP.NET MVC projects for customers with very high-traffic sites and continuously changing functional requirements. In these projects the design evolved to the one that I&#8217;m going to describe in detail.</p>
<p>The following subjects will be handled in oncoming blogs:</p>
<ul>
<li><a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/">Inversion of Control container: StructureMap</a></li>
<li><a href="http://blog.jorritsalverda.nl/2010/02/24/maintainable-mvc-series-view-hierarchy/">View hierarchy</a></li>
<li><a href="http://blog.jorritsalverda.nl/2010/03/03/maintainable-mvc-series-viewmodel-and-formmodel/">View Model and Form Model</a></li>
<li><a href="http://blog.jorritsalverda.nl/2010/03/08/maintainable-mvc-series-poor-man%E2%80%99s-renderaction/">Poor man&#8217;s RenderAction</a></li>
<li><a href="http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/">Post-Redirect-Get pattern</a></li>
<li><a href="http://blog.jorritsalverda.nl/2010/03/16/maintainable-mvc-binding/">Binding</a></li>
</ul>
<p><span id="more-55"></span></p>
<p>To make the site as testable and maintainable as possible I adhere to the DRY principle (don&#8217;t repeat yourself) and try to write SOLID code:</p>
<ul>
<li><a href="http://docs.google.com/viewer?url=http://www.objectmentor.com/resources/articles/srp.pdf" target="_blank">Single Responsibility Principle</a></li>
<li><a href="http://docs.google.com/viewer?url=http://www.objectmentor.com/resources/articles/ocp.pdf" target="_blank">Open/Closed Principle</a></li>
<li><a href="http://docs.google.com/viewer?url=http://www.objectmentor.com/resources/articles/lsp.pdf" target="_blank">Liskov Substitution Principle</a></li>
<li><a href="http://docs.google.com/viewer?url=http://www.objectmentor.com/resources/articles/isp.pdf" target="_blank">Interface Segregation Principle</a></li>
<li><a href="http://docs.google.com/viewer?url=http://www.objectmentor.com/resources/articles/dip.pdf" target="_blank">Dependency Inversion</a></li>
</ul>
<p>Another aspect to focus on is to keep the controllers mean and lean. This is called the <em>skinny controller, fat model</em>; it states to have your controller actions as thin/short as possible, because you really want to avoid having business logic in your controller. Keeping the business logic in the domain model and service layer encourages reuse and makes it easier to update your site flow, and of course avoids having duplicate code in your project. It&#8217;s really a question of <em><a href="http://en.wikipedia.org/wiki/Separation_of_concerns" target="_blank">Separation Of Concerns</a></em>.</p>
<h2>Architecture</h2>
<p>The following diagram globally represents the architecture of our MVC application. The layers are explained in a bit more detail below from bottom to top.</p>
<p><img src="http://blog.jorritsalverda.nl/wp-content/uploads/2010/02/mvc-reference-architecture.png" alt="our mvc architecture" width="400" height="447" class="aligncenter size-full wp-image-48" /></p>
<h3>Infrastructure layer</h3>
<p>Data is often accessed in databases or through web services; there usually is an impedance mismatch between their data structure and our <em>domain model</em>. To overcome this mismatch we have <em>mappers</em> to perform the conversion from <em>data model</em> to <em>domain model</em> and vice versa.</p>
<p>The repositories provide CRUD functionality for the domain models to the physical storage layer with the use of the <em>mappers</em>.</p>
<h3>Domain layer</h3>
<p>Inside this layer the <em>services</em> provide access to data in the form of <em>domain models</em> as well as the possibility to handle various other actions as creating and updating new objects.</p>
<p>The core business logic of the site is contained in this layer. This makes it reusable by all controllers and views.</p>
<h3>Presentation layer</h3>
<p>The controllers of course play the central role in this layer. On <em>get</em> requests the controller requests domain models from the services in the layer beneath and passes these to the views in the form of view models; the conversion between domain models and view models is handled by the mappers.</p>
<p>In the case of views containing a form, the controller supplies the view with a <em>form model</em>. These contain various data from the domain model. Except for the data being edited it also contains data for dropdown lists and the likes. These models are also converted in the mappers.</p>
<p>When data is posted it usually enters the controller action as a <em>form model</em>. This model is handed off to a handler that updates the domain model with the data from the <em>form model</em>. This prevents the possibility of security leaks through <em>overposting</em> or <em>underposting</em>. Furthermore it keeps the controller skinny. Sequentially the handler calls the services for further handling of the actions neccessary to persist any changes.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery: performance of DOM manipulation</title>
		<link>http://blog.jorritsalverda.nl/2009/02/14/jquery-dom-manipulation-perfomance/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=jquery-dom-manipulation-perfomance</link>
		<comments>http://blog.jorritsalverda.nl/2009/02/14/jquery-dom-manipulation-perfomance/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 12:22:14 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Separation of Concerns]]></category>

		<guid isPermaLink="false">http://jorritsalverda.nl/blog/?p=7</guid>
		<description><![CDATA[After extensive tests it is apparant, the currently widespread browsers aren't performant enough for extensive DOM manipulation.]]></description>
			<content:encoded><![CDATA[<p>I tried moving some html that didn&#8217;t have a direct relation to the meaning of my content, but more with layout aspect, to the client-side by writing a jQuery plugin for it. This in order to heighten the separation of concerns. The plugin performs some DOM manipulation in order to apply a drop shadow effect as seen in the following image (left side without plugin applied, right side with):</p>
<p><img class="aligncenter size-full wp-image-48" title="image-before-and-after-shadow-plugin" src="http://blog.jorritsalverda.nl/wp-content/uploads/2009/02/image-before-and-after-shadow-plugin.png" alt="image-before-and-after-shadow-plugin" width="450" height="150" /></p>
<p>To accomplish this the crucial part of the plugin performs the following DOM manipulation:</p>
<pre class="brush: jscript; title: ; notranslate">
elementToWrap.html(
	'&lt;div class=&quot;frame&quot; style=&quot;width: 157px;&quot;&gt;' +
		elementToWrap.html() +
		'&lt;div class=&quot;right_shadow&quot;&gt;' +
			'&lt;div class=&quot;shadow_top_right&quot;&gt;&lt;/div&gt;' +
			'&lt;div class=&quot;shadow_right&quot; style=&quot;height: 93px;&quot;&gt;&lt;/div&gt;' +
		'&lt;/div&gt;' +
		'&lt;div class=&quot;bottom_shadow&quot;&gt;'
			'&lt;div class=&quot;shadow_bottom_left&quot;&gt;&lt;/div&gt;' +
			'&lt;div class=&quot;shadow_bottom&quot; style=&quot;width: 143px;&quot;&gt;&lt;/div&gt;' +
			'&lt;div class=&quot;shadow_bottom_right&quot;&gt;&lt;/div&gt;' +
		'&lt;/div&gt;' +
	'&lt;/div&gt;'
);
</pre>
<p><span id="more-7"></span></p>
<p>However, when I started using it in my site, page loads seemed sluggish. Especially on the thumbnail pages, with some 20 images to apply the plugin to. I was in for some performance measurements. With the Firefox plugin Firebug this is easy. You surround the code for which you want to measure the execution time with the following code:</p>
<pre class="brush: jscript; title: ; notranslate">
console.time('applyShadow');
...
console.timeEnd('applyShadow')
</pre>
<p>After which the firebug console will present you with timing in milliseconds for each time the plugin wraps an image with the forementioned divs. It looks as follows on my 2,4GHz quadcore:</p>
<p><img class="aligncenter size-full wp-image-49" title="jquery-dom-manipulation-performance" src="http://blog.jorritsalverda.nl/wp-content/uploads/2009/02/jquery-dom-manipulation-performance.png" alt="jquery-dom-manipulation-performance" width="450" height="176" /></p>
<p>In total it adds up to some 100-200ms for the 20 images on my homepage and even more on other pages. I&#8217;m afraid that with current browsers &#8211; even on Google Chrome you could notice the difference &#8211; this kind of offloading html generation to the client-side isn&#8217;t performant enough. If you want to run a bleeding fast website DOM manipulation should be kept to a minimum. Of course it is still very useful and acceptable when reacting on user interactions (like with the jQuery UI dialogs).</p>
<p>Some very useful tips when it comes to using jQuery and performance can be found over here:</p>
<p><a href="http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx" target="_blank">http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2009/02/14/jquery-dom-manipulation-perfomance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

