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"));
}

Monday, November 28, 2011

Using Unity to Resolve Instances based on condition


Unity is a lightweight, extensible dependency injection container with support for nested containers that stores registrations and mappings between types and can instantiate the appropriate concrete types on demand. Identification of the registrations in unity can be done using a type and a name (optional).
You can use unity to register multiple implementations of the same type and later resolve the actual instance by passing the name for identifying the actual implementation. In this post we'll see how to resolve the instances registered in unity application block conditionally.
For e.g. I have created a sample interface and implementations as given below
public interface IMyObject
{
    string DoSomething();
}

public class MyObjectFirstImplementation : IMyObject
{
    public string DoSomething()
    {
        return "First";
    }
}

public class MyObjectSecondImplementation : IMyObject
{
    public string DoSomething()
    {
        return "Second";
    }
}

The registration of these components are done like
container
    .RegisterType<IMyObject, MyObjectFirstImplementation>(DependencyRegistrationKeys.FirstImplementation)
    .RegisterType<IMyObject, MyObjectSecondImplementation>(DependencyRegistrationKeys.SecondImplementation);

public static class DependencyRegistrationKeys
{
    public const string FirstImplementation = "FIRST_IMPLEMENTATION";
    public const string SecondImplementation = "SECOND_IMPLEMENTATION";
}

The factory class has a create method that accepts and object key to resolve the actual instances
public class MyObjectFactory
{
    public IMyObject Create(string objectKey)
    {
        return Container.Instance.Resolve<IMyObject>(objectKey);
    }
}

Tests
[TestMethod]
public void CreateMethodShouldReturnTheObjectImplementationBasedOnConditionPassed()
{
    var factory = new MyObjectFactory();
    var myObject = factory.Create(DependencyRegistrationKeys.FirstImplementation);

    Assert.IsInstanceOfType(myObject, typeof(MyObjectFirstImplementation));
}

Monday, November 21, 2011

The Specification Pattern - A Generic implementation


In this post I’m going to create a generic implementation of the specification pattern.
The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched against. As well as its usefulness in selection, it is also valuable forvalidation and for building to order. Every specification implementation needs to specify a method that evaluates a condition mentioned in the interface Ispecification as given below.
public interface ISpecification where T : class
{
    Expression<Funcbool>> SatisfiedBy();
}
The generic specification class implements the Ispecification interface as
public sealed class Specification : ISpecification where T : class
{
    readonly Expression<Funcbool>> _matchingCriteria;

    public Specification(Expression<Funcbool>> matchingCriteria)
    {
        if (matchingCriteria == null) throw new ArgumentNullException("matchingCriteria");

        _matchingCriteria = matchingCriteria;
    }

    public Expression<Funcbool>> SatisfiedBy()
    {
        return _matchingCriteria;
    }
}
Using this implementation we can create the AND specification as
public sealed class AndSpecification : ISpecification where T : class
{
    private readonly ISpecification _rightSideSpecification;
    private readonly ISpecification _leftSideSpecification;

    public AndSpecification(ISpecification leftSide, ISpecification rightSide)
    {
        if (leftSide == null) throw new ArgumentNullException("leftSide");
        if (rightSide == null) throw new ArgumentNullException("rightSide");

        _leftSideSpecification = leftSide;
        _rightSideSpecification = rightSide;
    }

    public ISpecification LeftSideSpecification
    {
        get { return _leftSideSpecification; }
    }

    public ISpecification RightSideSpecification
    {
        get { return _rightSideSpecification; }
    }

    public Expression<Funcbool>> SatisfiedBy()
    {
        var left = _leftSideSpecification.SatisfiedBy();
        var right = _rightSideSpecification.SatisfiedBy();

        return (left.And(right));
    }
}

The AND method is an extension method on the ISpecification and Expression<Funcbool>>  types
public static ISpecification AND(this ISpecification leftSpecification, ISpecification rightSpecification) where T : class
{
    return new AndSpecification(leftSpecification, rightSpecification);
}

public static Expression Compose(this Expression first, Expression second,
                                        Func<Expression, Expression, Expression> merge)
{
    var map =
        first.Parameters.Select((f, i) => new {f, s = second.Parameters[i]}).ToDictionary(p => p.s, p => p.f);
    var secondBody = ExpressionTreeParameterReplacer.ReplaceParameters(map, second.Body);
    return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
}

public static Expression<Funcbool>> AND(this Expression<Funcbool>> first,
                                                Expression<Funcbool>> second)
{
    return first.Compose(second, Expression.And);
}

The ExpressionTreeVisitor implementation to replace and join the parameters for these extension methods
public sealed class ExpressionTreeParameterReplacer : ExpressionVisitor
{
    private readonly Dictionary<ParameterExpression, ParameterExpression> _map;

    public ExpressionTreeParameterReplacer(Dictionary<ParameterExpression, ParameterExpression> map)
    {
        _map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
    }

