Monday, July 21, 2014

The hierarchy of Controller class in ASP.NET MVC architecture

It’s no need to discuss, how popular MVC architecture is in Microsoft’s web development platform.  We all know MVC stands for Model, view and controller where controller is like glue between Model and view. It’s hold business logic, formulates data and decisions which view to call and which data to be attached to it.


Fine, we know the functionality of it and we became happy to derive our controller class from “Controller” class and get our work done.  We never thought why the controller class is and how it derived? Me too was less bother at first of my MVC days but started to explore more about controller and found the big Hierarchy of controller class. In this article we will discuss hierarchy of controller class and we will see how the class had derived from various base classes and implemented various interfaces.  
At first we will discuss the hierarchy of controller class and then we will see how we define our own controller class from “Control” class in MVC framework. So, let’s start our discussion.

IController is in top level
We can say, this is the top basest interface of controller class. The interface is very simple and clean , contains only one signature , Here is the IController interface.

namespace System.Web.Mvc
{
    // Summary:
    //     Defines the methods that are required for a controller.
    public interface IController
    {
        // Summary:
        //     Executes the specified request context.
        //
        // Parameters:
        //   requestContext:
        //     The request context.
        void Execute(RequestContext requestContext);
    }
}

It’s containing single signatures which need to implement in its concrete implementation.  The controller is located within System.Web.Mvc namespace which is primary DLL of MVC framework. The method takes request context as parameter.

ControllerBase class which implements IController

This is the next level of hierarchy where ControllerBase class implements IController interface.  The ControllerBase contains six property , one parameter less constructor and three methods. The tow most popular and well known properties ViewData and ViewBag is defines within with in this class by which we can send data from controller to view. We can check that ViewBag is dynamic in nature which has introduce with MVC 3 and Viewdata is Dictionary in nature, we know that we need to store data in key value pair within ViewData.
Actually ViewBag is nothing but a abstraction over ViewData and internally they use same mechanism to store data. ViewBag gives flavor of dynamic characteristic. The rest of the functions and properties are described in comment.  You can get the same view of you explore each class in Visual Studio. Point to remember that, It’s a abstract class and we cannot create instance of this.

    // Summary:
    //     Represents the base class for all MVC controllers.
    public abstract class ControllerBase : IController
    {
        // Summary:
        //     Initializes a new instance of the System.Web.Mvc.ControllerBase class.
        protected ControllerBase();

        // Summary:
        //     Gets or sets the controller context.
        //
        // Returns:
        //     The controller context.
        public ControllerContext ControllerContext { get; set; }
        //
        // Summary:
        //     Gets or sets the dictionary for temporary data.
        //
        // Returns:
        //     The dictionary for temporary data.
        public TempDataDictionary TempData { get; set; }
        //
        // Summary:
        //     Gets or sets a value that indicates whether request validation is enabled
        //     for this request.
        //
        // Returns:
        //     true if request validation is enabled for this request; otherwise, false.
        //     The default is true.
        public bool ValidateRequest { get; set; }
        //
        // Summary:
        //     Gets or sets the value provider for the controller.
        //
        // Returns:
        //     The value provider for the controller.
        public IValueProvider ValueProvider { get; set; }
        //
        // Summary:
        //     Gets the dynamic view data dictionary.
        //
        // Returns:
        //     The dynamic view data dictionary.
        [Dynamic]
        public dynamic ViewBag { get; }
        //
        // Summary:
        //     Gets or sets the dictionary for view data.
        //
        // Returns:
        //     The dictionary for the view data.
        public ViewDataDictionary ViewData { get; set; }

        // Summary:
        //     Executes the specified request context.
        //
        // Parameters:
        //   requestContext:
        //     The request context.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The requestContext parameter is null.
        protected virtual void Execute(RequestContext requestContext);
        //
        // Summary:
        //     Executes the request.
        protected abstract void ExecuteCore();
        //
        // Summary:
        //     Initializes the specified request context.
        //
        // Parameters:
        //   requestContext:
        //     The request context.
        protected virtual void Initialize(RequestContext requestContext);
    }


Controller implements IController and ControllerBase and many more

Yes, we will see that Controller class implement IController and Derived from ControllerBase and many more. Here is the implementation information. The Controller class is too abstract class so we cannot create instance of it . Actually the Controller class contains lot of methods and properties, in this article we are not interested to talk about them; just we will understand the hierarchy of Controller class in ASP.NET MVC.

public abstract class Controller: ControllerBase, IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer

So, we are seeing that the Controller class is implementing many other interfaces which contain various useful functions to work out controller properly. For example the IDisoisposable interface contains method related to dispose the controller object after creation and various filter related interfaces are implemented to implement filter in controller level.

At last, define our own controller class
This is the last phase of hierarchy. Here we can define our own controller which will be derived from the Controller class. The beauty of the hierarchy is, we are getting the readymade product and tool to start action immediately.  As we are deriving our own Controller class from Controller class in Library we are capable to use all the functions and property which already implemented in Controller class and BaseController class.
Here is the way to derive our own controller class from Controller class.

MyController : Controller
{
}

Now, the question may come in mind, Why not defined our own controller class from BaseController or Why not implement all those interfaces in our own controller class manually ? Technically speaking, it’s possible to define control class in same approach, let’s have a look. In this example we have derived our controller class from ControllerBase and try to run the application. Before execute the controller the ExecuteCore() will get execute and as we did not implement it’s implementation, it will throw exception but always we can do it because we know MVC is open source application. 


