<?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>Agile at Work &#187; Inversion of Control</title>
	<atom:link href="http://www.agileatwork.com/tag/inversion-of-control/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agileatwork.com</link>
	<description>by Michael Valenty</description>
	<lastBuildDate>Sat, 10 Sep 2011 14:35:33 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Bolt-on Multi-Tenancy in ASP.NET MVC with Unity and NHibernate: Part II &#8211; Commingled Data</title>
		<link>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/</link>
		<comments>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/#comments</comments>
		<pubDate>Sat, 18 Jun 2011 15:03:05 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Open Closed Principle]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=580</guid>
		<description><![CDATA[Last time I went over going from separate web applications per tenant to a shared web application for all tenants, but each tenant still had its own database. Now we’re going to take the next step and let multiple tenants share the same database. After we add tenant_id to most of the tables in our [...]]]></description>
			<content:encoded><![CDATA[<p>Last time I went over going <a href="http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/">from separate web applications per tenant to a shared web application for all tenants</a>, but each tenant still had its own database. Now we’re going to take the next step and let multiple tenants share the same database. After we add <font size="2" face="Courier New">tenant_id</font> to most of the tables in our database we’ll need the application to take care of a few things.</p>
<p>First, we need to apply a where clause to all queries to ensure that each tenant sees only their data. This is pretty painless with NHibernate and completely transparent to the existing application! We just have to define a parameterized filter:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">hibernate-mapping</span><span style="color: blue"> </span><span style="color: red">xmlns</span><span style="color: blue">=</span>&quot;<span style="color: blue">urn:nhibernate-mapping-2.2</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">filter-def</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">filter-param</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">id</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">System.Int32</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">filter-def</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">hibernate-mapping</span><span style="color: blue">&gt;</span></pre>
</div>
<p>And then apply it to each entity:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&lt;</span><span style="color: #a31515">class</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">User</span>&quot;<span style="color: blue"> </span><span style="color: red">table</span><span style="color: blue">=</span>&quot;<span style="color: blue">[user]</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">id</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Id</span>&quot;<span style="color: blue"> </span><span style="color: red">column</span><span style="color: blue">=</span>&quot;<span style="color: blue">user_id</span>&quot;<span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">generator</span><span style="color: blue"> </span><span style="color: red">class</span><span style="color: blue">=</span>&quot;<span style="color: blue">identity</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">id</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">property</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Username</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">property</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">Email</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="background-color: #ffffc0; margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">filter</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant</span>&quot;<span style="color: blue"> </span><span style="color: red">condition</span><span style="color: blue">=</span>&quot;<span style="color: blue">tenant_id = :id</span>&quot;<span style="color: blue"> /&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px"><span style="color: blue">&lt;/</span><span style="color: #a31515">class</span><span style="color: blue">&gt;</span></pre>
</div>
<p>The last step is to set the value of the filter at runtime. This is done on the <font size="2" face="Courier New">ISession</font> like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> session = c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;().OpenSession();</pre>
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; session.EnableFilter(<span style="color: #a31515">&quot;tenant&quot;</span>).SetParameter(<span style="color: #a31515">&quot;id&quot;</span>, c.Resolve&lt;<span style="color: #2b91af">Tenant</span>&gt;().Id);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>The current tenant comes from <font size="2" face="Courier New">c.Resolve&lt;Tenant&gt;()</font>. In order for that to work, you have to tell Unity how to find the current tenant. In ASP.NET MVC, we can look at the host header on the request and find our tenant that way. We could just as easily use another strategy though. Maybe if this were a WCF service, we could use an authentication header to establish the current tenant context. You could build out some interfaces and strategies around establishing the current tenant context, however for this article I’ll just bang it out.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">Tenant</span>&gt;(<span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> repository = c.Resolve&lt;<span style="color: #2b91af">ITenantRepository</span>&gt;();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> context = c.Resolve&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = context.Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>] ?? context.Request.Url.Host;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> repository.FindByHost(host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }));</pre>
</div>
<p>Second, we have to set the <font size="2" face="Courier New">tenant_id</font> when new entities are saved. This is a bit more complicated with NHibernate and requires a bit of a concession in that we have to add a field to the entity in order for NHibernate to know how to persist the value. I’m using a private nullable int for this.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">User</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">int</span>? tenantId;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">int</span> Id { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Username { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Email { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>It’s private because I don’t want the business logic to deal with it and it’s nullable because my tenant table is in a separate database which means I can’t lean on the data model to enforce referential integrity. That’s a problem because the default value for an integer is zero which could be happily saved by the database. By making it nullable I can be sure the database will blow up if the <font size="2" face="Courier New">tenant_id</font> is not set.</p>
<p>So, back to the issue at hand. The <font size="2" face="Courier New">tenant_id</font> needs to be set when the entity is saved. For this, I’m using an interceptor and setting the value in the <font size="2" face="Courier New">OnSave</font> method:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MultiTenantInterceptor</span> : <span style="color: #2b91af">EmptyInterceptor</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Tenant</span>&gt; tenant;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> MultiTenantInterceptor(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Tenant</span>&gt; tenant)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.tenant = tenant;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> OnSave(<span style="color: blue">object</span> entity... <span style="color: blue">object</span>[] state, <span style="color: blue">string</span>[] propertyNames...)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> index = <span style="color: #2b91af">Array</span>.IndexOf(propertyNames, <span style="color: #a31515">&quot;tenantId&quot;</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (index == -1)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> tenantId = tenant().Id;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; state[index] = tenantId;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; entity</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .GetType()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .GetField(<span style="color: #a31515">&quot;tenantId&quot;</span>, <span style="color: #2b91af">BindingFlags</span>.Instance | <span style="color: #2b91af">BindingFlags</span>.NonPublic)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetValue(entity, tenantId);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>This <font size="2" face="Courier New">IInterceptor</font> mechanism is a little wonky. If you change any data, you have to do it in both the entity instance and the <font size="2" face="Courier New">state</font> array that NHibernate uses to hydrate entities. It’s not a big deal, it’s just one of those things you have to accept like the fact that Apple and Google are tracking your every move via your smart phone. Oh, and the interceptor gets wired up like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ContainerControlledLifetimeManager</span>(),</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>()</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="background-color: #ffffc0; margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetInterceptor(<span style="color: blue">new</span> <span style="color: #2b91af">MultiTenantInterceptor</span>(() =&gt; c.Resolve&lt;<span style="color: #2b91af">Tenant</span>&gt;()))</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; })</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>We’re almost done. There is one more case that needs to be handled. When NHibernate loads an entity by its primary key, it doesn’t run through the query engine which means the tenant filter isn’t applied. Fortunately, we can take care of this in the interceptor:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">MultiTenantInterceptor</span> : <span style="color: #2b91af">EmptyInterceptor</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; ...</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> OnLoad(<span style="color: blue">object</span> entity... <span style="color: blue">object</span>[] state, <span style="color: blue">string</span>[] propertyNames...)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> index = <span style="color: #2b91af">Array</span>.IndexOf(propertyNames, <span style="color: #a31515">&quot;tenantId&quot;</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (index == -1)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> entityTenantId = <span style="color: #2b91af">Convert</span>.ToInt32(state[index]);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> currentTenantId = tenant().Id;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (entityTenantId != currentTenantId)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">AuthorizationException</span>(<span style="color: #a31515">&quot;Permission denied to {0}&quot;</span>, entity);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">false</span>;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>That’s it. Have fun and happy commingling.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate-part-ii-commingled-data/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Bolt-on Multi-Tenancy in ASP.NET MVC with Unity and NHibernate</title>
		<link>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/</link>
		<comments>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/#comments</comments>
		<pubDate>Sat, 14 May 2011 15:59:32 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Open Closed Principle]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=564</guid>
		<description><![CDATA[The Mission: 
Build a web application as though it’s for a single customer (tenant) and add multi-tenancy as a bolt-on feature by writing only new code. There are flavors of multi-tenancy, in this case I want each tenant to have its own database but I want all tenants to share the same web application and [...]]]></description>
			<content:encoded><![CDATA[<p><strong>The Mission:</strong> </p>
<p>Build a web application as though it’s for a single customer (tenant) and add multi-tenancy as a bolt-on feature by writing only new code. There are flavors of multi-tenancy, in this case I want each tenant to have its own database but I want all tenants to share the same web application and figure out who’s who by looking at the host header on the http request.</p>
<p><strong>The Plan:</strong></p>
<p>To pull this off, we’re going to have to rely on our SOLID design principles, especially Single Responsibility and Dependency Inversion. We’ll get some help from these frameworks:</p>
<ul>
<li><a href="http://www.asp.net/mvc">ASP.NET MVC</a> </li>
<li><a href="http://unity.codeplex.com/">Unity</a> </li>
<li><a href="http://nhforge.org/Default.aspx">NHibernate</a> </li>
</ul>
<p><strong>Game on:</strong></p>
<p>Let’s take a look at a controller that uses NHibernate to talk to the database. I’m not going to get into whether you should talk directly to NHibernate from the controller or go through a service layer or repository because it doesn’t affect how we’re going to add multi-tenancy. The important thing here is that the <font size="2" face="Courier New">ISession</font> is <em>injected</em> into the controller, and we aren’t using the service locator pattern to request the <font size="2" face="Courier New">ISession</font> from a singleton.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">UserController</span> : <span style="color: #2b91af">Controller</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISession</span> session;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> UserController(<span style="color: #2b91af">ISession</span> session)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.session = session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ActionResult</span> Edit(<span style="color: blue">int</span> id)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> user = session.Load&lt;<span style="color: #2b91af">User</span>&gt;(id);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> View(user);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Alright, now it’s time to write some new code and make our web application connect to the correct database based on the host header in the http request. First, we’ll need a database to store a list of tenants along with the connection string for that tenant’s database. Here’s my entity:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Tenant</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> Host { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">virtual</span> <span style="color: blue">string</span> ConnectionString { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>I’ll use the repository pattern here so there is a crisp consumer of the <font size="2" face="Courier New">ISession</font> that connects to the lookup database rather than one of the tenant shards. This will be important later when we go to configure Unity.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">NHibernateTenantRepository</span> : <span style="color: #2b91af">ITenantRepository</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">ISession</span> session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">HttpContextBase</span> context;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> NHibernateTenantRepository(<span style="color: #2b91af">ISession</span> session, <span style="color: #2b91af">HttpContextBase</span> context)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.session = session;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.context = context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">Tenant</span> Current</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span></pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = context.Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>];</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> FindByHost(host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">Tenant</span> FindByHost(<span style="color: blue">string</span> host)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> session</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Query&lt;<span style="color: #2b91af">Tenant</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SingleOrDefault(t =&gt; t.Host == host);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>So now we need a dedicated <font size="2" face="Courier New">ISessionFactory</font> for the lookup database and make sure that our <font size="2" face="Courier New">NHibernateTenantRepository</font> gets the right <font size="2" face="Courier New">ISession</font> . It’s not too bad, we just need to name them in the container so we can refer to them explicitly.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session_factory&quot;</span>,</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ContainerControlledLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>().Configure().BuildSessionFactory())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session&quot;</span>,</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(<span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session_factory&quot;</span>).OpenSession())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ITenantRepository</span>, <span style="color: #2b91af">NHibernateTenantRepository</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">NHibernateTenantRepository</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionConstructor</span>(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ResolvedParameter</span>&lt;<span style="color: #2b91af">ISession</span>&gt;(<span style="background-color: #ffffc0; color: #a31515">&quot;tenant_session&quot;</span>),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">ResolvedParameter</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; )</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>Hopefully that’s about what you were expecting since it’s not really the interesting part. The more interesting part is configuring the <font size="2" face="Courier New">ISession</font> that gets injected into the <font size="2" face="Courier New">UserController</font> to connect to a different database based on the host header in the http request. The Unity feature we’re going to leverage for this is the <font size="2" face="Courier New">LifetimeManager</font>. This is an <a href="http://www.agileatwork.com/captcha-and-inversion-of-control/">often overlooked feature</a> of IoC containers.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="background-color: #ffffc0; color: #2b91af">PerHostLifetimeManager</span>(() =&gt; <span style="color: blue">new</span> <span style="color: #2b91af">HttpContextWrapper</span>(<span style="color: #2b91af">HttpContext</span>.Current)),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> connString = c</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Resolve&lt;<span style="color: #2b91af">ITenantRepository</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Current</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .ConnectionString;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">new</span> NHibernate.Cfg.<span style="color: #2b91af">Configuration</span>()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Configure()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .SetProperty(NHibernate.Cfg.<span style="color: #2b91af">Environment</span>.ConnectionString, connString)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; .BuildSessionFactory();</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }));</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">Container</pre>
<pre style="margin: 0px">&#160;&#160;&#160; .RegisterType&lt;<span style="color: #2b91af">ISession</span>&gt;(</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">PerRequestLifetimeManager</span>(),</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">new</span> <span style="color: #2b91af">InjectionFactory</span>(c =&gt; c.Resolve&lt;<span style="color: #2b91af">ISessionFactory</span>&gt;().OpenSession())</pre>
<pre style="margin: 0px">&#160;&#160;&#160; );</pre>
</div>
<p>Here we’re using a custom <font size="2" face="Courier New">PerHostLifetimeManager</font>. This tells Unity to maintain a session factory per host. When Unity runs across a host it doesn’t have a session factory for, it will run the <font size="2" face="Courier New">InjectionFactory</font> block to create one using the connection string associated with that tenant.</p>
<p>Since multiple simultaneous requests will be trying to get and set values <em>with the same key</em>, we need to make sure our <font size="2" face="Courier New">PerHostLifetimeManager</font> is thread safe. That’s pretty easy since Unity comes with a <font size="2" face="Courier New">SynchronizedLifetimeManager</font> base class that takes care of the fact that <font size="2" face="Courier New">Dictionary</font> <a href="http://stackoverflow.com/questions/157933/whats-the-best-way-of-implementing-a-thread-safe-dictionary-in-net">isn’t thread safe</a>.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">PerHostLifetimeManager</span> : <span style="background-color: #ffffc0; color: #2b91af">SynchronizedLifetimeManager</span></pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt; context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IDictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt; store;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> PerHostLifetimeManager(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt; context)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.context = context;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; store = <span style="color: blue">new</span> <span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">object</span>&gt;();</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">object</span> SynchronizedGetValue()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> host = GetHost();</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (!store.ContainsKey(host))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">null</span>;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> store[host];</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> SynchronizedSetValue(<span style="color: blue">object</span> newValue)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; store[GetHost()] = newValue;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">string</span> GetHost()</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> context().Request.Headers[<span style="color: #a31515">&quot;Host&quot;</span>];</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>So what did we accomplish? Well we didn’t touch any of our existing application code. We just wrote new code and through configuration we added multi-tenancy! That’s pretty cool, but was it worth it? Well, the goal in itself isn’t super important, but this exercise can certainly highlight areas of your codebase where you might be violating the single responsibility principle or leaking too many infrastructure concepts into your application logic.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Tamarack: Chain of Responsibility Framework for .NET</title>
		<link>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/</link>
		<comments>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 05:39:04 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Chain of Responsibility]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=554</guid>
		<description><![CDATA[The Chain of Responsibility is a key building block of extensible software.
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. – Gang of Four

Variations of this [...]]]></description>
			<content:encoded><![CDATA[<p>The Chain of Responsibility is a key building block of extensible software.</p>
<blockquote><p>Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. – Gang of Four</p>
</blockquote>
<p>Variations of this pattern are the basis for <a href="http://www.oracle.com/technetwork/java/filters-137243.html">Servlet Filters</a>, <a href="http://learn.iis.net/page.aspx/366/developing-iis-70-modules-and-handlers-with-the-net-framework/">IIS Modules and Handlers</a> and several open source projects I’ve had the opportunity to work with including <a href="https://www.forge.funambol.org/">Sync4J</a>, <a href="http://james.apache.org/">JAMES</a>, <a href="http://logging.apache.org/log4net/">Log4Net</a>, <a href="http://unity.codeplex.com/">Unity</a> and yes, even <a href="http://www.joomla.org/">Joomla</a>. It&#8217;s an essential tool in the OO toolbox and key in transforming rigid procedural code into a composable Domain Specific Language.</p>
<p><a href="http://www.agileatwork.com/where-does-it-hurt/">I’ve blogged about this pattern before</a> so what’s new this time?</p>
<ol>
<li>The next filter in the chain is provided via a delegate parameter rather than a property </li>
<li>The project is <a href="https://github.com/mikevalenty/tamarack">hosted on github</a> </li>
<li>There is a <a href="http://nuget.org/List/Search?packageType=Packages&amp;searchCategory=All+Categories&amp;searchTerm=tamarack">NuGet package</a> for it </li>
</ol>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="pkgmgr3" border="0" alt="pkgmgr3" src="http://www.agileatwork.com/wp-content/uploads/2011/04/pkgmgr31.png" width="640" height="332" /> </p>
<h3>How does it work?</h3>
<p>It&#8217;s pretty simple, there is just one interface to implement and it looks like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">interface</span> <span style="color: #2b91af">IFilter</span>&lt;T, TOut&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">    TOut Execute(T context, <span style="color: #2b91af">Func</span>&lt;T, TOut&gt; executeNext);</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Basically, you get an input to operate on and a value to return. The <font size="2" face="Courier New">executeNext</font> parameter is a delegate for the next filter in the chain. The filters are composed together in a chain which is referred to as a <font size="2" face="Courier New">Pipeline</font> in the Tamarack framework. This structure is the essence of the Chain of Responsibility pattern and it facilitates some pretty cool things:</p>
<ul>
<li>Modify the input before the next filter gets it </li>
<li>Modify the output of the next filter before returning </li>
<li>Short circuit out of the chain by not calling the executeNext delegate </li>
</ul>
<h3>Show me examples!</h3>
<p>Consider a block of code to process a blog comment coming from a web-based rich text editor. There are probably several things you&#8217;ll want to do before letting the text into your database.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">int</span> Submit(<span style="color: #2b91af">Post</span> post)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: #2b91af">Post</span>, <span style="color: blue">int</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">CanoncalizeHtml</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">StripMaliciousTags</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">RemoveJavascript</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">RewriteProfanity</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add(<span style="color: blue">new</span> <span style="color: #2b91af">GuardAgainstDoublePost</span>())</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(p =&gt; repository.Save(p));</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> newId = pipeline.Execute(post);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> newId;</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>What about dependency injection for complex filters? Take a look at this user login pipeline. Notice the generic syntax for adding filters by type. Those filters are built-up using the supplied implementation of <font size="2" face="Courier New">System.IServiceProvider</font>. My favorite is <font size="2" face="Courier New">UnityServiceProvider</font>.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">bool</span> Login(<span style="color: blue">string</span> username, <span style="color: blue">string</span> password)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt;(serviceProvider)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">WriteLoginAttemptToAuditLog</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">LockoutOnConsecutiveFailures</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">AuthenticateAgainstLocalStore</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">AuthenticateAgainstLdap</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(c =&gt; <span style="color: blue">false</span>);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(<span style="color: blue">new</span> <span style="color: #2b91af">LoginContext</span>(username, password));</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>Here’s another place you might see the chain of responsibility pattern. Calculating the spam score of a block of text:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">double</span> CalculateSpamScore(<span style="color: blue">string</span> text)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">SpamCopBlacklistFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">PerspcriptionDrugFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Add&lt;<span style="color: #2b91af">PornographyFilter</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(score =&gt; 0);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(text);</pre>
<pre style="margin: 0px">}</pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>Prefer convention over configuration? Try this instead:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">double</span> CalculateSpamScore(<span style="color: blue">string</span> text)</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">var</span> pipeline = <span style="color: blue">new</span> <span style="color: #2b91af">Pipeline</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;()</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .AddFiltersIn(<span style="color: #a31515">&quot;Tamarack.Example.Pipeline.SpamScorer.Filters&quot;</span>)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; .Finally(score =&gt; 0);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">return</span> pipeline.Execute(text);</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>Let&#8217;s look at the <font size="2" face="Courier New">IFilter</font> interface in action. In the spam score calculator example, each filter looks for markers in the text and adds to the overall spam score by modifying the <em>result</em> of the next filter before returning.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">PerspcriptionDrugFilter</span> : <span style="color: #2b91af">IFilter</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">double</span> Execute(<span style="color: blue">string</span> text, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">double</span>&gt; executeNext)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> score = executeNext(text);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (text.Contains(<span style="color: #a31515">&quot;viagra&quot;</span>))</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; score += .25;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> score;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<p>In the login example, we look for the user in our local user store and if it exists we&#8217;ll short-circuit the chain and authenticate the request. Otherwise we&#8217;ll let the request continue to the next filter which looks for the user in an LDAP repository.</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">AuthenticateAgainstLocalStore</span> : <span style="color: #2b91af">IFilter</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt;</pre>
<pre style="margin: 0px">{</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">readonly</span> <span style="color: #2b91af">IUserRepository</span> repository;</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> AuthenticateAgainstLocalStore(<span style="color: #2b91af">IUserRepository</span> repository)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">this</span>.repository = repository;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Execute(<span style="color: #2b91af">LoginContext</span> context, <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">LoginContext</span>, <span style="color: blue">bool</span>&gt; executeNext)</pre>
<pre style="margin: 0px">&#160;&#160;&#160; {</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">var</span> user = repository.FindByUsername(context.Username);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (user != <span style="color: blue">null</span>)</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> user.IsValid(context.Password);</pre>
<pre style="margin: 0px">&#160;</pre>
<pre style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> executeNext(context);</pre>
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
<pre style="margin: 0px">}</pre>
</div>
<h3>Why should I use it?</h3>
<blockquote>
<p>It&#8217;s pretty much my favorite animal. It&#8217;s like a lion and a tiger mixed&#8230; bred for its skills in magic. – Napoleon Dynamite</p>
</blockquote>
<p>It’s simple and mildly opinionated in effort to guide you and your code into <a href="http://blogs.msdn.com/b/brada/archive/2003/10/02/50420.aspx">The Pit of Success</a>. It’s easy to write single responsibility classes and use inversion of control and composition and convention over configuration and lots of other goodness. Try it out. Tell a friend.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/tamarack-chain-of-responsibility-framework-for-net/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Where Does it Hurt?</title>
		<link>http://www.agileatwork.com/where-does-it-hurt/</link>
		<comments>http://www.agileatwork.com/where-does-it-hurt/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 23:21:55 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Chain of Responsibility]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Open Closed Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=255</guid>
		<description><![CDATA[Notes from my Brown Bag Learning Forum Presentation. Download the source code, or just sit back and relax.
GoF Patterns:

Chain of Responsibility 
Decorator 
Adapter 

Buzz Phrases:

Single Responsibility Principle 
Open-Closed Principle 
Inversion of Control 
Aspect Oriented Programming 

Embracing the Single Responsibility Principle, Open-Closed Principle and Inversion of Control results in trading fragile application logic for fragile configuration [...]]]></description>
			<content:encoded><![CDATA[<p>Notes from my Brown Bag Learning Forum Presentation. <a href="http://www.secure-session.com/files/20/205/1664955444/E20E1B7ED7/i/brownbag-20110205b.zip">Download the source code</a>, or just sit back and relax.</p>
<p><strong>GoF Patterns:</strong></p>
<ul>
<li>Chain of Responsibility </li>
<li>Decorator </li>
<li>Adapter </li>
</ul>
<p><strong>Buzz Phrases:</strong></p>
<ul>
<li>Single Responsibility Principle </li>
<li>Open-Closed Principle </li>
<li>Inversion of Control </li>
<li>Aspect Oriented Programming </li>
</ul>
<p>Embracing the Single Responsibility Principle, Open-Closed Principle and Inversion of Control results in trading fragile application logic for fragile configuration logic. That’s a pretty good trade.</p>
<p>Fragile application logic is costly and it will come back to hurt you repeatedly. It goes without saying that fragile application logic is not testable, otherwise it wouldn’t be fragile. No tests mean changes are scary, so you have to compensate by regaining an intimate understanding of all the twists and turns in order to have enough confidence to make the change. The time and mental energy it takes to work through delicate and subtle conditional logic is enormous. My mediocre brain can only manage a short call stack and juggle a handful of variables at once.</p>
<p>Let’s say you’re sold on the promise of pretentious acronyms like SRP, OCP, IoC and the like. So now you end up with a billion small classes and gobs of code dedicated to wiring-up your favorite inversion of control container (mine is <a href="http://www.codeplex.com/unity">Unity</a>). Are we better for it? Let’s examine this trade-off by implementing the same functionality conventionally and using fancy patterns and principles.</p>
<p><strong>The Scenario:</strong> Implement captcha as the first step in some business process, like a registration form.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="captcha2" border="0" alt="captcha2" src="http://www.agileatwork.com/wp-content/uploads/2009/12/captcha2.png" width="492" height="238" /> </p>
<p>That’s pretty easy, I don’t need anything fancy to do that.</p>
<pre class="prettyprint"><code>public class SimpleController : Controller {
    private const string CaptchaTextKey = "captcha_text";

    public ActionResult Index() {
        return View();
    }

    public ActionResult Render() {

        var captchaImage = new CaptchaImage();

        HttpContext.Session[CaptchaTextKey] = captchaImage.Text;

        using (Bitmap bitmap = captchaImage.RenderImage()) {
            using (var stream = new MemoryStream()) {
                bitmap.Save(stream, ImageFormat.Jpeg);
                return new FileContentResult(stream.ToArray(), "image/jpeg");
            }
        }
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        var actualText = (string)HttpContext.Session[CaptchaTextKey];

        if (captchaText.Equals(actualText)) {
            ViewData["message"] = "You are a human";
        } else {
            ViewData["message"] = "fail";
        }

        return View("Index");
    }
}</code></pre>
<p>Fast forward 3 months and amazingly new requirements have crept into the simple captcha controller. Consider these contrived yet poignant scenarios:</p>
<ul>
<li>After the project goes to QA, you realize there needs to be a way to bypass the captcha check so automated Selenium tests can get to the rest of the application. </li>
<li>After the project goes live, the business decides it wants to know how many users are hitting the form. So an audit log is added. </li>
<li>After reviewing the audit log, it is discovered that some IPs are attacking the form, so we decide to implement a black list. </li>
<li>After the black list is live, the servers begin to perform slowly, so detailed logging is added. </li>
<li>The logs show the black list lookup is slow during attacks, so it is determined that caching should be implemented. </li>
<li>The business is doing a television promotion and expects traffic spikes. IT wants real-time visibility to monitor the application during heavy load. </li>
</ul>
<p>Now our <font size="2" face="Courier New">SimpleController</font> has morphed into a <font size="2" face="Courier New">SmellyController</font>:</p>
<pre class="prettyprint"><code>public class SmellyController : Controller {

    // ...

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        var ip = HttpContext.Request.ServerVariables["REMOTE_ADDR"];

        var isBlackListed = IsBlackListed(ip);

        if (IsMatch(captchaText) &amp;&amp; !isBlackListed || captchaText == "selenium" {
            ViewData["message"] = "You are a human";

            // reset consecutive error count
            ConsecutiveErrorCount = 0;
        } else {
            ViewData["message"] = "fail";

            // add to black list
            if (ConsecutiveErrorCount++ &gt;= 3 &amp;&amp; !isBlackListed) {
                AddToBlackList(ip);
            }
        }

        WriteToAuditLog(ip);

        return View("Index");
    }

    private bool IsBlackListed(string ip) {
        var sessionKey = BlackListKey + ip;
        object result = HttpContext.Cache[sessionKey];

        if (result == null) {
            using (var connection = new SqlConnection(connectionString)) {
                connection.Open();
		var sql = "select count(*) from blacklist where ip = @ip";
                using (var command = new SqlCommand(sql)) {
                    command.Connection = connection;
                    command.Parameters.AddWithValue("@ip", ip);
                    result = Convert.ToBoolean(command.ExecuteScalar());
                }
            }
            HttpContext.Cache[sessionKey] = result;
        }

        return (bool)result;
    }

    private int ConsecutiveErrorCount {
        get { return Convert.ToInt32(HttpContext.Session[ErrorCountKey] ?? "0"); }
        set { HttpContext.Session[ErrorCountKey] = value; }
    }

    // ...

    private bool IsMatch(IEquatable&lt;string&gt; captchaText) {
        var actualText = (string)HttpContext.Session[CaptchaTextKey];
        return captchaText.Equals(actualText);
    }</code></pre>
<p>How does this smell? Let me count the ways:</p>
<ol>
<li><a href="http://xunitpatterns.com/Hard%20to%20Test%20Code.html">Hard to test</a>&#160; </li>
<li><a href="http://c2.com/cgi/wiki?MixingLevels">Mixed levels of abstraction</a> </li>
<li>No separation of concerns </li>
</ol>
<p>What if we had followed <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">Uncle Bob’s SOLID principles</a>? Our controller might look like this:</p>
<pre class="prettyprint"><code>public class SolidController : Controller {
    private readonly ICaptchaProvider captchaProvider;

    public SolidController(ICaptchaProvider captchaProvider) {
        this.captchaProvider = captchaProvider;
    }

    public ActionResult Index() {
        return View();
    }

    public ActionResult Render() {
        using (var stream = new MemoryStream()) {
            captchaProvider.Render(stream, ImageFormat.Jpeg);
            return new FileContentResult(stream.ToArray(), "image/jpeg");
        }
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Verify(string captchaText) {

        if (captchaProvider.Verify(captchaText)) {
            ViewData["message"] = "You are a human";
        } else {
            ViewData["message"] = "fail";
        }

        return View("Index");
    }
}</code></pre>
<p>And our original simple captcha provider could look like this:</p>
<pre class="prettyprint"><code>[Serializable]
public class SimpleCaptchaProvider : ICaptchaProvider {
    private string captchaText;

    public void Render(Stream stream, ImageFormat format) {
        var captchaImage = new CaptchaImage();

        captchaText = captchaImage.Text;

        using (Bitmap bitmap = captchaImage.RenderImage()) {
            bitmap.Save(stream, format);
        }
    }

    public bool Verify(string text) {
        return text.Equals(captchaText);
    }
}</code></pre>
<p>If you’re wondering why we don’t have to store the captcha text in the session, it’s because we’re <a href="http://www.agileatwork.com/captcha-and-inversion-of-control/">putting the onus on the container</a> to give us the same instance of <font size="2" face="Courier New">SimpleCaptchaProvider</font> each time it’s requested in the same session.</p>
<p>Let’s revisit the list of features that made our controller smelly and see how we could have done it open-closed style (by writing new code instead modifying old code). The go-to technique for this is the decorator pattern. So let’s make a decorator to look for a secret captcha password that our selenium test knows and let it through.</p>
<pre class="prettyprint"><code>public class SeleniumBypassCaptchaProvider : ICaptchaProvider {
    private readonly ICaptchaProvider captchaProvider;
    private readonly string password;

    public SeleniumBypassCaptchaProvider(
        ICaptchaProvider captchaProvider,
        string password) {

        this.captchaProvider = captchaProvider;
        this.password = password;
    }

    public void Render(Stream stream, ImageFormat format) {
        captchaProvider.Render(stream, format);
    }

    public bool Verify(string captchaText) {
        if (captchaText == password) {
            return true;
        }
        return captchaProvider.Verify(captchaText);
    }
}</code></pre>
<p>Next is the audit log, then the black list. These could be implemented as two more decorators, however we’re outgrowing this solution which means it’s time to refactor. Let’s switch hats for a few minutes and promote our decorator chain into an explicit chain of responsibility. This is like adding another lane to the freeway, it really opens things up. We’re modifying existing code so maybe you’re wondering what happened to our open-closed principle? It’s still there, I promise. The first point I’ll make is that refactoring is a special activity. It does not change the observable behavior of the application. When working with single responsibility classes, all we end up doing is adapting the logic to a different interface. In our case, we’re moving logic from <font size="2" face="Courier New">BlackListCaptchaProvider</font> to <font size="2" face="Courier New">BlackListVerifyFilter</font>. The logic stays intact and the unit tests are minimally impacted.</p>
<p>The end result of this refactor might look like this:</p>
<pre class="prettyprint"><code>public class VerifyChainCaptchaProvider : ICaptchaProvider {
    private readonly ICaptchaProvider captchaProvider;
    private readonly IServiceProvider serviceProvider;

    public VerifyChainCaptchaProvider(
        ICaptchaProvider captchaProvider,
        IServiceProvider serviceProvider) {

        this.captchaProvider = captchaProvider;
        this.serviceProvider = serviceProvider;
    }

    public void Render(Stream stream, ImageFormat format) {
        captchaProvider.Render(stream, format);
    }

    public bool Verify(string captchaText) {
        return new Pipeline&lt;string , bool&gt;(serviceProvider)
            .Add&lt;AuditLoggingFilter&gt;()
            .Add&lt;BlackListingFilter&gt;()
            .Add&lt;SeleniumBypassFilter&gt;()
            .Add(new CaptchaProviderAdapter(captchaProvider))
            .Process(captchaText);
    }
}</code></pre>
<p>Was it worth it? Well, we’re left with all these little classes each with their single responsibility, however we still have to wire it up. I’m not going to lie, it’s ugly and it’s fragile. So why is this design any better? It’s better because troubleshooting bad configuration is better than troubleshooting bad application logic. Bad application logic can do really bad things. In a 24/7 business-critical application, this usually happens around 3 AM and involves you waking up and trying adjust your eyes to a harsh laptop screen. With bad configuration on the other hand, whole chunks of functionality are just missing. Chances are your app won’t even start, or maybe it starts but the black list or the audit logging isn’t wired in. These issues are easy to test and when you fix them, you have enormous confidence that the functionality you just wired-in will work and continue to work in the wee hours of the morning.</p>
<p>The second point I’ll make is the code more closely follows the way we think about our application. This makes it easier to respond to change because new requirements are extensions of the way we already think about our application. Consider the scenario that our selenium secret passphrase is not secure enough for production and we want to add an IP restriction or signature to make sure it’s really our selenium test that is getting through. In our smelly controller, a selenium test bypass is not an explicit concept, it’s just an or-clause tacked on to the end of an already abused <font size="2" face="Courier New">if</font> statement. We’ll have to go into our smelly controller and do some thrashing around in the most important and delicate block of code. In our solid controller however, we have a nicely abstracted testable single responsibility class we can isolate our change to.</p>
<p>As another example, consider the scenario that our black list caching is consuming too much memory on the web server. With our SOLID design we can surgically replace our <font size="2" face="Courier New">ICacheProvider</font> with an implementation backed by <a href="http://www.codeplex.com/memcachedproviders">Memcached</a>. Bits of functionality are free to evolve at their own pace. Some areas of your application will need a beefy solution and some will be just fine with a simple one. The important thing is that concerns are isolated from each other and allowed to fulfill their own destiny.</p>
<h3>Aspect-Oriented Programming</h3>
<p>I mentioned aspect oriented programming at the beginning of the article in a shallow attempt to pique your interest. So before I wrap things up I’ll show how it fits in. Since we’re already using an IoC container and faithfully employing our SOLID design principles, we pretty much get AOP for free. This is a big deal. Software running under service level agreements and government regulations demands visibility and having aspects in your toolbox is a must. Because aspects are reusable, they are typically higher quality and more mature than something hand-rolled for a one-off scenario. And because they are bolt-on, our core business logic stays focused on our business domain.</p>
<p>Consider the cliché logging example. It’s overused, but works well not unlike the calculator example for unit testing or the singleton job interview question. The idea is that we tell our IoC container to apply a logging aspect to all objects it has registered. Here’s what my logging aspect produces:</p>
<pre style="padding-bottom: 3px; background-color: black; padding-left: 3px; padding-right: 3px; color: white; font-size: 10pt; padding-top: 3px">DEBUG VerifyChainCaptchaProvider.Render() stream = MemoryStream, format = Jpeg
DEBUG SimpleCaptchaProvider.Render() stream = MemoryStream, format = Jpeg
DEBUG SimpleCaptchaProvider.Render() [72 ms]
DEBUG VerifyChainCaptchaProvider.Render() [74 ms]
DEBUG VerifyChainCaptchaProvider.Verify() text = afds
DEBUG AuditLoggingFilter.Process() input = afds
DEBUG BlackListingFilter.Process() input = afds
DEBUG CachingBlackListService.IsBlocked() ip = 127.0.0.1
DEBUG CachingBlackListService.IsBlocked() &gt; False [0 ms]
DEBUG SeleniumBypassFilter.Process() input = afds
DEBUG SimpleCaptchaProvider.Verify() text = afds
DEBUG SimpleCaptchaProvider.Verify() &gt; False [0 ms]
DEBUG SeleniumBypassFilter.Process() &gt; False [1 ms]
DEBUG BlackListingFilter.Process() &gt; False [4 ms]
DEBUG AuditLoggingFilter.Process() &gt; False [8 ms]
DEBUG VerifyChainCaptchaProvider.Verify() &gt; False [14 ms]</pre>
<p>Again, this is powerful because we didn’t have to pollute our code with logging statements, yet we see quality log entries with input, output and execution time. In addition to logging, we can attach <a href="http://www.agileatwork.com/definition-of-enterprise-software/">performance counters</a> to meaningful events, add exception policies to notify us when things go wrong, selectively add caching at run-time and lots more. To see it all in action, you can <a href="http://www.secure-session.com/files/20/205/1664955444/E20E1B7ED7/i/brownbag-20110205b.zip">download the source code</a> for the examples used in this article.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/where-does-it-hurt/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Definition of Enterprise Software</title>
		<link>http://www.agileatwork.com/definition-of-enterprise-software/</link>
		<comments>http://www.agileatwork.com/definition-of-enterprise-software/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 20:41:32 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Enterprise Library]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=244</guid>
		<description><![CDATA[The difference between Enterprise software and regular software is like the difference between a start-up and a public company. Enterprise software has lots of bureaucracy and red tape (indirection and configuration) to support transparency and top-down policy. You pay a price up front to create all these layers and well-defined communication channels between departments, but [...]]]></description>
			<content:encoded><![CDATA[<p>The difference between Enterprise software and regular software is like the difference between a start-up and a public company. Enterprise software has lots of bureaucracy and red tape (indirection and configuration) to support transparency and top-down policy. You pay a price up front to create all these layers and well-defined communication channels between departments, but once the whole thing is up and running, it’s powerful.</p>
<p>Big companies can throw time and money at problems to produce activity diagrams, advisory boards and flow charts. Sure there’s bloat, but you need that kind of oversight to enforce corporate policy. Similarly, enterprise software can extravagantly use cpu cycles, disk space and memory, but this is a fair price to pay when complexity is king. Enterprise software must be concerned with things like service level agreements and government regulations. So how do you do that?</p>
<p>You do that by dissecting your application into composable units of behavior. This is the essence of the single-responsibility-principle and while the concept is deceptively simple, it can have a profound effect on your software. Yes, the end result is lots of little classes, but it’s much more than that. These classes capture individual business concepts and overtime your software becomes a domain-specific-language (DSL). I don’t mean the kind of DSL that a business person would use directly, but more like xpath and regular expressions except your DSL is focused on your business domain.</p>
<p>Over time, software becomes an asset or a liability. The difference is your ability to respond to the needs of the business and your toolbox for that is your DSL or lack thereof. You need to compose, decompose, rearrange and built-out bits of behavior in ways impossible to predict. Single responsibility gives you that ability and dependency inversion creates seams throughout your code to spin off in unpredictable directions. These seams are the key to longevity and the difference between enterprise software and regular software.</p>
<p>I’ll share an experience I had this weekend. I was about to deploy a new application and I thought it would be cool to use a performance counter to watch throughput. Within about 20 minutes I was able to add a performance counter by only modifying the App.config and this was the result:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="perfmon3" border="0" alt="perfmon3" src="http://www.agileatwork.com/wp-content/uploads/2009/12/perfmon3.png" width="602" height="520" /></p>
<p>This was possible because of IoC among other things. The app is composed of many small pieces and you’d be hard pressed to find the “new” keyword where it matters. <font size="2" face="Courier New">SyncListingJob</font> was already being built-up by <a href="http://www.codeplex.com/Wikipage?ProjectName=unity">Unity Container</a>, so I was able take advantage of an off-the-shelf performance monitor aspect in the <a href="http://msdn.microsoft.com/en-us/library/dd139982.aspx">Enterprise Library 4.1 Policy Injection Application Block</a> and wire it in via the App.config.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/definition-of-enterprise-software/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Console application with IoC</title>
		<link>http://www.agileatwork.com/console-application-with-ioc/</link>
		<comments>http://www.agileatwork.com/console-application-with-ioc/#comments</comments>
		<pubDate>Sun, 22 Nov 2009 03:41:43 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Fluent Interface]]></category>
		<category><![CDATA[Inversion of Control]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=203</guid>
		<description><![CDATA[I like to think of the Main method in a Console application like the Global.asax. Its single responsibility is to wire-up things to be run in a console context. Each environment has unique configuration requirements. For example, when using NHiberate in a web application the lifetime of the ISession is attached to the HttpRequest, however [...]]]></description>
			<content:encoded><![CDATA[<p>I like to think of the <font size="2" face="Courier New">Main</font> method in a Console application like the Global.asax. Its single responsibility is to wire-up things to be run in a console context. Each environment has unique configuration requirements. For example, when using NHiberate in a web application the lifetime of the <font size="2" face="Courier New">ISession</font> is attached to the <font size="2" face="Courier New">HttpRequest</font>, however in the context of a console application it may be a singleton or “per job” in a windows service. I like this:</p>
<pre class="prettyprint">
<code>class Program
{
    static void Main(string[] args)
    {
        using (var container = new UnityContainer())
        {
            container
                .AddExtension(new ConfigureForConsole(args))
                .Resolve&lt;MyApplication&gt;()
                .Execute();
        }
    }
}</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/console-application-with-ioc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Holy Trinity of Web 2.0 Application Monitoring</title>
		<link>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/</link>
		<comments>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/#comments</comments>
		<pubDate>Fri, 24 Jul 2009 19:34:22 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Decorator Pattern]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Open Closed Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=171</guid>
		<description><![CDATA[We had just rolled out a new system for a client and they were doing a high profile launch of their product. We had all our normal monitoring in place like CPU, memory, connections and page load time. Everything was swell…
On their signup form, we did an ajax call to check if their desired username [...]]]></description>
			<content:encoded><![CDATA[<p>We had just rolled out a new system for a client and they were doing a high profile launch of their product. We had all our normal monitoring in place like CPU, memory, connections and page load time. Everything was swell…</p>
<p>On their signup form, we did an ajax call to check if their desired username was available. If it wasn’t, we displayed a validation error an prevented the user from submitting the form. Turns out our little jquery script was silently bombing out and always returning ‘false’ meaning nobody could sign up!</p>
<p><a href="http://www.agileatwork.com/wp-content/uploads/2009/07/scaredmonkey.png"><img title="scared-monkey" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="scared-monkey" src="http://www.agileatwork.com/wp-content/uploads/2009/07/scaredmonkey_thumb.png" width="238" border="0" /></a></p>
<p>This little issue slipped through the cracks and it hurt pretty bad. I couldn’t just tell the stake holders “sorry”, I needed something a little better so I spent some time with <a href="http://blog.mattbeckman.com/">Matt, our super do-everything networking guy</a>, and we put together the holy trinity of web 2.0 application monitoring (insert enlightenment music here).</p>
<p><img title="Nagios" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="50" alt="Nagios" src="http://www.agileatwork.com/wp-content/uploads/2009/07/Nagios.png" width="212" border="0" />&#160; <font size="7">+</font>&#160; <img title="cruisecontrol" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="42" alt="cruisecontrol" src="http://www.agileatwork.com/wp-content/uploads/2009/07/cruisecontrol.png" width="195" border="0" />&#160; <font size="7">+</font>&#160; <img title="selenium" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; vertical-align: middle; border-right-width: 0px" height="90" alt="selenium" src="http://www.agileatwork.com/wp-content/uploads/2009/07/selenium.png" width="100" border="0" /></p>
<p>We were already using <a href="http://www.nagios.org/">Nagios</a> for monitoring and alerting, <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a> for running unit tests, and <a href="http://seleniumhq.org/">Selenium</a> for automated web application testing. We just needed to glue it all together!</p>
<p>1) The first step was to write a selenium test to go through the online order sequence. We then exported it as a phpUnit test and dropped it in a our svn repository in a folder named “monitoring.”</p>
<p>2) Next, we configured a CruiseControl project named “selenium-bot” to pull down all the phpUnit tests from the “monitoring” folder in svn and run the whole test suite every 10 minutes.</p>
<p>3) The last step was to use Nagios to monitor the CruiseControl log file to make sure it was actually running every 10 minutes and returning all green. If anything stops working, Nagios takes care of the alerting.</p>
<p>I should also mention that since this hits the live online order form every 10 minutes, we needed a way to a way to short circuit the test orders. Fortunately, we already had a convenient <font face="Courier New" size="2">OrderGateway</font> interface, so we were able accomplish this in a very <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open-closed</a> manner using the decorator pattern:</p>
<pre class="csharpcode"><span class="kwrd">class</span> TestOrderInterceptor <span class="kwrd">implements</span> OrderGateway
{
  <span class="kwrd">const</span> TEST_CODE = '843feaa7-bf13-4aff-91f6-a074434f9c14';
  <span class="kwrd">const</span> SUCCESS_RESULT = 1;

  <span class="kwrd">private</span> $orderGateway;
  <span class="kwrd">private</span> $logger;

  <span class="kwrd">public function</span> __construct(OrderGateway $orderGateway, Logger $logger)
  {
    $this-&gt;orderGateway = $orderGateway;
    $this-&gt;logger = $logger;
  }

  <span class="kwrd">public function</span> createOrder(CreateOrderRequest $order)
  {
    if ($this-&gt;isTest($order))
    {
      $this-&gt;logger-&gt;debug(<span class="str">'test order intercepted'</span>);
      <span class="kwrd">return self</span>::SUCCESS_RESULT;
    }

    <span class="kwrd">return</span> $this-&gt;orderGateway-&gt;createOrder($order);
  }

  <span class="kwrd">private function</span> isTest($request)
  {
    <span class="kwrd">return</span> strpos($request-&gt;name1, <span class="kwrd">self</span>::TEST_CODE) !== false;
  }
}</pre>
<p>The decorator chain is wired up using <a href="http://www.picocontainer.org/">PicoContainer</a>, and looks like this:</p>
<pre class="csharpcode">$pico-&gt;regComponentImpl(<span class="str">'SoapOrderGateway'</span>, <span class="str">'SoapOrderGateway'</span>);

$pico-&gt;regComponentImpl(<span class="str">'OrderGateway'</span>, <span class="str">'TestOrderInterceptor'</span>, <span class="kwrd">array</span>(
    <span class="kwrd">new</span> BasicComponentParameter(<span class="str">'SoapOrderGateway'</span>),
    <span class="kwrd">new</span> BasicComponentParameter(<span class="str">'Logger'</span>)));</pre>
<p>This infrastructure has paid dividends more than a few times and now I can’t imagine rolling out a site without it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/the-holy-trinity-of-web-2-0-application-monitoring/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Captcha and Inversion of Control</title>
		<link>http://www.agileatwork.com/captcha-and-inversion-of-control/</link>
		<comments>http://www.agileatwork.com/captcha-and-inversion-of-control/#comments</comments>
		<pubDate>Mon, 15 Jun 2009 06:09:18 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=98</guid>
		<description><![CDATA[
I made a few tweaks to a captcha library I found here and basically wrapped their CaptchaImage object in a service interface to use in my application. Pretty easy stuff, but I didn’t get it right the first time.
What’s wrong with this class? (hint: it’s highlighted in yellow)
public class HttpContextCacheCaptchaProvider : ICaptchaProvider
{
    [...]]]></description>
			<content:encoded><![CDATA[<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Inversion of Control" border="0" alt="Inversion of Control" src="http://www.agileatwork.com/wp-content/uploads/2009/06/lorenzoflip.jpg" width="240" height="159" /></p>
<p>I made a few tweaks to a captcha library I found <a href="http://www.codeproject.com/KB/aspnet/CaptchaImage.aspx">here</a> and basically wrapped their <font size="2" face="Courier New">CaptchaImage</font> object in a service interface to use in my application. Pretty easy stuff, but I didn’t get it right the first time.</p>
<p>What’s wrong with this class? <font size="2"><em>(hint: it’s highlighted in yellow)</em></font></p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> HttpContextCacheCaptchaProvider : ICaptchaProvider
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> <span class="kwrd">string</span> httpContextCacheKey = <span class="str">&quot;4D795A45-8015-475C-A6C4-765B09EB9955&quot;</span>;
    <span class="kwrd">private</span> ICaptchaImageFactory factory;
    <span class="kwrd">private</span> HttpContextBase context;

    <span class="kwrd">public</span> HttpContextCacheCaptchaProvider(ICaptchaImageFactory factory, HttpContextBase context)
    {
        <span class="kwrd">this</span>.factory = factory;
        <span class="kwrd">this</span>.context = context;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        <span style="background: #ffffc0">context.Cache[httpContextCacheKey] = captchaImage.Text;</span>

        <span class="kwrd">using</span> (Bitmap bitmap = captchaImage.RenderImage())
        {
            bitmap.Save(stream, ImageFormat.Jpeg);
        }
    }

    <span class="kwrd">public</span> <span class="kwrd">bool</span> Verify(<span class="kwrd">string</span> text)
    {
        <span style="background: #ffffc0"><span class="kwrd">string</span> captchaText = (<span class="kwrd">string</span>)context.Cache[httpContextCacheKey];</span>

        <span class="kwrd">if</span> (text == <span class="kwrd">null</span> || captchaText == <span class="kwrd">null</span>)
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        <span class="kwrd">else</span>
            <span class="kwrd">return</span> text.ToLower().Equals(captchaText.ToLower());
    }
}</pre>
<p>Perhaps your nose can lead you in the right direction. The smell is <a href="http://c2.com/cgi/wiki?CodeSmellMetrics">hard to test</a>, and it’s hard to test because it requires mocking the <font size="2" face="Courier New">HttpContextBase</font>. You might say “no problem, I can blast out a stub with <a href="http://code.google.com/p/moq/">Moq</a> in no time” but you’re missing the real problem. That would be like taking aspirin for a brain tumor.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="arnold" border="0" alt="arnold" src="http://www.agileatwork.com/wp-content/uploads/2009/06/arnold.jpg" width="208" height="241" /></p>
<blockquote>
<p>It’s not a tumor</p>
</blockquote>
<p>The real problem is this class is violating the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a> (SRP) by doing more than one thing. I don’t mean the two methods <font size="2" face="Courier New">Render()</font> and <font size="2" face="Courier New">Verify()</font>, those are a cohesive unit operating on the same data. The other thing is <em>lifetime management</em>. Look how simple the class gets when you invert control and take out the notion of lifetime management:</p>
<pre class="csharpcode">[Serializable]
<span class="kwrd">public</span> <span class="kwrd">class</span> LifetimeManagedCaptchaProvider : ICaptchaProvider
{
    <span class="kwrd">private</span> ICaptchaImageFactory factory;
    <span class="kwrd">private</span> <span class="kwrd">string</span> captchaText;

    <span class="kwrd">public</span> LifetimeManagedCaptchaProvider(ICaptchaImageFactory factory)
    {
        <span class="kwrd">this</span>.factory = factory;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        <span style="background: #ffffc0">captchaText = captchaImage.Text;</span>

        <span class="kwrd">using</span> (Bitmap bitmap = captchaImage.RenderImage())
        {
            bitmap.Save(stream, ImageFormat.Jpeg);
        }
    }

    <span class="kwrd">public</span> <span class="kwrd">bool</span> Verify(<span class="kwrd">string</span> text)
    {
        <span class="kwrd">if</span> (text == <span class="kwrd">null</span> || captchaText == <span class="kwrd">null</span>)
            <span class="kwrd">return</span> <span class="kwrd">false</span>;
        <span class="kwrd">else</span>
            <span class="kwrd">return</span> text.ToLower().Equals(captchaText.ToLower());
    }
}</pre>
<p>Now this class is a breeze to test and all you have to do is register it like this:</p>
<pre class="csharpcode">Container.RegisterType&lt;ICaptchaProvider, LifetimeManagedCaptchaProvider&gt;(
    <span class="kwrd">new</span> HttpSessionStateLifetimeManager());</pre>
<p>The moral of the story is let your IoC container do things it’s good at.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/captcha-and-inversion-of-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing Unity Container Configuration</title>
		<link>http://www.agileatwork.com/testing-unity-container-configuration/</link>
		<comments>http://www.agileatwork.com/testing-unity-container-configuration/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 05:38:00 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://blog.agileatwork.com/testing-unity-container-configuration/</guid>
		<description><![CDATA[Before Inversion of Control, I would use configuration for a connection string, port number or other boring piece of information. Nowadays however, configuration can be a pretty hairy part of the application in its own right. Not necessarily the xml kind of configuration, just configuration. You know, the place where you use the “new “ [...]]]></description>
			<content:encoded><![CDATA[<p>Before Inversion of Control, I would use configuration for a connection string, port number or other boring piece of information. Nowadays however, configuration can be a pretty hairy part of the application in its own right. Not necessarily the xml kind of configuration, just configuration. You know, the place where you use the “new “ keyword and essentially break all the principals you worked so hard to protect in the rest of your application. Uncle Bob referred to this as “the other side of the wall” in a <a href="http://hanselminutes.com/default.aspx?showID=163">podcast with Scott Hanselman</a>.</p>
<p><a href="http://blog.agileatwork.com/wp-content/uploads/2009/06/afewgoodmenjacktruth1.jpg"><img title="afewgoodmenjacktruth" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin-left: 0px; margin-right: 0px; border-right-width: 0px" height="193" alt="afewgoodmenjacktruth" src="http://blog.agileatwork.com/wp-content/uploads/2009/06/afewgoodmenjacktruth-thumb.jpg" width="188" border="0" /></a></p>
<blockquote style="padding-right: 10px; padding-left: 10px; padding-bottom: 10px; padding-top: 10px"><p>“Son, we live in a world that has walls, and those walls have to be guarded by men with guns. Who&#8217;s gonna do it? You? You, Lieutenant Weinberg? I have a greater responsibility than you can possibly fathom…” &#8211; Colonel Nathan R. Jessep</p>
</blockquote>
<div style="clear: both">
<p>In my case, I wanted to inject an encryption provider to do Rijndael encryption with a specific vector and all that. Since I already had another IEncryptionProvider registered with the container, I named the new one.</p>
<pre class="prettyprint">
<code>Container.Configure&lt;InjectedMembers&gt;().ConfigureInjectionFor&lt;RijndaelEncryptionProvider&gt;(
    "MyEncryptionProvider",
    new InjectionConstructor(
        new ResolvedParameter&lt;NoOpSaltStrategy&gt;(),
        new RijndaelConfig { Hash = "SHA1", Vector = "notreal", Iterations = 2, Size = 256 }));

Container.Configure&lt;InjectedMembers&gt;().ConfigureInjectionFor&lt;MyService&gt;(
    new InjectionConstructor(
        new ResolvedParameter&lt;IEncryptionProvider&gt;("MyEncryptionProvider"),
        new ResolvedParameter&lt;DataDropConfigSection&gt;()));        </code></pre>
<p>What is a good way to make sure I’m wiring up Unity properly? I could just go black box and make sure my service can decrypt a string encrypted with a particular vector. That would be pretty BDDish and provide good insulation from volatile configuration code. In this application however, doing a legit integration test was a PITA for other reasons and I wanted some quick feedback on my Unity configuration.</p>
<p>A coworker and I decided to use a container extension to watch all the dependencies that were resolved and then tell us if we got the right one. The unit test looked like this:</p>
<pre class="prettyprint">
<code>[TestFixture]
public class EncryptionProviderTests
{
    private IUnityContainer container;
    private WasResolvedContainerExtension wasResolvedContainerExtension;

    [SetUp]
    public void SetUp()
    {
        wasResolvedContainerExtension = new WasResolvedContainerExtension();

        container = new UnityContainer()
            .AddExtension(wasResolvedContainerExtension)
            .AddNewExtension&lt;WebMvcContainerExtension&gt;();
    }

    [TearDown]
    public void TearDown()
    {
        container.Dispose();
    }

    [Test]
    public void Should_inject_named_instance_of_encryption_provider()
    {
        var service = container.Resolve&lt;MyService&gt;();

        AssertNamedInstanceWasResolved&lt;IEncryptionProvider&gt;("MyEncryptionProvider");
    }

    private void AssertNamedInstanceWasResolved&lt;T&gt;(string name)
    {
        Assert.IsTrue(wasResolvedContainerExtension.WasResolved&lt;T&gt;(name));
    }
}</code>
</pre>
<p>Granted it’s a little magical, but at least it reads well and a failure is pretty easy to track down from that point.&#160; This is what the container extension looks like:</p>
<pre class="prettyprint">
<code>public class WasResolvedContainerExtension : UnityContainerExtension
{
    private WasResolvedBuilderStrategy strategy;

    protected override void Initialize()
    {
        strategy = new WasResolvedBuilderStrategy();

        Context.Strategies.Add(strategy, UnityBuildStage.Creation);
    }

    public bool WasResolved&lt;T&gt;()
    {
        return WasResolved&lt;T&gt;(null);
    }

    public bool WasResolved&lt;T&gt;(string name)
    {
        return strategy.WasResolved&lt;T&gt;(name);
    }
}</code>
</pre>
<p>The real work is done in the BuilderStrategy which looks like:</p>
<pre class="prettyprint">
<code>public class WasResolvedBuilderStrategy : BuilderStrategy
{
    private IList&lt;NamedTypeBuildKey&gt; buildKeys = new List&lt;NamedTypeBuildKey&gt;();

    public override void PreBuildUp(IBuilderContext context)
    {
        buildKeys.Add((NamedTypeBuildKey)context.BuildKey);
    }

    public bool WasResolved&lt;T&gt;()
    {
        return WasResolved&lt;T&gt;(null);
    }

    public bool WasResolved&lt;T&gt;(string name)
    {
        var buildKey = (buildKeys.FirstOrDefault(k =&gt;
        typeof(T).IsAssignableFrom(k.Type) &amp;&amp; k.Name == name));

        return buildKey.Type != null;
    }
}</code>
</pre>
<p>And there you have it, a pretty quick way to test Unity configuration.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/testing-unity-container-configuration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