    public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map,
                                                Expression exp)
    {
        return new ExpressionTreeParameterReplacer(map).Visit(exp);
    }

    protected override Expression VisitParameter(ParameterExpression p)
    {
        ParameterExpression replacement;
        if (_map.TryGetValue(p, out replacement))
            p = replacement;

        return base.VisitParameter(p);
    }
}

Now let’s look at a sample using the specification pattern implementation.
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string UserName { get; set; }
    public DateTime DateOfJoining { get; set; }
    public Address Address { get; set; }
}
public class Address
{
    public string Street { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class CountryNameSpecification  : ISpecification<Customer>
{
    private readonly string _countryName;

    public CountryNameSpecification(string countryName)
    {
        _countryName = countryName;
    }

    public Expression<Func<Customer, bool>> SatisfiedBy()
    {
        return new Specification<Customer>(c => c.Address.Country.Contains(_countryName)).SatisfiedBy();
    }
}

public class CustomerFirstNameSpecification :ISpecification<Customer>
{
    private readonly string _firstName;

    public CustomerFirstNameSpecification(string firstName)
    {
        _firstName = firstName;
    }

    public Expression<Func<Customer, bool>> SatisfiedBy()
    {
        return new Specification<Customer>(c => c.FirstName.Equals(_firstName)).SatisfiedBy();
    }
}

[TestMethod]
public void AndSpecificationShouldSatisfyIfBothExpressionsSatisfiesTheCondition()
{
    var customers = GetAllCustomers();

    var fooCountrySpecification = new CountryNameSpecification("Foo");
    var customerFirtNameSpecification = new CustomerFirstNameSpecification("Foo4");

    var andSpecification = fooCountrySpecification.AND(customerFirtNameSpecification);

    var results = customers.Where(andSpecification.SatisfiedBy());
    Assert.IsTrue(results.ToList().All(c => c.Address.Country.Contains("Foo") && c.FirstName.Equals("Foo4")));
}

[TestMethod]
public void OrSpecificationShouldSatisfyIfOnOfTheConditionsSatisfiesTheSet()
{
    var customers = GetAllCustomers();

    var fooCountrySpecification = new CountryNameSpecification("Foo");
    var abcCountrySpecification = new CountryNameSpecification("Abc");
    var pqrCountrySpecification = new CountryNameSpecification("Pqr");


    var orSpecification = fooCountrySpecification.OR(abcCountrySpecification).OR(pqrCountrySpecification);

    var results = customers.Where(orSpecification.SatisfiedBy());
    Assert.IsTrue(results.Count() == customers.Count());
}

Where GetAllCustomers return an Iqueryable resultset of customers with addresses.

Wednesday, September 14, 2011

Continuous Deployment – Automating ASP.Net web deployment using TeamCity and MSBuild

Of all the Lean Startup techniques, Continuous Deployment is by far the most controversial. Continuous Deployment is a process by which software is released several times throughout the day – in minutes versus days, weeks, or months. Continuous Flow Manufacturing is a Lean technique that boosts productivity by rearranging manufacturing processes so products are built end-to-end, one at a time (using singe-piece flow), versus the more prevalent batch and queue approach.
Continuous Deployment is Continuous Flow applied to software. The goal of both is to eliminate waste. The biggest waste in manufacturing is created from having to transport products from one place to another. The biggest waste in software is created from waiting for software as it moves from one state to another: Waiting to code, waiting to test, waiting to deploy. Reducing or eliminating these waits leads to faster iterations which is the key to success.” – Eric Ries

Continuous deployment is one of the new trends in agile development that ensures release of software in a faster and reliable manner. It also helps the team to deliver value to customers early and often. In this post I’ll show how to setup a continuous integration environment using TeamCity and MSBuild scripts created by using a Web deployment project deploy your website every time a check in happens into the source safe.

TeamCity is a user-friendly continuous integration (CI) server from jet brains that is available as a free download from the vendor website. You can use go to the website http://www.jetbrains.com/teamcity/ to get your free copy. I have also used the Web deployment project from MS for MSBuild script generations in this sample.

For setting up the automated deployment on a website, you can follow the below given steps.
  • Right click on the web application project for automated build and select Add Web Deployment Project

  • On the ‘Add Web Deployment Project’ dialog give an appropriate name for the deployment project and press OK. This web deployment project created for the web application is the build scripts for MSBUILD.

  • Next we can create the build configuration setup for the project. For this right click the solution and select Configuration manager.
  • Unselect the build option for ‘Debug’ and ‘Release’ configurations for the Deployment project.

  • On the Active solution configuration drop down select ‘New’

  • On the ‘New Solution Configuration’ dialog, enter the name for the deployment configuration and press OK. Close the configuration manager window by selecting Close.

  • Next we’ll create separate configuration options for staging environment. For e.g. the connection strings for the staging server will be different that the development environment. Right click the web application and add a new folder ‘Configuration’
  • In the Configuration folder add a new configuration file ‘ConnectionStrings.Staging.Config’ and include the connection strings for the staging environment in this file. These settings will be replaced with the connection strings section in the web.config file when the deployment is started.

  • We’ll now setup the deployment properties for the project. For that, right click the deployment project and select property pages.
  • Change the output folder to the location where the build output will be deployed to.

  • On the deployment section of the property pages, you can set transformations on the configuration options for the application. You can also mention the virtual directory options on this page. Save the settings by selecting OK.

  • Next we have to configure the project on Team city. Login to team city as administrator and navigate to the Administration tab. On the administration page, select ‘Create Project’. Give an appropriate name for the project and select ‘Create’ option on the page.

  • Next we have to configure the VSC settings used by TeamCity to obtain the source files for the build. For this select the VCS roots tab and click on ‘Create VCS roots’.
  • Select the type of source control from the ‘Type of VCS’ dropdown to enter the source control specific configuration entries. Enter the URL, username, password and other details for the sub version and click on Create to update the configuration information.

  • On the general tab, select ‘Create new build configuration’ to enter details for the build configuration. Enter a name for the build configuration and select VCS settings to continue.
  • On the next page enter details for the checkout directory and Select ‘Add build Step’.
  • Select MSBuild as the build runner and enter the name of solution as the Build file path option.

  • On the build triggering, select ‘Add new trigger’. And select VCS trigger to trigger the build on every check in done to the source safe. 


  • Select Save and you have successfully created an automated build setup for your web application.

Thursday, August 11, 2011

ASP.NET dependency injection using Unity Application Block


ASP.NET was not designed with the concepts of DI and IoC in mind. That makes it very difficult to actually configure a website/ application using ASP.NET to use the concepts of IoC and resolve the dependencies when the pages are requested. An easier way to resolve the dependencies on the page will be using the container and requesting for the resolved types for dependencies. A much better approach is to interpret the page creation implementation code in ASP.NET and resolve the dependencies on the Page from there. In this post I'll show a sample scenario where we'll intercept the page creation logic and resolve the dependencies on the page using Unity container.
The sample used in this article has views that have dependencies on the respective presenters. The presenters will depend on the service abstractions to do their work.
I have the base presenter and view interface declarations as
public abstract  class AppPresenter where T : IAppView
{
    public T View
    {
        get
        {
            if (HttpContext.Current == null) return DependencyInjection.Container.Resolve();
            return (T)HttpContext.Current.Handler;
        }
    }

    public abstract void InitializeViewEvents();
}

public interface IAppView
{
}

For resolving the dependencies on my views, I have created a custom PageHandler implementation which looks like.
public class UnityPageHandlerFactory : PageHandlerFactory
{
    public override IHttpHandler GetHandler(HttpContext context, string requestType, string virtualPath, string path)
    {
        var view = base.GetHandler(context, requestType, virtualPath, path) as Page;
        if (view == null) return view;

        DependencyInjection.Container.BuildUp(view.GetType(), view);
        return view;
    }
}

<httpHandlers>
  <add path="*.aspx" verb="*" type="BlogsPrajeesh.WebForms.DI.UnityPageHandlerFactory" />
httpHandlers>
I have created an extension method on the container to register the dependencies while initializing the container
public static class DependencyRegistrations
{
    public static void SetupRegistrations(this UnityContainer container)
    {
        container
            .RegisterType<IHomeView, HomeViewNullObject>()
            .RegisterType<IHomeService, HomeService>()
            .RegisterType<HomePresenter>();
    }
}

Later when the container is initialized you can call the SetupRegistrations methods on the container. container.SetupRegistrations();

A sample view – Presenter implementation can be done like.
public partial class Home : Page, IHomeView
{
    private HomePresenter _presenter;
    public new event EventHandler OnLoad;

    [Dependency]
    public HomePresenter Presenter
    {
        set { _presenter = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _presenter.InitializeViewEvents();
        if (OnLoad != null) OnLoad(this, EventArgs.Empty);
        lblHello.Text = _presenter.GetMessage();
    }
}

public class HomePresenter : AppPresenter<IHomeView>
{
    private readonly IHomeService _homeService;

    public HomePresenter([Dependency] IHomeService homeService)
    {
        _homeService = homeService;
    }

    public string GetMessage()
    {
        return _homeService.GetMessage();
    }

    public override void InitializeViewEvents()
    {
        View.OnLoad += new EventHandler(View_OnLoad);
    }
}

Using this kind of an implementation allows you to completely unit test your ASP.NET web application.
[TestMethod]
public void GetMessageShouldRetrieveTheMessageFromTheRegisteredService()
{
    var presenter = DependencyInjection.Container.Resolve<HomePresenter>();
    Assert.IsFalse(string.IsNullOrEmpty(presenter.GetMessage()));
}