Showing posts with label Aspect Oriented Programming. Show all posts
Showing posts with label Aspect Oriented Programming. Show all posts

Friday, December 9, 2011

Aspect Oriented Programming and Interceptor pattern - Creating a Session handler for ASP.NET


Interceptor pattern can be used for addressing cross cutting concerns in the application that happens at either the beginning or end of a method. For e.g. checking the validity of the input parameters before executing the method and throwing exceptions, catching and logging exceptions etc. These situations can be encapsulated in a reusable component that can be processed by the compiler and produce executable code (AOP).
Unity allows developers to implement the idea of interception by allowing creation of objects that can add some extra code on the target method before or after the regular execution of these target methods. In this post, I'll show how to create a Session handler for ASP.Net using the interface interception mechanism provided by unity application block, that will allow you to address encapsulate the logic for checking session for a value before execution of the method and returning back the value from session if available. The same handler can be used to also add the return value to the session if not available so that this value can be retrieved next time.
Creating the session handler
public class SessionHandler : ICallHandler
{
    private readonly string _sessionKey;

    public SessionHandler(string sessionKey)
    {
        _sessionKey = sessionKey;
    }

    public ISessionService SessionService
    {
        get { return Container.Instance.Resolve<ISessionService>(); }
    }

    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        if (SessionService.Contains(_sessionKey))
        {
            input.CreateMethodReturn(SessionService.Get(_sessionKey));
            return getNext()(input, getNext);
        }

        var returnValue = getNext()(input, getNext);
        SessionService.Add(_sessionKey, returnValue.ReturnValue);
        return returnValue;
    }

    public int Order { get; set; }
}

The session handler uses the session service which encapsulates the actual Session object to add/ remove values from the session.  You can also use the HttpContext.Current.Session object here.
Creating the Attribute for the handler
public class SessionDependencyAttribute : HandlerAttribute
{
    private readonly string _sessionKey;
       
    public SessionDependencyAttribute(string sessionKey)
    {
        _sessionKey = sessionKey;
    }

    public override ICallHandler CreateHandler(IUnityContainer container)
    {
        return new SessionHandler(_sessionKey);
    }
}

Creating a service and using the SessionHandler we created.
public interface IMockService
{
    [SessionDependency("TestKey")]
    string GetValue(bool flag);
}

public class MockService : IMockService
{
    public string GetValue(bool flag)
    {
        return flag ? "True" : "False";
    }
}

Configuring the Unity container
_container = new UnityContainer();
_container.AddNewExtension<Interception>();


_container
    .RegisterType<ISessionService, SessionService>()
    .RegisterType<IMockService, MockService>()
    .RegisterType<MockPresenter>()
    .Configure<Interception>().SetDefaultInterceptorFor<IMockService>(new InterfaceInterceptor());

Test cases
[TestMethod]
public void MethodShouldReturnValueFromSessionIfValueDoesNotExistsAndAddToSession()
{
    var service = Container.Instance.Resolve<IMockService>();
    var actual = service.GetValue(true);

    Assert.IsTrue(SessionService.Contains("TestKey"));
}

Wednesday, December 30, 2009

Unity Application Block – Complete series


The links for the unity application block tutorials from my site.

Unity Application Block – Creating an Handler for exception application block


As mentioned in my previous post, Unity can be used to address cross cutting concerns by registering and invoking interceptors. In this post, I’ll show how to create an Exception handler for the enterprise library exception block using unity to reduce the cross concerns in your code for exception handling.
Step 1: Create ICallHanlder implementation
public class ExceptionCallHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        var __Result = getNext()(input, getNext);
        if (__Result.Exception == null)
            return __Result;
        var __Rethrow = ExceptionPolicy.HandleException(__Result.Exception, "MyExceptionPolicy");
        if (__Rethrow) throw __Result.Exception;
        else throw new ArgumentException("An exception occured");
    }

    public int Order { get; set; }
}
Step 2: Create an attribute for Exception Handling
public class ExceptionCallHandlerAttribute : HandlerAttribute
{
    public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
    {
        return new ExceptionCallHandler();
    }

Step 3: Use the handler attribute in your code.
[ExceptionCallHandler]
void Update(T instance);
Step 4: Configure the container
IUnityContainer ___Container = new UnityContainer();
___Container.AddNewExtension<Interception>();
___Container.RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
___Container.Configure<Interception>().SetDefaultInterceptorFor<IRepository<Employee, Guid>>(new TransparentProxyInterceptor());

It’s that simple to remove the try catch blocks from your code!!!

Tuesday, April 15, 2008

Aspect Oriented Programing and Policy Injection Application Block (Part - 2)

As mentioned in Part 1 of this article series, The Policy Injection Application Block is used to seperate the core concerns of the entity by using handlers available in the block. You can also create your own custom handlers by implementing the ICallHandler interface.

PIAB can be used to specify crosscutting behavior of objects in terms of a set of policies. A policy is the combination of a series of handlers that execute when client code calls methods of the class and—with the exception of attribute-based policies—a series of matching rules that select the classes and class members (methods and properties) to which the application block attaches the handlers.

A handler can be defined either

• By decorating class members with an attribute that will declaratively define the handler to be used

OR

• By defining the class type and class member on which the handler will act

A common scenario when using any policy injection framework is the requirement to specify policies for classes and their members using attributes directly applied to the appropriate classes and members. The PIAB supports this technique; this means the only configuration required is the addition of the application block to the Enterprise Library configuration for the application. After that, the application block actively discovers classes and members with the attributes defined within the Policy Injection Application Block applied, and then the application block applies the appropriate policies.

Some of the common scenario where PIAB can be used in your application includes