After ExecuteCoe() has done , it will execute Hello() action.  So the advantage is , Microsoft has already defined those stuffs for us and just we need to use it.

Point to remember
If you are new in MVC framework then you may think that, why our Controller class ends with “Controller” suffix? The suffix is mandatory otherwise it will not active. I wish to discuss the fact in another article.

Various mock setups using Moq Framework

In this article we will understand various mocking setup using Moq framework.  Basically those setup will help in time of unit testing in application.
If you are bit experience in unit testing then probably you are aware from those concepts, we know that mocking is one operation where we mimic the original operation with our custom or fake operation.  In time of application development, we now and then see that one component is dependent on another component and we cannot wait till the completion of dependent object.
In this situation, concept of mocking comes into picture. The mock object will mimic the original object, so that we can carry one the development process.
There are many mocking frameworks in market which we can use in time of mock object creation. Moq is one of them. It is free and simple to use. In this article we will use Moq as mocking framework. In time of mock setup there might be different situation which need to implement in time unit test configuration. In this example we will understand few important setup of Moq framework.    


At first, give the reference of Moq framework to your application. Once you give the reference, it will show in reference folder of solution, just like below.
So, let’s start with the first configuration.


Returns statement to return value
We can setup the expected return value to a function. In this example we will setup Hello() function using mock object and then we will setup , after execution of Hello() function it will return “true” always. Here, true is primitive type value, in need we can return our custom complex type too. Please notice that we have declared Hello() function as virtual, because Moq demands that . The function should defined as virtual when we are going to mock a concrete implementation. Have a look on below code.

namespace TestMVC
{
    public class TestClass
    {
        public virtual Boolean Hello()
        {
            throw new Exception();
        }
    }

    [TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<TestClass>();
            mock.Setup(x => x.Hello()).Returns(true);
            Assert.AreEqual(mock.Object.Hello(), true);
        }
    }
}

Perform certain task after execution of certain function
This is another very important setup, sometime it’s needed to perform certain operation after completion of some operation or after execution of some function. For example, we want to count the number of times of a function execution and depending on times we will make decisions.  In this situation we can setup callback() in time of mock. Here is sample example.

[TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            string status = "";
            var mock = new Mock<Service>();
            mock.Setup(x => x.CallService()).Returns(true).Callback(() => {
                //Do some other stuff
                status = "FunctionCalled";
            });

            var consumer = new ServiceConsumer(mock.Object);
            Assert.AreEqual(consumer.Execute(), true);
            if (status == "FunctionCalled")
            {
                //perform other task when finish the first
            }
        }
    }

Once it complete the execution of  CallService() function, immediately it will execute callback and perform some other operation, In this example just we are setting some variable value and it might check farther to take decisions in other steps.

Return multiple values sequentially from mocked function
This is another important setup where the mocked function (I mean the function setup associated with mock object) will return different value per each call. Here is simple implementation.

using System;
using ConsoleApp;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using ConsoleApp;
using System.Collections.Generic;

namespace TestMVC
{

    public class TestClass
    {
        public virtual Boolean ReturnSequence()
        {
            throw new Exception();
        }
    }

    [TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<TestClass>();
           
            //First Return True then false
            mock.SetupSequence(x => x.ReturnSequence())
                .Returns(true)
                .Returns(false);
            Assert.AreEqual(mock.Object.ReturnSequence(), true);
            Assert.AreEqual(mock.Object.ReturnSequence(), false);

        }
    }
}

In this example we have used multiple Returns() statements and at the first time it will return true and in next time it will return false. Here is output and we are seeing that the test is getting pass , as we expected in Assert.


Throws exception in second time
There might be certain situation where we want such a configuration when at the first time, the mocked function will return a value but in call of second time it will throw exception.  In this example the function will return true at first time and in second call it will throw exception.

namespace TestMVC
{

    public class TestClass
    {
        public virtual Boolean Function()
        {
            throw new Exception();
        }
    }

    [TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<TestClass>();
           
            //First Return True then Throws exception
            mock.SetupSequence(x => x.Function())
                .Returns(true)
                .Throws(new Exception());

            Assert.AreEqual(mock.Object.Function(), true);
            Assert.AreEqual(mock.Object.Function(), true);

        }
    }
}

We are seeing that it is throwing exception in second call.


CallBase() to call original implementation

This setup is helpful when we want to call the original function rather than mocked function. In this example , Function() is not mocked, just we are calling the original function with the help of CallBase(). As we throwing exception from Function() intentionally , the test should throw exception.

namespace TestMVC
{
    public class TestClass
    {
        public virtual Boolean Function()
        {
            throw new Exception();
        }
    }

    [TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<TestClass>();
            mock.CallBase = true;

            mock.SetupSequence(x => x.Function()).CallBase();
               

            Assert.AreEqual(mock.Object.Function(), true);

        }
    }
}

And it’s throwing exception from Function().



Mock Generic class
The mocking mechanism of generic class is just like the normal class mocking, have a look on below example.

    public class Hello
    {
    }
    public class TestClass <T> where T : class
    {
        public virtual Boolean Function()
        {
            throw new Exception();
        }
    }
    [TestClass]
    public class MVCUnitTest
    {
        [TestMethod]
        public void MockAlways()
        {
            var mock = new Mock<TestClass<Hello>>();
            mock.SetupSequence(x => x.Function()).Returns(true);
            Assert.AreEqual(mock.Object.Function(), true);
        }
    }



Border line:
In this article we have learned few important mock setups using Moq framework. In my next article I am planning to explore mock in depth.