Monday, April 29, 2013

Getting Started with Castle Windsor Interceptors in ASP.NET MVC

Don’t you hate when writing code you have to think about generic exception handling, logging of method calls, caching of methods, authorization, etc...  Well suppose there was a tool/technique you could use that you could write the above items once and make sure they get implemented on existing code along with any new code added in the future.  Castle Windsor and its Interceptors support just that.

In the example below we will create a interceptor and do the necessary wiring up to make it work.  We will be using an ASP.NET MVC4 application based on the initial Windsor setup done in my last blog post.
http://blog.devdave.com/2013/04/castle-windsor-in-aspnet-mvc-4.html

Create a manager class to do some work.  We will call methods of this class in our controller class. later in this blog post  In the Infrastructure folder create a new folder called Managers.  Inside the Managers folder create a new folder called Interfaces.  Create an interface called IExampleManager in the interface folder.

public interface IExampleManager
{
    void ExampleMethod();
}

Creating the concrete implementation of the manager, create a class called ExampleManager in the Managers folder.

public class ExampleManager : IExampleManager
{
    public void ExampleMethod()
    {
        Debug.WriteLine("Doing Work...");
    }
}

Now we need to register our new manager in Windsor.  In the Infrastructure\Installers folder add a new class called ManagerInstaller.

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient()));
    }
}

Now that Windsor knows how to handle the manager we can modify our controllers constructor like so

private IExampleManager exampleManager;

public HomeController(IExampleManager exampleManager)
{
    this.exampleManager = exampleManager;
}

Since Windsor knows how to turn an IExampleManager into ExampleManager it will handle this for us when Windsor instantiates the controller.

Modify the controller action method to call a method on the example manager.

public ActionResult Index()
{
    this.exampleManager.ExampleMethod();
    return new ContentResult(){Content = "test"};
}

Running the site and calling the Index action, note the output window.
image

Now lets say we wanted to intercept the call to any public method of the ExampleManager class.  We can do this by adding in an interceptor. To do this we will need to create the interceptor.  Create a new folder inside the infrastructure folder called Interceptors.  Create a new class in this folder called ExampleInterceptor.

public class ExampleInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Debug.WriteLine(string.Format("Before method: {0}", invocation.Method.Name));
        invocation.Proceed();
        Debug.WriteLine(string.Format("After method: {0}", invocation.Method.Name));
    }
}

Now we need to tell Windsor about the interceptor.  In the Infrastructure\Installers folder lets add a new class called InterceptorInstaller.

public class InterceptorInstaller : IWindsorInstaller
{
    public void Install(Castle.Windsor.IWindsorContainer container, Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
    {
        container.Register(Component.For<ExampleInterceptor>()
                               .LifestyleTransient());
    }
}

Now lets go back to our manager installer and add in the interceptor to all managers.

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient().Interceptors<ExampleInterceptor>()));
    }
}

Running the site and calling the Index action, note the output window now.
image

As you can see the interceptor intercepted the call to the method on our ExampleManager.   Adding new public methods to our manager call will automatically get intercepted also.  This means that adding code in the future required no thought about the interceptor.  This opens up all kinds of ideas for interceptors like:

  • Exception Handling
  • Logging
  • Performance Counters
  • Authorization
  • Caching
  • Timing
  • etc...

Note there is a different way to implement interceptors.  You can use an attribute on a class that is already under the control of Windsor.  More information about this can be found here: http://docs.castleproject.org/Windsor.Interceptors.ashx.

Monday, April 15, 2013

Castle Windsor in Asp.Net MVC 4

The project I am using at work currently uses Castle Windsor as its IOC container.  My colleague did the initial setup so I decided to do this blog post based on a new MVC project to explain the setup and get more familiar with the steps needed to make MVC and Castle Windsor work together.

First thing, create a new MVC 4 website (which template you use is up to you).  After that I updated all the existing NuGet packages and added this one Castle Windsor.

Create a Infrastructure folder at the root of the MVC application.  Inside the Infrastructure folder create a WindsorControllerFactory class.  This will inherit MVC’s DefaultControllerFactory and override the GetControllerInstance and ReleaseController methods. We will use this class in a later step to tell MVC to use this controller factory instead of its default one.

