> Mike Valenty

Validation With Unity Interception

| Comments

This is how I want things to look:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class UpdateUserRequest
{
    [AuthorizedUserPublisherRequired]
    public int UserId { get; set; }

    [Required("Name is required")]
    public string Name { get; set; }

    [ValidZipCodeRequired("Invalid zip code")]
    public string ZipCode { get; set; }
}

public interface IUserService
{
    void Update(UpdateUserRequest request);
}

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:

  1. How do I get dependencies into the validators?
  2. How do I get ValidZipCodeRequired to fire with the value of the ZipCode property
  3. How do I initiate this on userService.Update()?

Let’s take a look at building up the validators.

1
2
3
4
5
6
7
public class ValidZipCodeRequiredAttribute : ValidatorAttribute
{
    public override IValidator CreateValidator(IValidatorFactory factory)
    {
        return new factory.Create<ValidZipCodeRequiredValidator>();
    }
}

This allows me to make a UnityValidatorFactory that can supply all my dependencies. Now how about this business of running the ValidZipCodeRequiredValidator with the value of the ZipCode property? For that I made a composite validator that loops through each property and runs the annotated validator against it’s property value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class CompositeValidator<T> : IValidator<T>
{
    private IValidatorFactory factory;

    public CompositeValidator(IValidatorFactory factory)
    {
        this.factory = factory;
    }

    public IEnumerable<RuleException> Validate(T subject)
    {
        List<RuleException> exceptions = new List<RuleException>();

        foreach (PropertyInfo property in typeof(T).GetProperties())
        {
            foreach (var validator in GetValidatorsFor(property))
            {
                exceptions.AddRange(validator.Validate(property.GetValue(subject, null)));
            }
        }

        return exceptions;
    }

    private IEnumerable<IValidator> GetValidatorsFor(ICustomAttributeProvider provider)
    {
        foreach (ValidatorAttribute attribute
            in provider.GetCustomAttributes(typeof(ValidatorAttribute), true))
        {
            yield return attribute.CreateValidator(factory);
        }
    }
}

Now I just need to run the CompositeValidator on userService.Update(). For that I use Unity Interception:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class ValidationCallHandler : ICallHandler
{
    private IValidator validator;

    public ValidationCallHandler(IValidator validator)
    {
        this.validator = validator;
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var ruleExceptions = ValidateEachArgument(input.Arguments);

        if (ruleExceptions.Count() > 0)
        {
            throw new ValidationException(ruleExceptions);
        }

        return getNext()(input, getNext);
    }

    private IEnumerable<RuleException> ValidateEachArgument(IParameterCollection arguments)
    {
        var ruleExceptions = new List<RuleException>();

        foreach (var arg in arguments)
        {
            ruleExceptions.AddRange(validator.Validate(arg));
        }

        return ruleExceptions;
    }

    public int Order { get; set; }
}

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:

1
2
3
4
5
6
container.AddNewExtension<Interception>()
    .Configure<Interception>()
    .SetInterceptorFor<IUserService>(new InterfaceInterceptor())
    .AddPolicy("UserServiceValidationPolicy")
    .AddCallHandler<ValidationCallHandler>()
    .AddMatchingRule<AlwaysApplyMatchingRule>();

What Happens When You Actually Use AOP for Logging?

| Comments

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 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!

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 every 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.

This is how I wanted it to look:

1
2
3
4
5
public interface IPayPalGateway
{
    [MaskCredCardForLogging]
    string Submit(string request, string id);
}

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 ILogger interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[TestFixture]
public class LoggerWithFilterFixture
{
    [Test]
    public void Should_apply_filter_to_message()
    {
        var logger = new InterceptingLogger();

        var loggerWithFilter = new LoggerWithFilter(logger, new AppendBangToMessage());

        loggerWithFilter.Debug("This is a message");

        Assert.AreEqual("This is a message!", logger.LastMessage);
    }
}

public class AppendBangToMessage : ILogFilter
{
    public string Filter(string message)
    {
        return message + "!";
    }
}

The decorator is then applied in the call handler by looking for custom attributes of type LogFilterAttribute like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class LoggerCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        ILogger logger = GetLogger(input);

        if (logger.IsDebugEnabled)
        {
            logger.Debug(CreateLogMessage(input));
        }

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

        if (logger.IsDebugEnabled)
        {
            logger.Debug(CreateLogMessage(input, result, stopWatch));
        }

        return result;
    }

    ...

    public ILogger GetLogger(IMethodInvocation input)
    {
        var logger = CreateLogger(input);

        var filter = CreateLogFilter(input);

        return new LoggerWithFilter(logger, filter);
    }

    private ILogFilter CreateLogFilter(IMethodInvocation input)
    {
        var composite = new CompositeLogFilter();

        foreach (LogFilterAttribute attribute
            in input.MethodBase.GetCustomAttributes(typeof(LogFilterAttribute), true))
        {
            composite.Add(attribute.CreateLogFilter());
        }

        return composite;
    }
}

I’ll spare you the actual credit card masking logic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MaskCreditCardForLoggingAttribute : LogFilterAttribute
{
    public override ILogFilter CreateLogFilter()
    {
        return new CreditCardMaskingLogFilter();
    }
}

public class CreditCardMaskingLogFilter : ILogFilter
{
    public string Filter(string message)
    {
        ...
    }
}

Auto-Mocking Unity Container Extension

| Comments

Using a container for unit testing is a good way to insulate your tests from changes in object construction. Typically my first test will be something pretty boring just to get the process started. A few tests later, the real behavior comes out along with new dependencies. Rather than having to go back and add the dependencies to all the tests I’ve already written, I like to use a container to build up the object I’m testing.

