<?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; Open Closed Principle</title>
	<atom:link href="http://www.agileatwork.com/tag/open-closed-principle/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>A Custom HttpModule to Log Request Duration</title>
		<link>http://www.agileatwork.com/a-custom-httpmodule-to-log-request-duration/</link>
		<comments>http://www.agileatwork.com/a-custom-httpmodule-to-log-request-duration/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 22:31:45 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Open Closed Principle]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=543</guid>
		<description><![CDATA[My application has logging of fine-grained operations, but I want to see the duration of the entire web request. The idea is to start a Stopwatch on the BeginRequest event and then log the elapsed time on the EndRequest event. I started by modifying the Global.asax to wire this up, but quickly got turned off [...]]]></description>
			<content:encoded><![CDATA[<p>My application has logging of fine-grained operations, but I want to see the duration of the entire web request. The idea is to start a <font size="2" face="Courier New">Stopwatch</font> on the <font size="2" face="Courier New">BeginRequest</font> event and then log the elapsed time on the <font size="2" face="Courier New">EndRequest</font> event. I started by modifying the Global.asax to wire this up, but quickly got turned off because I was violating the Open-Closed Principle. I really just want to bolt-in this behavior while I’m profiling the application and then turn it off when the kinks are worked out. IIS has a pretty slick extension point for this sort of thing that let’s you hook into the request lifecycle events.</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">RequestDurationLoggerModule</span> : <span style="color: #2b91af">IHttpModule</span></pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">{</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">const</span> <span style="color: blue">string</span> ContextItemKey = <span style="color: #a31515">&quot;stopwatchContextItemKey&quot;</span>;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Init(<span style="color: #2b91af">HttpApplication</span> application)</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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; application.BeginRequest += (o, args) =&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; application.Context.Items[ContextItemKey] = <span style="color: #2b91af">Stopwatch</span>.StartNew();</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;</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; application.EndRequest += (o, args) =&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">var</span> stopwatch = (<span style="color: #2b91af">Stopwatch</span>)application.Context.Items[ContextItemKey];</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; stopwatch.Stop();</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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">var</span> logger = GetLogger(application);</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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; logger.Debug(</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; <span style="color: #a31515">&quot;{0} -&gt; [{1} ms]&quot;</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; application.Context.Request.RawUrl,</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; stopwatch.ElapsedMilliseconds);</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>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">static</span> <span style="color: #2b91af">ILogger</span> GetLogger(<span style="color: #2b91af">HttpApplication</span> application)</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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; <span style="color: blue">var</span> serviceProvider = application <span style="color: blue">as</span> <span style="color: #2b91af">IServiceProvider</span>;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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; <span style="color: blue">if</span> (serviceProvider == <span style="color: blue">null</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; {</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> <span style="color: #2b91af">NullLogger</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; }</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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; <span style="color: blue">return</span> serviceProvider.GetService&lt;<span style="color: #2b91af">ILogger</span>&gt;();</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; }</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">void</span> Dispose()</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#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>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">}</pre>
</div>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px">&#160;</pre>
</div>
<p>The only weird part here is getting a handle to the logger. I’m using an IoC container in my application, however I can’t tell IIS how to build up my <font size="2" face="Courier New">RequestDurationLoggerModule</font>, so I’m stuck using the Service Locator pattern. The container could be a singleton, but <a href="http://www.agileatwork.com/dont-say-singleton/">I don’t like singletons</a>, so I implemented <font size="2" face="Courier New">IServiceProvider</font> in Global.asax instead. All that’s left now is wiring in the module. Since Cassini behaves like IIS6, you have to use the legacy style configuration, which looks like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">system.web</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">httpModules</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">...</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">MyApplication.RequestDurationLoggerModule</span><span style="color: blue">, MyApplication</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">httpModules</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">system.web</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>For IIS7 though, you add it like this:</p>
<div style="font-family: consolas; background: white; color: black; font-size: 10pt">
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;</span><span style="color: #a31515">system.webServer</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; &lt;</span><span style="color: #a31515">modules</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160;&#160;&#160;&#160;&#160; &lt;</span><span style="color: #a31515">add</span><span style="color: blue"> </span><span style="color: red">name</span><span style="color: blue">=</span>&quot;<span style="color: blue">...</span>&quot;<span style="color: blue"> </span><span style="color: red">type</span><span style="color: blue">=</span>&quot;<span style="color: blue">MyApplication.RequestDurationLoggerModule, MyApplication</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">modules</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px"><span style="color: blue">&#160; &lt;/</span><span style="color: #a31515">system.webServer</span><span style="color: blue">&gt;</span></pre>
<pre style="margin: 0px">&#160;</pre>
</div>
<p>Finally, it’s time to run the application and see the total request duration logged.</p>
<p><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="durationmodule" border="0" alt="durationmodule" src="http://www.agileatwork.com/wp-content/uploads/2011/01/durationmodule.png" width="725" height="173" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/a-custom-httpmodule-to-log-request-duration/feed/</wfw:commentRss>
		<slash:comments>4</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>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>Martinizing is Not Refactoring</title>
		<link>http://www.agileatwork.com/martinizing-is-not-refactoring/</link>
		<comments>http://www.agileatwork.com/martinizing-is-not-refactoring/#comments</comments>
		<pubDate>Sun, 24 May 2009 20:02:50 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Open Closed Principle]]></category>
		<category><![CDATA[Refactoring]]></category>

		<guid isPermaLink="false">http://blog.agileatwork.com/martinizing-is-not-refactoring/</guid>
		<description><![CDATA[A friend of mine, Keith, used the term martinizing (as in Uncle Bob) for the process of cleaning code. The term has taken on a very specific meaning and it’s worth a few words.
Martinizing is similar to refactoring in that it does not change the observable behavior of the code, but the goal is different. [...]]]></description>
			<content:encoded><![CDATA[<p>A friend of mine, Keith, used the term <em>martinizing</em> (as in <a href="http://www.objectmentor.com/omTeam/martin_r.html">Uncle Bob</a>) for the process of <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">cleaning code</a>. The term has taken on a very specific meaning and it’s worth a few words.
<p>Martinizing is similar to refactoring in that it does not change the observable behavior of the code, but the goal is different. When I refactor, I am changing the design, usually in an effort to add a new feature in an <a href="http://c2.com/cgi/wiki?OpenClosedPrinciple">open closed</a> manner.</p>
<p>When I martinize, I am telling a story. The most important story being the desired behavior, but also a story of the hard earned knowledge acquired along the way. If I spend hours distilling some business concept. I want to leave a trail for the next guy to understand that a simple property assignment or conditional statement isn’t so simple. And of course the perfect way to punctuate that message is with a well written unit test.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/martinizing-is-not-refactoring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