public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public WindsorControllerFactory(IKernel kernel)
        {
            this.kernel = kernel;
        }

        public override void ReleaseController(IController controller)
        {
            kernel.ReleaseComponent(controller);
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException(404, string.Format("The controller for path '{0}' could not be found.", requestContext.HttpContext.Request.Path));
            }
            return (IController)kernel.Resolve(controllerType);
        }
    }

Next create a folder in the Infrastructure called Installers.  This is where all of the installers used by Windsor will go.  Our first installer will be a class named ControllersInstaller.  This inherits the IWindowsInstaller interface which requires the implementation of the Install method.  The code below basically says all classes in the assembly that are based on the IController interface should be created using LifestyleTransient which basically means instantiate an instance every time.

public class ControllersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(Classes.FromThisAssembly()
                                .BasedOn<IController>()
                                .LifestyleTransient());
        }
    }

The last step needed to get things running is the modifications needed in the global.asax.cs file.  There are several things going on the code below.  Note the static field used to store the container, the value of the field is set in the static method BootstrapContainer.  This method does two things.

  1. Set the value of the container by instantiating an instance of the WindsorContainer and telling it to Install all the installers in the assembly (basically any class that inherits form the IWindsorInstaller interface).
  2. Tell MVC to use our WindsorControllerFactory instead of the default MVC controller factory implementation.

The BootstrapContainer method is called on application start after the other MVC registration code.  The last change is to dispose the container on application end.

public class MvcApplication : System.Web.HttpApplication
{
    private static IWindsorContainer container;

    private static void BootstrapContainer()
    {
        container = new WindsorContainer().Install(FromAssembly.This());

        var controllerFactory = new WindsorControllerFactory(container.Kernel);
        ControllerBuilder.Current.SetControllerFactory(controllerFactory);
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        MvcApplication.BootstrapContainer();
    }

    protected void Application_End()
    {
        container.Dispose();
    }
}

At this point adding a controller and view should work correctly.  All these changes to make MVC work the way it would have before doing all this.  So what is the big deal, what if in my Home controller I wanted to do something like this:

private IContactManager contactManager;

public HomeController(IContactManager contactManager)
{
    this.contactManager = contactManager;
}

Using the code we have now this would not work since the container at this point would not know how to resolve IContactManager into its concrete implementation.  To get this to work we would need to add a new installer to our installer folder.  For example:

public class ManagerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Classes.FromThisAssembly()
            .Where(type => type.Name.EndsWith("Manager"))
            .WithServiceDefaultInterfaces()
            .Configure(c => c.LifestyleTransient()));
    }
}

This installer’s install method would get called by the instantiation of the container in the global.asax.cs application start event.  This installer says to register all the classes in the assembly that end in Manager and follow the default interface pattern (info) and instantiate them on a per use basis.

So now lets say the CustomerManager had a dependency on the CustomerRepository.  This would require a new installer.  I prefer to use a separate installer for each convention I am going to use.  This way if a specific convention needs to have a different lifestyle (per call, singleton, etc…) it easier to setup.  No need to show this installer since it would be just like the one above with a separate lambda in the where clause.

Wednesday, January 23, 2013

Mocking an internal interface with Moq

The other day I was trying to write some unit tests on a public class with an internal constructor.  In order for the test project to get access to the internal constructor (primarily used for testing) I had to add the assembly: InternalsVisibleTo to the AssemblyInfo.cs file and specify the class library I was testing would expose its internals to the test class library, for example:

[assembly: InternalsVisibleTo("SomeApi.Test")]

This got me close, next issue was the parameter of the internal constructor was an internal interface referencing a dependency of the class under test.  No big deal.  I figured I would use Moq to mock out the dependency and I got the following error when trying to run the test:

Test method SomeNamespace.SomeClass.SomeTestMethod threw exception:
Castle.DynamicProxy.Generators.GeneratorException: Type SomeNamespace.SomeInterface is not public. Can not create proxy for types that are not accessible.

Hmm, it seems like Moq does not have access to the internals.  Adding the following to the class libraries AssemblyInfo.cs file solved the problem

[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]

Next time I ran the test Moq was able to access the internal interface and my test passed.

Sunday, November 4, 2012

Messing around with Generics