To streamline this process, I thought it would be handy to use a container extension to auto generate mocks for any required interface that wasn’t explicitly registered. The best way I can explain this is with code, so here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[SetUp]
public void SetUp()
{
    container = new UnityContainer()
        .AddNewExtension<AutoMockingContainerExtension>();
}
 
[Test]
public void Should_be_really_easy_to_test()
{
    container
        .RegisterMock<IDependencyThatNeedsExplicitMocking>()
        .Setup(d => d.MyMethod(It.IsAny<int>()))
        .Returns("I want to specify the return value");

    var service = container.Resolve<ServiceWithThreeDependencies>();
    var result = service.DoSomething();

    Assert.That(result, Is.EqualTo("I didn't have to mock the other 2 dependencies!"));
}

It really reduces the noise level in tests and lets you focus on the interesting parts of your application. Here’s the code for the container extension:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class AutoMockingContainerExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        var strategy = new AutoMockingBuilderStrategy(Container);

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

    class AutoMockingBuilderStrategy : BuilderStrategy
    {
        private readonly IUnityContainer container;

        public AutoMockingBuilderStrategy(IUnityContainer container)
        {
            this.container = container;
        }

        public override void PreBuildUp(IBuilderContext context)
        {
            var key = context.OriginalBuildKey;

            if (key.Type.IsInterface && !container.IsRegistered(key.Type))
            {
                context.Existing = CreateDynamicMock(key.Type);
            }
        }

        private static object CreateDynamicMock(Type type)
        {
            var genericMockType = typeof(Mock<>).MakeGenericType(type);
            var mock = (Mock)Activator.CreateInstance(genericMockType);
            return mock.Object;
        }
    }
}

In case you’re wondering about container.RegisterMock<>, it’s just extension method that you can read about here.

Captcha and Inversion of Control

| Comments

I made a few tweaks to a captcha library I found here and basically wrapped their CaptchaImage object in a service interface to use in my application. Pretty easy stuff, but I didn’t get it right the first time.

What’s wrong with this class?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class HttpContextCacheCaptchaProvider : ICaptchaProvider
{
    private const string httpContextCacheKey = "4D795A45-8015-475C-A6C4-765B09EB9955";
    private ICaptchaImageFactory factory;
    private HttpContextBase context;

    public HttpContextCacheCaptchaProvider(ICaptchaImageFactory factory, HttpContextBase context)
    {
        this.factory = factory;
        this.context = context;
    }

    public void Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        context.Cache[httpContextCacheKey] = captchaImage.Text; // hint

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

    public bool Verify(string text)
    {
        string captchaText = (string)context.Cache[httpContextCacheKey]; // hint

        if (text == null || captchaText == null)
            return false;
        else
            return text.ToLower().Equals(captchaText.ToLower());
    }
}

Perhaps your nose can lead you in the right direction. The smell is hard to test, and it’s hard to test because it requires mocking the HttpContextBase. You might say “no problem, I can blast out a stub with Moq in no time” but you’re missing the real problem. That would be like taking aspirin for a brain tumor.

It’s not a tumor

The real problem is this class is violating the Single Responsibility Principle (SRP) by doing more than one thing. I don’t mean the two methods Render() and Verify(), those are a cohesive unit operating on the same data. The other thing is lifetime management. Look how simple the class gets when you invert control and take out the notion of lifetime management:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
[Serializable]
public class LifetimeManagedCaptchaProvider : ICaptchaProvider
{
    private ICaptchaImageFactory factory;
    private string captchaText;

    public LifetimeManagedCaptchaProvider(ICaptchaImageFactory factory)
    {
        this.factory = factory;
    }

    public void Render(Stream stream)
    {
        CaptchaImage captchaImage = factory.Create();

        captchaText = captchaImage.Text;

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

    public bool Verify(string text)
    {
        if (text == null || captchaText == null)
            return false;
        else
            return text.ToLower().Equals(captchaText.ToLower());
    }
}

Now this class is a breeze to test and all you have to do is register it like this:

1
2
Container.RegisterType<ICaptchaProvider, LifetimeManagedCaptchaProvider>(
    new HttpSessionStateLifetimeManager());

The moral of the story is let your IoC container do things it’s good at.

This Could Have Been a Stored Procedure

| Comments

I read Domain Driven Design about a year and a half ago and when I got to the part about the specification pattern, I thought it was really cool and I couldn’t wait to try it out. Maybe the pattern gods were listening or maybe I was unknowingly using the secret. Either way, it was pretty much the next morning that I went to work and had the perfect project dropped in my lap.

Our phone system routes live phone calls to doctor’s offices and the project was to bill the doctor if the call met the following criteria:

  1. Caller is a new patient (pressed “1” instead of “2” in response to a voice prompt)
  2. A live call was connected for more than 20 seconds or message longer than 10 seconds was recorded.
  3. The doctor has not already been billed for this caller.
  4. The call is not from a known list of test numbers.

The application subscribes to an event stream of new call records and runs them through this composite specification to determine if the call is billable.

1
2
3
4
5
6
7
8
9
public bool IsBillable(CallRecord call)
{
    ISpecification<CallRecord> billableCallSpecification = new NewPatient()
        .And(new MinLengthLiveCall(liveCallSeconds).Or(new MinLengthMessage(messageSeconds))
        .And(new RepeatCall(referralFinder).Not())
        .And(new TestCall(testNumbers).Not()));

    return billableCallSpecification.IsSatisfiedBy(call);
}

I have to admit that I was already an hour into Query Analyzer blasting through another monster stored procedure when I caught myself. Not just the criteria logic either, I mean bypassing all the event stream hooha and basically just writing the whole enchilada as one gnarly stored procedure that would run as a job. That was a close one!