Archive

Source code used in these blog posts is available on GitHub

How many times have you written something like this:

private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
    get
    {
        if(_productRepository == null)
        {
            _productRepository = new ProductRepository();
        }
        return _productRepository;
    }
}

This is a piece of code that you might write dozens or more times to be able to use a repository to return some data to use in your application. If you're in a hurry, it's a quick way to get something that works, and also an easy way to get some lazy loading in place so that the repository doesn't instantiate until you need it to. Unfortunately, this piece of code incurs technical debt. And the more you use this boilerplate elsewhere in your code, the more technical debt you incur.

There are two things in this code that are incurring the debt: hardwired dependencies and boilerplate code.

Generally, I prefer to use an IoC container to wire up these sort of dependencies for me, but that isn't always possible or easy to do, especially when I'm programming within a framework that doesn't have dependency injection in mind (WinForms/WebForms, etc). It's not impossible to do DI on those frameworks without PostSharp, but it's certainly a lot more work.

While the property itself is of type IProductRepository, the getter of that property is still hard-wired to ProductRepository. If you need to change "new ProductRepository()" to "new RevisedProductRepository()" or even "new ProductRepository(2011)", you must go through each instance of your boilerplate and update the code. Sure, you could try a find & replace, but each other programmer on your team could be making changes, tweaks, adjustments, and now a find & replace might break something, or might not even work. Wouldn't it be better to have those dependencies configured in one central place, instead of scattered throughout your entire app? Using a service locator from an IoC framework, for instance, you could get this:

private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
    get
    {
        if(_productRepository == null)
        {
            _productRepository = ObjectFactory.GetInstance<IProductRepository>();
        }
        return _productRepository;
    }
}

And now the ObjectFactory will take care of the instantiations. If you want to plug in a new concrete implementation, wrap the existing implementation, add constructor parameters, etc, now you can do it all in once place. (Note that "ObjectFactory" is a static class in StructureMap , but you could use any IoC container that you like). Now the code looks much better, and the development team doesn't have to worry about the implementation: only the interface. It's still a true dependency inversion, because now the class only depends on the interface, not the implementation.

The code is now much cleaner, but we still have a bunch of null checking and lazy loading scattered all over the app. If you decide to change to a different IoC container, you still have to make changes throughout your app. And if you get to the point where the simple null-checking strategy isn't good enough, then you have to change that everywhere too. Let's use PostSharp to centralize this logic, so you can save time and DRY up your code while you're at it.

[LoadDependency] private IProductRepository _productRepository;

[Serializable]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
    public override void OnGetValue(LocationInterceptionArgs args)
    {
        args.ProceedGetValue(); // fetches the field and populates the args.Value
        if (args.Value == null)
        {
            var locationType = args.Location.LocationType;
            var instantiation = ObjectFactory.GetInstance(locationType);

            if (instantiation != null)
            {
                args.SetNewValue(instantiation);
            }
            args.ProceedGetValue();
        }
    }
}

Now you have a very declarative way of using dependencies. You simply tag any field with the "LoadDependency" attribute, and it will be instantiated by your IoC container the first time you use it. You save yourself from having to write the same boilerplate properties over and over again, and the null-checking/lazy loading itself is now centralized into a single class (LoadDependencyAttribute).

With just a simple PostSharp aspect, we've compressed a 12-line lazy-loading property into a one-line field, with no hard-wired dependencies or boilerplate code. We've removed a lot of pointless repetition from the code (DRY ). We've replaced hard-wired dependencies with pure interfaces (DIP ). We've moved the lazy-loading into its own class, and dependency resolution into its own class (SRP ). Since PostSharp won't try to use the service locator if the field isn't null, you can easily use constructor injection as part of your testing instead of letting PostSharp load the real dependency. Our app is on the fast track to being a maintainable, easy to configure, and easy to test masterpiece.

This is a very helpful, and very simple example of how to use PostSharp to make your life easier.

Now suppose that the dependency mappings (like IProductRepository <-> ProductRepository in the above example) is already known at compile time. That is, the dependency will not change during runtime. In this case, you don't need to use a service locator at all. You can instead override the CompileTimeInitialize method in LocationInterceptionAspect to resolve the dependency at compile time (hence the name), and just store the type as a field. Then, at run time, you can use Activator.CreateInstance to do the instantiation.

[Serializable]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
    private Type _type;

    public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
    {
        _type = DependencyMap.GetConcreteType(locationInfo.LocationType);
        if(_type == null)
        {
            Message.Write(SeverityType.Error, "002",
					"A concrete type was not found for {0}.{1}",
					locationInfo.DeclaringType, locationInfo.Name);
            return false;
        }
        return true;
    }

    public override void OnGetValue(LocationInterceptionArgs args)
    {
        args.ProceedGetValue();
        if (args.Value == null)
        {
            form.LogListBox.Items.Add("Instantiating UserService");
            args.SetNewValue(Activator.CreateInstance(_type));
            args.ProceedGetValue();
        }
    }
}