  • Logging Method Invocation and Property Access
  • Handling Exceptions in a Structured Manner
  • Validating Parameter Values
  • Caching Method Results and Property Values
  • Authorizing Method and Property Requests
  • Measuring Target Method Performance

In the below given example I have used PIAB to handle exceptions, Caching and Validation purposes.

public class User : IUser

{

#region IUser Members

[ExceptionCallHandler("My Exception Policy")]

[CachingCallHandler]

public Collection<Int32> GetUserIDs()

{

return GetUserIDsFromDB();

}

private Collection<Int32> GetUserIDsFromDB()

{

Collection<Int32> ids = new Collection<Int32>();

ids.Add(1);

ids.Add(2);

System.Windows.Forms.MessageBox.Show("Getting ID's from DB");

return ids;

}

[ExceptionCallHandler("My Exception Policy")]

[ValidationCallHandler]

public void UpdateAge([RangeValidator(typeof(Int32), "20", RangeBoundaryType.Inclusive, "100", RangeBoundaryType.Exclusive)] Int32 age, Int32 index)

{

//Implementation code goes here

}

#endregion

}

After having the entity created with the appropriate handlers for avoiding cross concerns you can use the PIAB factory class methods for creating or obtaining object instances:
  • Create: This method creates a new instance of a policy-enabled interceptable target object.
  • Wrap: This method adds policies to existing interceptable target object instances.

IUser user = PolicyInjection.Create<User, IUser>();

And call the interface methods like

Collection<Int32> usersids = user.GetUserIDs();

The implementation of a system that automatically creates a proxy and handler pipelines for methods is similar to the aspect-oriented programming (AOP) approach. However, the Policy Injection Application Block is not an AOP framework implementation for the following reasons:
• It uses interception to enable only pre-processing handlers and post-processing handlers.
• It does not insert code into methods.
• It does not provide interception for class constructors.

Aspect Oriented Programing and Policy Injection Application Block (Part -1)

In Object Oriented programming classes and methods are designed for performing specific operations and common/duplicate functionality are factored out into common classes. However, there are cross-cutting concerns that span across all classes and methods, like logging, caching, exception handling, security etc.

The separation of concerns is a major consideration for any programming language. In the simplest terms, a concern is a modular unit of code that has a specific purpose. All programming methodologies, in some way or another, handle the separation of concerns by encapsulating them into some entity. In procedural languages, concerns are defined within procedures. In object-oriented languages, concerns are defined within classes. However, some concerns cannot be bound to these constructs.

For example, in my User class, I have used the exception handling code for the methods as given below.

public class User : IUser
{

#region IUser Members


public void Insert(IUser user)
{
try
{
//Implementation code goes here
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex,"My Exception Policy");
}
}

public void Remove(int index)
{
try
{
//Implementation code goes here
}
catch (Exception ex)
{
ExceptionPolicy.HandleException(ex, "My Exception Policy");
}
}

#endregion
}

During the process it was necessary for me to repeat the same code for Exception Handling in different functions. These types of cross-cutting concerns can be found in various regions of my code. Cross cutting concerns can occur in coding validation, caching etc also. Aspect oriented programming attempts to address these cross cutting concerns and eliminate repetitive and intermixing code in your application.

Aspect Oriented Programming model encapsulates these cross-cutting concerns using the following concepts

Join-points: The points in the structure of base-code where the cross-cutting functionality needs to execute. This can be method call, functions, properties etc.
Point-cut: A logical description of join-points using some specific syntax. Point-cut tells us when we should match a join point.
Advice: Decides the sequence of execution of advice code with respect to joint point. Additional code like exception, logging, validation and security check that each of these methods need to perform

Implementing Aspect Oriented Programming in .NET

In .NET, two approaches can be taken in aspect-oriented programming, Compile-time weaving, and Runtime weaving. Weaving is injecting instructions into the application.

Compile-time weaving happens at the compiler level and Code is injected into the source code of an application to address the cross-cutting concerns. Runtime weaving is done by using the .NET runtime. Instructions are injected at runtime, typically through the use of a proxy object that the consuming object sees as the original object. This behaves the same way as Remoting does.

There are lot of posts and blogs available for implementing AOP in C#. In this article series (Part 2) I will try to explain how the Policy Injection Application Block (PIAB) can be used to separate the core concerns of the entity, such as business logic, from the cross-cutting concerns (Exception, Logging etc) that are required to develop an application.