<?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; AOP</title>
	<atom:link href="http://www.agileatwork.com/tag/aop/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>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>Default Interceptor for Unity</title>
		<link>http://www.agileatwork.com/default-interceptor-for-unity/</link>
		<comments>http://www.agileatwork.com/default-interceptor-for-unity/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 07:41:56 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/default-interceptor-for-unity/</guid>
		<description><![CDATA[Default: the two sweetest words in the English language – Homer Simpson

Unity interception requires you to specify what kind of interceptor to use for each type you want to intercept. This can be a little painful, so I decided to take a stab at a container extension that will apply a default interceptor with optional [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Default: the two sweetest words in the English language – Homer Simpson</p>
</blockquote>
<p>Unity interception requires you to specify what kind of interceptor to use for each type you want to intercept. This can be a little painful, so I decided to take a stab at a container extension that will apply a default interceptor with optional matching rules.</p>
<p>This is how I want it to look:</p>
<pre class="prettyprint">
<code>container
    .AddNewExtension&lt;InterceptOnRegister&gt;()
    .Configure&lt;InterceptOnRegister&gt;()
    .SetDefaultInterceptor&lt;TransparentProxyInterceptor&gt;()
    .AddMatchingRule(new AssemblyNameStartsWith("MyCompany"));</code>
</pre>
<p>The basic idea here is to subscribe to the register events and configure interception if it meets our criteria. By default it will match everything and apply <font face="Courier New" size="2">TransparentProxyInterceptor</font>, but as you can see from the snippet above, you can explicitly supply another interceptor and matching rules.</p>
<p>Here it is:</p>
<pre class="prettyprint">
<code>public class InterceptOnRegister : UnityContainerExtension {
    private IInstanceInterceptor interceptor;
    private readonly IList&lt;IInterceptRule&gt; rules;

    public InterceptOnRegister() {
        interceptor = new TransparentProxyInterceptor();
        rules = new List&lt;IInterceptRule&gt; {
            new NotUnityInterceptionAssembly(),
            new DoesNotHaveGenericMethods() };
    }

    public InterceptOnRegister AddMatchingRule(IInterceptRule rule) {
        rules.Add(rule);
        return this;
    }

    public InterceptOnRegister AddNewMatchingRule&lt;T&gt;() where T : IInterceptRule, new() {
        rules.Add(new T());
        return this;
    }

    public InterceptOnRegister SetDefaultInterceptor&lt;T&gt;() where T : IInstanceInterceptor, new() {
        interceptor = new T();
        return this;
    }

    protected override void Initialize() {
        AddInterceptionExtensionIfNotExists();

        Context.Registering +=
            (sender, e) =&gt; SetInterceptorFor(e.TypeFrom, e.TypeTo ?? e.TypeFrom);
    }

    private void AddInterceptionExtensionIfNotExists() {
        if (Container.Configure&lt;Interception&gt;() == null) {
            Container.AddNewExtension&lt;Interception&gt;();
        }
    }

    private void SetInterceptorFor(Type typeToIntercept, Type typeOfInstance) {
        if (!AllMatchingRulesApply(typeToIntercept, typeOfInstance)) {
            return;
        }

        if (interceptor.CanIntercept(typeOfInstance)) {
            Container
                .Configure&lt;Interception&gt;()
                .SetDefaultInterceptorFor(typeOfInstance, interceptor);
        } else if (interceptor.CanIntercept(typeToIntercept)) {
            Container
                .Configure&lt;Interception&gt;()
                .SetDefaultInterceptorFor(typeToIntercept, interceptor);
        }
    }

    private bool AllMatchingRulesApply(Type typeToIntercept, Type typeOfInstance) {
        foreach (var rule in rules) {
            if (!rule.Matches(typeToIntercept, typeOfInstance)) {
                return false;
            }
        }

        return true;
    }
}</code>
</pre>
<p>And you’ll need this stuff too:</p>
<pre class="prettyprint">
<code>public interface IInterceptRule {
    bool Matches(Type typeToIntercept, Type typeOfInstance);
}

public class NotUnityInterceptionAssembly : IInterceptRule {
    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return !typeToIntercept.Assembly.Equals(typeof(Interception).Assembly);
    }
}

public class DoesNotHaveGenericMethods : IInterceptRule {
    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return typeOfInstance.GetMethods().Count(m =&gt; m.IsGenericMethod) == 0;
    }
}

public class AssemblyNameStartsWith : IInterceptRule {
    private string match;

    public AssemblyNameStartsWith(string match) {
        this.match = match;
    }

    public bool Matches(Type typeToIntercept, Type typeOfInstance) {
        return typeOfInstance.Assembly.FullName.StartsWith(match);
    }
}</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/default-interceptor-for-unity/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Validation with Unity Interception</title>
		<link>http://www.agileatwork.com/validation-with-unity-interception/</link>
		<comments>http://www.agileatwork.com/validation-with-unity-interception/#comments</comments>
		<pubDate>Sat, 18 Jul 2009 20:16:19 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Composite Pattern]]></category>
		<category><![CDATA[Unity]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=149</guid>
		<description><![CDATA[ 
This is how I want things to look: 
public class UpdateUserRequest
{
    [AuthorizedUserPublisherRequired]
    public int UserId { get; set; }

    [Required(&#34;Name is required&#34;)]
    public string Name { get; set; }

    [ValidZipCodeRequired(&#34;Invalid zip code&#34;)]
    public string ZipCode { [...]]]></description>
			<content:encoded><![CDATA[<p><img title="funny_sign_5" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="237" alt="funny_sign_5" src="http://www.agileatwork.com/wp-content/uploads/2009/07/funny_sign_5.jpg" width="240" border="0" /> </p>
<p>This is how I want things to look: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> UpdateUserRequest
{
    [AuthorizedUserPublisherRequired]
    <span class="kwrd">public</span> <span class="kwrd">int</span> UserId { get; set; }

    [Required(<span class="str">&quot;Name is required&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> Name { get; set; }

    [ValidZipCodeRequired(<span class="str">&quot;Invalid zip code&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">string</span> ZipCode { get; set; }
}</pre>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IUserService
{
    <span class="kwrd">void</span> Update(UpdateUserRequest request);
} </pre>
<p>There are validation frameworks out there that will do this, so what’s my beef? Well, first of all I want to inject the validators with dependencies to implement the juicier rules. And second, I’m treating validation as a core concern so I don’t want a dependency on a framework like Enterprise Library. I had several questions like:</p>
<p>1) How do I get dependencies into the validators?</p>
<p>2) How do I get <font face="Courier New" size="2">ValidZipCodeRequired</font> to fire with the value of the <font face="Courier New" size="2">ZipCode</font> property</p>
<p>3) How do I initiate this on <font face="Courier New" size="2">userService.Update()</font>?</p>
<p>Let’s take a look at building up the validators.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ValidZipCodeRequiredAttribute : ValidatorAttribute
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> IValidator CreateValidator(IValidatorFactory factory)
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> factory.Create&lt;ValidZipCodeRequiredValidator&gt;();
    }
}</pre>
<p>This allows me to make a <font face="Courier New" size="2">UnityValidatorFactory</font> that can supply all my dependencies. Now how about this business of running the <font face="Courier New" size="2">ValidZipCodeRequiredValidator</font> with the value of the <font face="Courier New" size="2">ZipCode</font> property? For that I made a composite validator that loops through each property and runs the annotated validator against it’s property value.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> CompositeValidator&lt;T&gt; : IValidator&lt;T&gt;
{
    <span class="kwrd">private</span> IValidatorFactory factory;

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

    <span class="kwrd">public</span> IEnumerable&lt;RuleException&gt; Validate(T subject)
    {
        List&lt;RuleException&gt; exceptions = <span class="kwrd">new</span> List&lt;RuleException&gt;();

        <span class="kwrd">foreach</span> (PropertyInfo property <span class="kwrd">in</span> <span class="kwrd">typeof</span>(T).GetProperties())
        {
            <span class="kwrd">foreach</span> (var validator <span class="kwrd">in</span> GetValidatorsFor(property))
            {
                exceptions.AddRange(validator.Validate(property.GetValue(subject, <span class="kwrd">null</span>)));
            }
        }

        <span class="kwrd">return</span> exceptions;
    }

    <span class="kwrd">private</span> IEnumerable&lt;IValidator&gt; GetValidatorsFor(ICustomAttributeProvider provider)
    {
        <span class="kwrd">foreach</span> (ValidatorAttribute attribute
            <span class="kwrd">in</span> provider.GetCustomAttributes(<span class="kwrd">typeof</span>(ValidatorAttribute), <span class="kwrd">true</span>))
        {
            <span class="kwrd">yield</span> <span class="kwrd">return</span> attribute.CreateValidator(factory);
        }
    }
}</pre>
<p>Now I just need to run the <font face="Courier New" size="2">CompositeValidator</font> on <font face="Courier New" size="2">userService.Update()</font>. For that I use Unity Interception:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> ValidationCallHandler : ICallHandler
{
    <span class="kwrd">private</span> IValidator validator;

    <span class="kwrd">public</span> ValidationCallHandler(IValidator validator)
    {
        <span class="kwrd">this</span>.validator = validator;
    }

    <span class="kwrd">public</span> IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var ruleExceptions = ValidateEachArgument(input.Arguments);

        <span class="kwrd">if</span> (ruleExceptions.Count() &gt; 0)
        {
            <span class="kwrd">throw</span> <span class="kwrd">new</span> ValidationException(ruleExceptions);
        }

        <span class="kwrd">return</span> getNext()(input, getNext);
    }

    <span class="kwrd">private</span> IEnumerable&lt;RuleException&gt; ValidateEachArgument(IParameterCollection arguments)
    {
        var ruleExceptions = <span class="kwrd">new</span> List&lt;RuleException&gt;();

        <span class="kwrd">foreach</span> (var arg <span class="kwrd">in</span> arguments)
        {
            ruleExceptions.AddRange(validator.Validate(arg));
        }

        <span class="kwrd">return</span> ruleExceptions;
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Order { get; set; }
}</pre>
<p>Phew, we’re almost done. The only thing left is to apply this validator in configuration so I can keep the Unity reference out of my core domain. That looks like this:</p>
<pre class="csharpcode">container.AddNewExtension&lt;Interception&gt;()
    .Configure&lt;Interception&gt;()
    .SetInterceptorFor&lt;IUserService&gt;(<span class="kwrd">new</span> InterfaceInterceptor())
    .AddPolicy(<span class="str">&quot;UserServiceValidationPolicy&quot;</span>)
    .AddCallHandler&lt;ValidationCallHandler&gt;()
    .AddMatchingRule&lt;AlwaysApplyMatchingRule&gt;();</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/validation-with-unity-interception/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Happens When You Actually Use AOP for Logging?</title>
		<link>http://www.agileatwork.com/what-happens-when-you-actually-use-aop-for-logging/</link>
		<comments>http://www.agileatwork.com/what-happens-when-you-actually-use-aop-for-logging/#comments</comments>
		<pubDate>Mon, 06 Jul 2009 04:48:57 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[Composite Pattern]]></category>

		<guid isPermaLink="false">http://www.agileatwork.com/?p=139</guid>
		<description><![CDATA[Everybody’s favorite example for AOP is logging. There are a few reasons for that. First, it’s a great problem to solve with AOP and chances are it’s something everyone can relate to. Well, what happens when you actually use it for logging?
I can tell you what happened to me last week. Things were going great [...]]]></description>
			<content:encoded><![CDATA[<p>Everybody’s favorite example for AOP is logging. There are a few reasons for that. First, it’s a great problem to solve with AOP and chances are it’s something everyone can relate to. Well, what happens when you actually use it for logging?</p>
<p>I can tell you what happened to me last week. Things were going great until it came time to port our credit card charging program from the stone age to .NET. It occurred to me that our fancy AOP logging would unknowingly log decrypted credit cards!</p>
<p>&#160;<img title="credit_cards" 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="180" alt="credit_cards" src="http://www.agileatwork.com/wp-content/uploads/2009/07/credit_cards1.jpg" width="240" border="0" /></p>
<p>An obvious solution was to do a regex on log messages and mask credit card numbers – and that’s pretty much what we did, but I didn’t want to perform a regex on <em>every</em> message when I knew only a tiny percentage would contain sensitive data. The solution of course, was to fight fire with fire and use more AOP.</p>
<p>This is how I wanted it to look:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">interface</span> IPayPalGateway
{
    [MaskCredCardForLogging]
    <span class="kwrd">string</span> Submit(<span class="kwrd">string</span> request, <span class="kwrd">string</span> id);
}</pre>
<p>This way I could specifically mark an interface that I knew would accept sensitive data and apply an appropriate filter to it. The log filtering is implemented as a decorator to a log4net-like <font face="Courier New" size="2">ILogger</font> interface.</p>
<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> LoggerWithFilterFixture
{
    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Should_apply_filter_to_message()
    {
        var logger = <span class="kwrd">new</span> InterceptingLogger();

        var loggerWithFilter = <span class="kwrd">new</span> LoggerWithFilter(logger, <span class="kwrd">new</span> AppendBangToMessage());

        loggerWithFilter.Debug(<span class="str">&quot;This is a message&quot;</span>);

        Assert.AreEqual(<span class="str">&quot;This is a message!&quot;</span>, logger.LastMessage);
    }
}

<span class="kwrd">public</span> <span class="kwrd">class</span> AppendBangToMessage : ILogFilter
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> Filter(<span class="kwrd">string</span> message)
    {
        <span class="kwrd">return</span> message + <span class="str">&quot;!&quot;</span>;
    }
}</pre>
<p>The decorator is then applied in the call handler by looking for custom attributes of type <font face="Courier New" size="2">LogFilterAttribute</font> like this:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> LoggerCallHandler : ICallHandler
{
    <span class="kwrd">public</span> IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        ILogger logger = GetLogger(input);

        <span class="kwrd">if</span> (logger.IsDebugEnabled)
        {
            logger.Debug(CreateLogMessage(input));
        }

        Stopwatch stopWatch = Stopwatch.StartNew();
        IMethodReturn result = getNext()(input, getNext);
        stopWatch.Stop();

        <span class="kwrd">if</span> (logger.IsDebugEnabled)
        {
            logger.Debug(CreateLogMessage(input, result, stopWatch));
        }

        <span class="kwrd">return</span> result;
    }

    ...

    <span class="kwrd">public</span> ILogger GetLogger(IMethodInvocation input)
    {
        var logger = CreateLogger(input);

        var filter = CreateLogFilter(input);

        <span class="kwrd">return</span> <span class="kwrd">new</span> LoggerWithFilter(logger, filter);
    }

    <span class="kwrd">private</span> ILogFilter CreateLogFilter(IMethodInvocation input)
    {
        var composite = <span class="kwrd">new</span> CompositeLogFilter();

        <span class="kwrd">foreach</span> (LogFilterAttribute attribute
            <span class="kwrd">in</span> input.MethodBase.GetCustomAttributes(<span class="kwrd">typeof</span>(LogFilterAttribute), <span class="kwrd">true</span>))
        {
            composite.Add(attribute.CreateLogFilter());
        }

        <span class="kwrd">return</span> composite;
    }
}</pre>
<p>I’ll spare you the actual credit card masking logic:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MaskCreditCardForLoggingAttribute : LogFilterAttribute
{
    <span class="kwrd">public</span> <span class="kwrd">override</span> ILogFilter CreateLogFilter()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> CreditCardMaskingLogFilter();
    }
}

<span class="kwrd">public</span> <span class="kwrd">class</span> CreditCardMaskingLogFilter : ILogFilter
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> Filter(<span class="kwrd">string</span> message)
    {
        ...
    }
}</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/what-happens-when-you-actually-use-aop-for-logging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit of Work with Unity and ASP.NET MVC</title>
		<link>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/</link>
		<comments>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/#comments</comments>
		<pubDate>Sun, 10 May 2009 07:58:14 +0000</pubDate>
		<dc:creator>Michael Valenty</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[AOP]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://blog.agileatwork.com/?p=9</guid>
		<description><![CDATA[I was recently asked how I get the context of&#160; “this” in the UoW relating to the current page request.
 
Before I get into the guts, I would like to provide a little context. My application has 20+ databases scattered across 4 machines.

IRepository&#60;Customer&#62; customerRepository; // customer database on server 1
IRepository&#60;Package&#62;  packageRepository; // customer database [...]]]></description>
			<content:encoded><![CDATA[<p>I was recently asked how I get the context of&#160; “this” in the UoW relating to the current page request.</p>
<p><a href="http://blog.agileatwork.com/wp-content/uploads/2009/05/howididit.jpg"><img title="howididit" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="179" alt="howididit" src="http://blog.agileatwork.com/wp-content/uploads/2009/05/howididit-thumb.jpg" width="240" border="0" /></a> </p>
<p>Before I get into the guts, I would like to provide a little context. My application has 20+ databases scattered across 4 machines.</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<pre class="csharpcode">IRepository&lt;Customer&gt; customerRepository; <span class="rem">// customer database on server 1</span>
IRepository&lt;Package&gt;  packageRepository; <span class="rem">// customer database on server 1</span>
IRepository&lt;Contact&gt;  contactRepository; <span class="rem">// contact database on server 2</span></pre>
<div>So, I might ask for a Customer object and a Package object and I want to get the same ISession for both and if I ask for the same Customer twice, I want to get the one from the 1st level cache (I’m using NHibernate). If I ask for a Contact object, I will get a different ISession. All opened sessions are managed by my UoW. So, when the page request is complete, I call UoW.Commit and all sessions are committed.</div>
<p>The “magic” if you will, happens in the global.asax. I was nosing around in Rhino.Commons for inspiration and adapted a technique I saw there. This is how it looks:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> GlobalApplication : HttpApplication
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IUnityContainer container;

    <span class="kwrd">public</span> GlobalApplication()
    {
        BeginRequest += <span class="kwrd">new</span> EventHandler(GlobalApplication_BeginRequest);
        EndRequest += <span class="kwrd">new</span> EventHandler(GlobalApplication_EndRequest);
    }

    <span class="kwrd">protected</span> <span class="kwrd">void</span> Application_Start(<span class="kwrd">object</span> sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);

        container = <span class="kwrd">new</span> UnityContainer();
        container.AddNewExtension&lt;PolicyInjectorContainerExtension&gt;();
        container.AddNewExtension&lt;HttpRequestLifetimeCoreContainerExtension&gt;();
        container.AddNewExtension&lt;WebMvcContainerExtension&gt;();

        ControllerBuilder.Current.SetControllerFactory(<span class="kwrd">new</span> UnityControllerFactory(container));
    }

    <span class="kwrd">void</span> GlobalApplication_BeginRequest(<span class="kwrd">object</span> sender, EventArgs e)
    {
        var unitOfWork = container.Resolve&lt;IUnitOfWork&gt;();
        unitOfWork.Start();
    }

    <span class="kwrd">void</span> GlobalApplication_EndRequest(<span class="kwrd">object</span> sender, EventArgs e)
    {
        var unitOfWork = container.Resolve&lt;IUnitOfWork&gt;();
        unitOfWork.Commit();
    }
}</pre>
<p>I register the UoW with an HttpRequestLifetimeManager so I get a new instance for each request.</p>
<pre class="csharpcode">Container.RegisterType&lt;IUnitOfWork&lt;ISession&gt;,
	NHibernateUnitOfWork&gt;(<span class="kwrd">new</span> HttpRequestLifetimeManager());</pre>
<div>My NHibernateRepository gets injected with the UoW for the current HttpRequest and when the request is complete, the global.asax commits the whole thing.</div>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> NHibernateRepository&lt;T&gt; : IRepository&lt;T&gt;
{
    <span class="kwrd">protected</span> ISession session;

    <span class="kwrd">public</span> NHibernateRepository(IUnitOfWork&lt;ISession&gt; unitOfWork)
    {
        session = unitOfWork.GetContextFor&lt;T&gt;();
    }

    ...

    <span class="kwrd">public</span> <span class="kwrd">virtual</span> <span class="kwrd">void</span> Save(T obj)
    {
        session.Save(obj);
    }
}</pre>
<p>Now, this is all the context of an ASP.NET MVC Controller, but I have a similar issue for other (non-web) services. In that context I am using AOP and decorating a particular method with [UnitOfWork], which looks like:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> UnitOfWorkCallHander : ICallHandler
{
    <span class="kwrd">private</span> IUnitOfWork&lt;ISession&gt; unitOfWork;

    <span class="kwrd">public</span> UnitOfWorkCallHander(IUnitOfWork&lt;ISession&gt; unitOfWork)
    {
        <span class="kwrd">this</span>.unitOfWork = unitOfWork;
    }

    <span class="kwrd">public</span> <span class="kwrd">int</span> Order { get; set; }

    <span class="kwrd">public</span> IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        unitOfWork.Start();

        <span class="kwrd">try</span>
        {
            <span class="kwrd">return</span> getNext()(input, getNext);
        }
        <span class="kwrd">finally</span>
        {
            unitOfWork.Commit();
        }
    }
}</pre>
<p>In that context I use a PerThreadLifetimeManager for the NHibernateUnitOfWork, and code ends up looking like:</p>
<pre class="csharpcode">[UnitOfWork]
<span class="kwrd">public</span> <span class="kwrd">void</span> Process(Job job)
{
    ...
}</pre>
<p>You know, there is really no reason why you couldn’t do the same thing in the MVC context. You could basically ditch the global.asax event hooha and just annotate the Controller task:</p>
<pre class="csharpcode">[UnitOfWork]
<span class="kwrd">public</span> ActionResult ControllerTaskThatRequiresUoW()
{
    ...
}</pre>
<p>It’s more explicit than using the global.asax technique and it would allow you to specify different UoW behavior on each controller task:</p>
<pre class="csharpcode">[UnitOfWork(IsolationLevel.ReadCommitted]
<span class="kwrd">public</span> ActionResult SomeTaskThatShouldNotReadUncommitedData()
{
}

[UnitOfWork(IsolationLevel.ReadUncommitted)]
<span class="kwrd">public</span> ActionResult AnotherTaskWithDifferentRequirements()
{
}</pre>
<p>I’d like to try this out next time I get back into ASP.NET MVC, the global.asax event technique felt a little too magical and I don’t think Uncle Bob would approve.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agileatwork.com/unit-of-work-with-unity-and-aspnet-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