If there isn't a type configured, then you will get a build time error instead of a runtime error. You are hopefully starting to see that PostSharp can be a very powerful tool. I'm not too keen on using this method to totally replace a runtime service locator, but I can certainly see where it would be useful in some select circumstances.

Another way to improve either of the above aspects is to do a compile-time check to validate that the aspect is being used correctly. For instance, using the LoadDependency attribute usually doesn't make sense if you apply it to a field that isn't an interface. Indeed, this would be a bad design, as it would make our dependencies hard coded again! So let's put some code into place to prevent this sort of code from even getting compiled. Just add one more check to the CompileTimeValidate method:

public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
{
    if(!locationInfo.LocationType.IsInterface)
    {
        Message.Write(SeverityType.Error, "001",
			"LoadDependency can only be used on Interfaces in {0}.{1}",
			locationInfo.DeclaringType, locationInfo.Name);
        return false;
    }

    _type = DependencyMap.GetConcreteType(locationInfo.LocationType);
    if(_type == null)
    {
        Message.Write(SeverityType.Error, "002",
			"A concrete type was not found for {0}.{1}",
			locationInfo.DeclaringType, locationInfo.Name);
        return false;
    }
    return true;
}

Go ahead and put LoadDependency on a non-interface field, compile, and this is what you'll see:

Visual Studio build error

And you'd get a similar message if you forgot to put a interface<->concrete mapping in the DependencyMap class too. This is such a great feature, because if you make a mistake, you will fail much faster in your testing, get a clear message of what exactly went wrong, and ultimately save a lot of time and frustration. Make sure to put as much information as you can in the error message, to make the error easy to find in the code, since you won't have line numbers to fall back on.

With just a simple aspect, we've turned our hard-coded dependencies and repetitive boilerplate code into a maintainable, testable, easy-to-read app that follows SOLID principles. More importantly, you will save a lot of time, not just in the development and testing phases of your project, but also in the (usually much longer) maintanence phase.

Matthew D. Groves is a software development engineer with Telligent, and blogs at mgroves.com.

Marcus King recently released 3 screencasts showing how to address exception handling and caching.
We asked him to introduce his work in this guest post.

How often do I have to keep solving the same problem?  As developers we’ve all been there, each project we work on we have to do the same ole’ thing we’ve done a thousand times before.  Luckily in most cases there are good native features built into the language or third party frameworks that are available to reduce the tedious chore of writing basic code yet again.  However, there are a lot of times when OOP doesn’t provide us with a good way to solve a recurring problem.  I’m guessing since your reading the SharpCrafter’s Blog you see that this is the point where AOP steps in and fills the gap left by OOP.  I recently did a video tutorial on improving exception handing  using AOP via PostSharp.  Traditionally in applications we need to catch when certain exceptions are thrown and do something with the exception by either logging it, calling another workflow, wrapping the exception inside of another one, or simply swallowing the exception, or some combination of all.  Let’s say for example we have a class we use to call a remote web service to retrieve data for our application.

public class StockService
{
    public StockDetails GetStockDetails( string symbol )
    {
        try
        {
            //.... call to service
        }
        catch ( SoapException ex )
        {
            throw new StockServiceException( "Error Getting Details", ex );
        }
    }

    public decimal GetHistoricalPrice( string symbol )
    {
        try
        {
            //.... call to service
        }
        catch ( SoapException ex )
        {
            throw new StockServiceException( "Error Getting Historical Price", ex );
        }
    }

    public void AddToPortfolio( string symbol, int shares )
    {
        try
        {
            //.... call to service
        }

        catch ( SoapException ex )
        {
            throw new StockServiceException( "Error Adding to portfolio", ex );
        }
    }
}

Look how often we are repeating the same basic pattern.  We’re making our service call and wrapping any SoapException that is thrown in a custom StockServiceException.  Using PostSharp we are able to modularize our code and make the business logic of the StockService class look so much cleaner.