The other day I was looking through some code and thought of a way to refactor the code using generics.  I decided to create an example with the code in its current form and then see if I could make it work more generically. All the source can be found here (https://github.com/devdaves/genericconditions) on GitHub.

Here is the code example prior to using generics:

public ExampleResponse ValidateExampleWithoutGenerics(ExampleRequest request)
{
    ExampleResponse response = new ExampleResponse();

    Condition1(request, ref response);
    Condition2(request, ref response);
    Condition3(request, ref response);
    //could be many conditions...
    DoWork(request, ref response);

    return response;
}

The method accepts a request object and returns a response object.  There are several conditions that need to be validated prior to doing the work.  All condition and do work methods check the status property in the response prior to doing any work.  This way if Condition1 fails the rest of the methods will still be executed but the work will not be done since the status of the response is checked in each method.

What I am trying to solve is not running the other conditions or do work if the response status is in a faulted state.  Now I know I could just add some conditions into this method but what's the fun in that.  So time to refactor.

First the response needs to inherit from an IResponse that enforces that all responses will have a status property.  This will come in handy when we create the generic method a little later in the post.

public interface IResponse
{
    Status Status { get; set; }
}

Next rewrite the Validate method with generics.  Note the list of actions.

public ExampleResponse ValidateExampleWithGenerics(ExampleRequest request)
{
    ExampleResponse response = new ExampleResponse();

    List<Action<ExampleResponse>> todo = new List<Action<ExampleResponse>>()
    {
        {(r) => {Condition4(request, ref r);} },
        {(r) => {Condition5(request, ref r);} },
        {(r) => {Condition6(request, ref r);} },
        {(r) => {DoWork2(request, ref r);} },
    };

    //DoToDo<ExampleResponse>(todo, ref response);
    todo.RunWithShortCircuit(ref response);

    return response;
}

Initially the list of actions was sent to a method in the same class (DoToDo now commented out) and later turned into an extension method.  This is the extension method.

public static void RunWithShortCircuit<T>(this List<Action<T>> actions, ref T response)
    where T : IResponse
{
    foreach (var action in actions)
    {
        if (response.Status.StatusCode == 0)
        {
            action.Invoke(response);
        }
        else
        {
            // short circuits the rest of the actions from running
            break;
        }
    }
}

This extension method will work off any list of actions that inherit from the IResponse interface created earlier.  It will loop through the actions and execute each one and check the status.  If the status is in a faulted state it will stop processing the list of actions.  Since this is now generic any method we create in the project that uses the request/response pattern should be able to use this extension method to execute the conditions and dowork.

The cool thing here is not only are we short circuiting the process but each condition and dowork method no longer needs to check the status since its done in one place.  If the logic that checks the status is done in only one place the maintenance of the code is much easier.

I have to admit that I haven't spent a lot of time playing with generics like this but I can see from a maintenance point of view that it can save some substantial time in a decent sized project.  Plus I really like the way it reads although it does take some time to get used to.

Wednesday, May 30, 2012

Moq: Mocking HttpContext in your MVC3 unit tests

Lets take the following action method on our Home controller.

public ActionResult TestAction()
{
    var idFromCookie = Request.Cookies["ID"].Value;
    var model = new TestActionViewModel() { Id = idFromCookie };
    return View("TestAction", model);
}

Unit testing this action method can be difficult due to its dependency on the Request object.  Luckily the Request object here maps to the HttpContext of the controller.  The HttpContext on the controller is an instance of HttpContextBase and can be mocked in unit tests.

Below is a class I currently use to mock out the HttpContext.  Note that I have many other properties mocked that are part of the HttpContext.  I plan on doing other blog posts using those different properties in the future.

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Moq;

public class MockContext
{
    public Mock<RequestContext> RoutingRequestContext { get; private set; }
    public Mock<HttpContextBase> Http { get; private set; }
    public Mock<HttpServerUtilityBase> Server { get; private set; }
    public Mock<HttpResponseBase> Response { get; private set; }
    public Mock<HttpRequestBase> Request { get; private set; }
    public Mock<HttpSessionStateBase> Session { get; private set; }
    public Mock<ActionExecutingContext> ActionExecuting { get; private set; }
    public HttpCookieCollection Cookies { get; private set; }

    public MockContext()
    {
        this.RoutingRequestContext = new Mock<RequestContext>(MockBehavior.Loose);
        this.ActionExecuting = new Mock<ActionExecutingContext>(MockBehavior.Loose);
        this.Http = new Mock<HttpContextBase>(MockBehavior.Loose);
        this.Server = new Mock<HttpServerUtilityBase>(MockBehavior.Loose);
        this.Response = new Mock<HttpResponseBase>(MockBehavior.Loose);
        this.Request = new Mock<HttpRequestBase>(MockBehavior.Loose);
        this.Session = new Mock<HttpSessionStateBase>(MockBehavior.Loose);
        this.Cookies = new HttpCookieCollection();

        this.RoutingRequestContext.SetupGet(c => c.HttpContext).Returns(this.Http.Object);
        this.ActionExecuting.SetupGet(c => c.HttpContext).Returns(this.Http.Object);
        this.Http.SetupGet(c => c.Request).Returns(this.Request.Object);
        this.Http.SetupGet(c => c.Response).Returns(this.Response.Object);
        this.Http.SetupGet(c => c.Server).Returns(this.Server.Object);
        this.Http.SetupGet(c => c.Session).Returns(this.Session.Object);
        this.Request.Setup(c => c.Cookies).Returns(Cookies);
    }

}

In the constructor I new up the new mocks and do some wiring up of the dependencies of the objects you will need while working with the HttpContext.  Since the above action uses a cookie, note that there is a Cookies property that is mapped to the mocked request object.  So when Request.Cookies is called in the action method it will actually be looking at the Cookies collection defined in this class.

Here is a test that uses the MockContext object to test the action method above.

[TestMethod]
public void TestActionCookieValueReturnedInModel()
{
   //arrange
    var expectedValue = "TEST";
    MockContext mockContext = new MockContext();
    mockContext.Cookies.Add(new HttpCookie("ID", expectedValue));
    var homeController = new HomeController()
        {
            ControllerContext = new ControllerContext()
                {
                    HttpContext = mockContext.Http.Object
                }
        };

    //act
    var result = homeController.TestAction() as ViewResult;
    var model = result.ViewData.Model as TestActionViewModel;

    //assert
    Assert.AreEqual(expectedValue, model.Id);
}

Note that I new up a new instance of the MockContext and add the cookie to the cookie collection so the action method above will have access to it.  When creating an instance of the controller I used an object initializer to set the controller context to a new controller context using our MockContext http object.

Using this technique it would be very easy to mock out what would happen if the cookie was not in the cookies collection.

Monday, May 28, 2012

Moq: Adding Setups/Expectations work after providing object to Dependent

First some background code.

Lets assume we have a contact repository interface like so:

public interface IContactRepository
{
    Contact Add(Contact contact);
    bool Exists(Contact contact);
}

Lets assume we also have a contact service that implements the contact repository like so:

public class ContactService
{
    IContactRepository repository;

    public ContactService() : this(new ContactRepository())
    {
    }

    public ContactService(IContactRepository repository)
    {
        this.repository = repository;
    }

    public Contact Add(Contact contact)
    {
        if (!repository.Exists(contact))
        {
            return repository.Add(contact);    
        }
        return null;
    }
}

Now I used to write the tests like this:

[TestMethod]
public void AddContactContactDoesNotExistReturnsNewContact()
{
    var mockRepository = new Mock<IContactRepository>();
    mockRepository.Setup(x => x.Exists(It.IsAny<Contact>())).Returns(false);
    mockRepository.Setup(x => x.Add(It.IsAny<Contact>())).Returns(new Contact() { Id = 1 });
    var contactService = new ContactService(mockRepository.Object);

    var result = contactService.Add(new Contact() { Name = "Test" }) as Contact;

    Assert.IsNotNull(result, "Should have returned a contact object");
    Assert.AreEqual(1, result.Id);
}

Notice how I setup the mock repository expectations prior to assigning the mock repository to the constructor of the contact service. For some reason I always though you had to define your expectations prior to assigning the mock object to its dependents.  As it turns out this is not required.  Look at the following code and notice how the setup of the expectations comes after the mock repository has been assigned to the contact service.

[TestMethod]
public void AddContactContactDoesNotExistReturnsNewContact()
{
    var mockRepository = new Mock<IContactRepository>();
    var contactService = new ContactService(mockRepository.Object);
    mockRepository.Setup(x => x.Exists(It.IsAny<Contact>())).Returns(false);
    mockRepository.Setup(x => x.Add(It.IsAny<Contact>())).Returns(new Contact() { Id = 1 });
    
    var result = contactService.Add(new Contact() { Name = "Test" }) as Contact;

    Assert.IsNotNull(result, "Should have returned a contact object");
    Assert.AreEqual(1, result.Id);
}

Knowing that there is no specific order in regards to assigning the expectations to your mock object and assigning the mock object to its dependent object can go a long way in making your code more readable.

Thursday, August 18, 2011

Using the Flags attribute with an Enumeration

I was recently tasked with adding an attribute to an object.  This object persists in the database and I assumed that adding an attribute meant I would add a new property to the class, add a new column to the database and tie it all together.

Well, that wasn't the case.  The implementation that was already in place used an enumeration for the collection of possible attributes.  That enumeration allowed more then one value to be stored.  The enumeration was then converted into an integer as it was stored in the database.  All I had to do to add the new attribute was add an additional value to the enumeration.

This served as yet another epiphany on how something works and then the realization that I have seen and used this before in many places already. What I am talking about is using an enumeration of values as a bitmask.

Now the trick if you want to call it that is each numeric value of the enumeration was 2 multiplied by the preceding value (except for zero and one) and the enumeration has a Flags attribute.  Here is some example code:

[Flags]
public enum Colors : int
{
    None = 0,
    Red = 1,
    Blue = 2,
    Yellow = 4,
    Green = 8,
    White = 16
}

Since the values of the enumeration above are actually numeric they are represented by the following table:

Color Number 32 Bit Definition
None 0 00000000000000000000000000000000
Red 1

00000000000000000000000000000001

Blue 2

00000000000000000000000000000010

Yellow 4

00000000000000000000000000000100

Green 8

00000000000000000000000000001000

White 16

00000000000000000000000000010000

Since the enumeration is of type integer it will be stored as a 32 bit number. Since the integers are 32 bit each bit represents an enumeration value so the enumeration can only have 32 items.  If I wanted more then 32 items in the enumeration I could change the type of the enumeration to long.  This would store the value as a 64 bit number therefore giving you a capacity of 64 items in the enumeration.

Here is some example code showing how to add and remove colors:

Colors myColors = Colors.None;

//lets add some colors
myColors = myColors | Colors.Red;
myColors = myColors | Colors.Green;
myColors = myColors | Colors.Blue;
myColors = myColors | Colors.White;

//lets remove a color
myColors = myColors ^ Colors.White;

The table below represents the value of the myColors variable at each addition and removal of a color.

Colors Number 32 Bit Definition
None 0 00000000000000000000000000000000
Red (1) 1

00000000000000000000000000000001

Red (1), Green (8)   1+8=9 9

00000000000000000000000000001001

Red (1), Green (8), Blue (2)  1+8+2=11 11 00000000000000000000000000001011
Red (1), Green (8), Blue (2), White (16)  1+8+2+16=27 27 00000000000000000000000000011011
Red (1), Green (8), Blue (2) 1+8+2=11 11 00000000000000000000000000001011

Notice the 32 bit representation of the value of the colors above.  Each bit that is ON is 1 and the ones that are OFF are 0.

So how would you figure out what enumeration item values where ON with out the computer?  All you need to know is the enumeration value and the values of the individual enumeration items.  Lets take the value 27 for example. Going from highest enumeration item value that can go into the value we can figure out what colors are ON in the enumeration value.

27 – 16 (White) = 11
11 – 8 (Green) = 3
3 – 2 (Blue) = 1
1 – 1 (Red) = 0
Answer = White, Green, Blue and Red.

The value of myColor variable would get saved to the database as an integer value. I wondered how or if I could use SQL to figure out which items where ON or OFF.  As long as I know the value of the enumeration items I am looking for I can use that information to query the data.  Look at the following SQL script to see how to do it.

declare @colors as table (
    id int,
    name nvarchar(100) not null,
    colors int not null
)

insert @colors (id, name, colors)
values
(1, 'Red', 1),
(2, 'Red, Green', 9),
(3, 'Red, Green, Blue', 11),
(4, 'Red, Green, Blue, White', 27),
(5, 'Red, Green, Blue', 11)

--lets get all the rows that have white in them
--we know white is 16
select *
from @colors
where colors & 16 = 16

--lets get all the rows that have blue and green but not white
--we know blue = 2m green = 8 and white = 16
select *
from @colors
where colors & 2 = 2 and colors & 8 = 8 and colors & 16 = 0

 

My Thoughts

While the initial issue with using this technique is that you are limited to the number of items in the enumeration depending on what data type you use.  I feel if you know you will use less then the maximum number of items in the enumeration this implementation would work.  Not having to add a new column to a database table every time you add an attribute sounds like a real win.