<?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; Composite Pattern</title>
	<atom:link href="http://www.agileatwork.com/tag/composite-pattern/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>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>
	</channel>
</rss>