public class StockService
{
    [HandleException( SoapException, StockServiceException, 
"Error Getting Details" )] public StockDetails GetStockDetails( string symbol ) { //.... call to service } [HandleException( SoapException, StockServiceException,
"Error Getting Historical Price" )] public decimal GetHistoricalPrice( string symbol ) { //.... call to service } [HandleException( SoapException, StockServiceException,
"Error Adding To Portfolio" )] public void AddToPortfolio( string symbol, int shares ) { //.... call to service } }

All we need to do is create an attribute that derives from OnMethodBoundaryAspect that accepts three parameters in the constructor;  the type of exception to handle, the type of exception to wrap the caught exception in, and a message to give to the wrapped exception.

[Serializable]
public class HandleExceptionAttribute : OnExceptionAspect
{
    private Type _expectedException;
    private Type _wrapInException;
    private string _message;

    // Constructor that takes in variable parameters when the attribute is applied
    public HandleExceptionAttribute( Type expectedExeptionType, Type wrapInExceptionType, 
string message ) { _expectedException = expectedExceptionType; _wrapInException = wrapInExceptionType; _message = message; } // This method checks to see if the exception that was thrown from the method the // attribute was applied on matches the expected exception type we passed into the
// constructor of the attribute public override Type GetExceptionType( MethodBase targetMethod ) { return _expectedException; } // This method is called when we have guaranteed the exception type thrown matches the // expected exception type passed in the constructor. It wraps the thrown exception
// into a new exception and adds the custom message that was passed into the constructor public override void OnException( MethodExecutionArgs args ) { args.FlowBehavior = FlowBehavior.Continue; Exception newException = (Exception) Activator.CreateInstance(
_wrapInException, new object[] {_message, _expectedException} ); throw newException; } }

Another common problem set I solve with PostSharp is caching expensive method calls. I find myself repeating the same basic pattern in projects when I need to implement caching. I’m sure you’re familiar with it.

public Account GetAccount( int accountId )
{
    string cacheKey = string.Format( "GetAccount_{0}", accountId );

    Account account = Cache.Get( cacheKey );

    if ( account == null )
    {
        account = accountRepository.GetAccount( accountId );

        Cache.Add( cacheKey, account );
    }

    return account;
}

We build our cache key and check to see if the item is present if the cache. If it is we return the value pulled from the cache, otherwise we do the necessary work to retrieve/build the item to return and save it in the cache with the cache key we built so that the next time this method is called we can successfully pull the item from the cache. I’ve repeated this pattern over and over again, typically in a business layer when I need to retrieve data from an expensive resource like a database or a web service call or when I do complex logic to construct the object that I need to return. Luckily PostSharp provides a way to centralize all of the caching logic for me so I can concentrate on the business logic. The same method now looks like this

[Cache]
public Account GetAccount(int accountId)
{
    return accountRepository.GetAccount(accountId);
}

Once again I simply adorn the method with an attribute and it handles a lot of the repitive code. Here is what the Cache Attribute/Aspect code looks like.

public class CacheAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry( MethodExecutionArgs args )
    {
        string key = args.Method.Name + "_" + Cache.GenerateKey( args.Arguments );

        object value = Cache.Get( key );

        if ( value == null )
        {
            args.MethodExecutionTag = key;
        }

        else
        {
            args.ReturnValue = value;

            args.FlowBehavior = FlowBehavior.Return;
        }
    }

    public override void OnSuccess( MethodExecutionArgs args )
    {
        string key = args.MethodExecutionTag.ToString();

        Cache.Add( key, args.ReturnValue );
    }
}

In the OnEntry method I’m building the cache key and checking to see if the item exists in the cache and if so I’m not letting the target method complete and I’m returning the value pulled from cache. If no item was found in the cache, the execution of the target method proceeds and when the target method successfully executes the OnSuccess override is fired and the item is stored in the cache.

There are a lot more interesting things to do with the two areas of caching and exception handling so I would encourage you to check out my screen casts to learn more.

Exception Handling: http://www.sharpcrafters.com/media/tutorials/exception-handling

Cachinghttp://www.sharpcrafters.com/media/tutorials/caching-1

Going Further with Cachinghttp://www.sharpcrafters.com/media/tutorials/caching-2

 

marcus_king_image

Marcus King is a Software Engineer based in Louisville, KY. He has a broad IT background ranging from infrastructure security to software development, with years of experience working for many different sized companies, from Fortune 100 to small web startups. Marcus is passionate about performance tuning applications, developing solutions for highly scalable applications, plus is heavily involved in discovering and setting standards and best practices for software development. An Aspect-Oriented Programming (AOP) champion, Marcus regularly gives presentations on the topic. In his free time he writes applications for iPhone and Android and is on the executive committee of the codepaLOUsa developer conference in Louisville, KY.

Download the source code for this post.

Undo-redo is one of those features we don’t notice any more. It is however one of the most annoying to program because it requires so much menial code. Fortunately, aspect-oriented programming (AOP) renders this task virtually effortless.

There are two ways to implement an undo-redo feature. The first way, in a model-view-controller, is to put the feature inside the controller (each command implementation in the controller is responsible for generating another command, reversing the effect of the first one). The second way is to record all changes on the model. We’ll focus on this one and demonstrate how you could use an aspect to automatically record any change to domain objects.

Designing the undo-redo system

First, let me remind you that aspect-oriented programming is not opposed to object-oriented programming in any way; therefore a good aspect-oriented design must always start with a good object-oriented design.

In our design, every single change to a model object (such as changing the value of a field or added an object to a collection) is modeled as an object implementing the interface IUndoItem, with the following semantics:

public interface IUndoItem
{
  void Redo();
  void Undo();
}

Next we need an UndoManager. The manager has two kinds of clients (or consumers). First, domain objects (model) will call its Record operation whenever they are changed, so the manager will maintain a list of IUndoItem. Secondly, UI objects (or, possibly, the controller) will call its operations Undo and Redo. The core of the UndoManager is a double linked list of undo items and a cursor to the current item. When the UI invokes the Undo operation, the UndoManager invokes the Undo operation of the current item, and moves the cursor backward. When the UI invokes the Redo operation, the UndoManager invokes the Redo operation of the next item and moves the cursor forward.

Since the purpose of this article is to demonstrate the use of aspects and not to design or implement a general undo-redo system, I will not spend more time on the architecture and implementation of the manager.

Implementing the aspect

What do we want the aspect to do? Well, we need to intercept any change to a domain object field, wrap it into an IUndoItem, and record it using the UndoManager. This is pretty easy to do, since we can use aspects derived from LocationInterceptionAspect to hook any change to any field.

/// 
/// Aspect that, when applied on a field (directly or indirectly, using multicasting),
/// registers all changes to that field into the .
/// 
[Serializable]
[MulticastAttributeUsage( MulticastTargets.Field )]
public class UndoableAttribute : LocationInterceptionAspect
{
    /// 
    /// Method invoked whenever a field value is changed.
    /// 
    /// Information about the field being changed and 
    /// the new value.
    public override void OnSetValue( LocationInterceptionArgs args )
    {
        // Store the new and old values.
        object newValue = args.Value;
        object oldValue = args.GetCurrentValue();

        // If we're not changing anything, don't do anything.
        if ( Equals( newValue, oldValue ) )
            return;

        // Change the field value (or invoke the next aspect in chain).
        base.OnSetValue( args );

        // Record the change in the UndoManager.
        UndoManager.Record( new UndoField( args.Binding, args.Instance, oldValue, newValue ) );
    }

    /// 
    /// Encapsulates a change of field value as an .
    /// 
    private class UndoField : IUndoItem
    {
        private readonly ILocationBinding binding;
        private object instance;
        private readonly object oldValue;
        private readonly object newValue;

        public UndoField( ILocationBinding binding, object instance, 
object oldValue, object newValue ) { this.binding = binding; this.instance = instance; this.oldValue = oldValue; this.newValue = newValue; } public void Redo() { this.binding.SetValue(ref this.instance, Arguments.Empty, newValue ); } public void Undo() { this.binding.SetValue(ref this.instance, Arguments.Empty, oldValue ); } public bool CanUndo { get { return true; } } public bool CanRedo { get { return true; } } } }

The implementation is pretty simple, as you can read yourself: the method OnSetValue is invoked whenever a change of a field value is attempted; this method encapsulates the change as an instance of the UndoField class, and records it in the UndoManager.

The only difficulty is maybe to set the value of the field. We could use reflection (FieldInfo.SetValue), but it has two drawbacks: it is slow, and it would cause a recursion of the aspect: the change done during an undo operation would be recorded in the UndoManager. PostSharp addresses this issue with the notion of binding. When you assign a value to a field, you usually just think that you assign a value to a field, but PostSharp sees that a little differently: it considers you’re sending a message to the field, and this message is “set the value to x”. PostSharp considers aspects as filters between the sender and the receiver of the message. Every filter receives a binding: this is where the filter should send the message. A binding binds to the next filter in the chain or to the final receiver. The point of this message-passing mechanism is that it’s robust: you can’t mess with the order of aspects. Also, note that the message-passing mechanism is only a mental model; in reality, this is implemented as normal method calls, and is very resource-effective.

Using the aspect

Since the aspect class behaves as a custom attribute we could apply it to any field we want to make undoable. Of course, this is not very convenient, and that’s why we will use a combination of custom attribute multicasting (by applying on a class, we implicitly apply it to all fields of that class) and custom attribute inheritance (by applying on a class, we implicitly apply it to all derived classes). Supposing that the common ancestor of all domain classes is Entity, we would write:

[Undoable(AttributeInheritance = MulticastInheritance.Multicast)]
abstract class Entity
{
    public int ID;
}

That’s all you need to track changes to all fields of your domain objects. However, that’s not the end of the story: you still need to ensure that the type of all fields of domain classes is either a domain class itself, either value types (hint: see CompileTimeValidate in PostSharp documentation), and you have implement the design pattern for collection types (using standard OOP, this time).

Now you can see how AOP offers an elegant solution where conventional OOP alone requires a lot of code duplication. Indeed, in most projects, there are plenty of opportunities to use aspects.

Download the source code for this post.

Happy PostSharping!

-gael