MS SQL Profiler – Limiting trace information by database name

Okay, this is going to be a really short post about MS SQL profiler (yay, my first post about MS SQL :D ). In case you are not aware of the sql profiler (which I am sure most of the developers are aware of), it’s a tool used to view the queries issued by various applications to a database server. “SQL Server Profiler” is normally present in the following location All Programs\Microsoft SQL Server 2008\Performance Tools\SQL Server Profiler. Once you launch this executable, you can use the File menu to start a new trace session (File -> New Trace). Then you will have to enter the database server name and the login credentials. Once you click on “Connect”, you will get the “Trace Properties” dialog. When you hit on “Run”, all the queries issued by various applications to this database server can be seen. Now let me get to the most interesting part.

At times, in a database server that has a number of databases accessed by a number of applications, it may be really difficult keep track all the traced events. Of course, you can use Ctrl + F, but this is much more interesting as you pretty much get a limited amount of data to look at. The profiler has an option to limit the trace to a specific database. This post is going to discuss with images as to how this filter can be applied so as to limit the amount of trace information.

First, when you choose File -> New Trace, you get the trace window as shown below. Notice the 2nd tab “Events Selection”. Select that tab.

Initial trace properties window

In this tab, look for the “Show all columns” checkbox and check it. Then click on the “Column Filters” button.

Initial trace properties window

Now in the “Edit Filter” dialog displayed look for the “DatabaseName” and select it. Then in the right pane, in the tree displayed, expand “Like“. You now get a text box where you can enter the database name. Now click the OK button and now you are all set. You can also enter multiple database names here. You get a new text box whenever you enter a database name.

Initial trace properties window

Now, you get back to the “Trace Properties” window. When you hit on “Run”, you only see the traces for the database you selected!

If you knew this already, this could be a refresher of sorts! But I came to know of this only today :( , but still happy to know this!!!

Hope this post was helpful!

Share

Dependency Injection With Ninject And Extending It a Bit Further

In this post I am going to discuss a very interesting concept called “dependency injection (DI)” and also about extending the class that injects the dependencies further to achieve some more functionalities that I needed for a project of mine. I am going to use a mvc 3 application to explain about DI. DI is a type of interface programming that allows you to create loosely coupled systems. This increases testability and also reduces the amount of changes required to a project for adding / removing features. At this point it may be confusing, but once I discuss more about this with some examples, it will be much more clearer.

A system implementing DI could be pictured of as having 3 components:

  • Dependent Consumer
  • Dependency
  • Dependency Injector

Dependency consumer‘s are parts of the system that expects a concrete instance to implement something. Consider the following code listing (listing 1):

public class Consumer
{
    private DbAccessor _accessor;

    public Consumer(DbAccessor accessor)
    {
        _accessor = accessor;
    }

    public void DoSomething()
    {
       // -- snip --
    }
}

public class Tester
{
   public static void Main(string[] args)
   {
        DbAccessor accessor = new DbAccessor();
        Consumer consumer = new Consumer(accessor);
        consumer.DoSomething();
   }
}

If you notice the Main method, in order to create an instance of a Consumer, the method has to first create a DbAccessor instance. This is a Dependency. Thus, the method has to know about both the DbAccessor and Consumer. This is known as tight coupling. Because, if you change the name of this class to say DbType1Accessor and assuming this class is used a number of files, you have to change it in all of these files. A way better example is, say you want to replace DbAccessor with XmlAccessor you have to replace the same in all those numerous files. So with all of these facts, I am sure you understand why strong coupling is bad! Later in the post I will show how this strong coupling can be removed.

Now, let’s get to the most important component, the dependency injector. A Dependency Injector is a component that would help you to free the system from this coupling. And this post concentrates on adding a DI component for your project. I have always used “NInject” for implementing DI in my projects.

It’s extremely easy to setup and get started with NInject. To get started download, the NInject dll from here. For this post I was using NInject v2.0.0 (yeto to update to v2.2 :( ). Once you download the dll, add it to the project using “Add Reference”. Then create a class called NinjectControllerFactory and add the following code snippet to this file. This class is going to act as the principal class for implementing DI. If you notice this class inherits the DefaultControllerFactory, which is the default for the mvc framework.

A controller factory is a component of the mvc framework that helps in creating an instance of a controller as required by the mvc framework. In this case we are attempting to provide loose coupling to all the controllers. The controller factory, which is responsible for creating the controllers is overridden in this case so that when a controller is created now, the new controller factory would take the responsibility of creating an instance of the controoler and enabling the Ninject module to “inject” the dependency required by the controller.

public class NinjectControllerFactory : DefaultControllerFactory
{
	private IKernel kernel = new StandardKernel(new AplicationIocServices());

	protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
	{
	    if (controllerType == null)
        {
		    return null;
        }
	    return (IController)kernel.Get(controllerType);
	}

	private class AplicationIocServices : NinjectModule
	{
	    public override void Load()
	    {
		    Bind<IProductsRepository>().To<FakeProductsRepository>();
		    Bind<ICategoryRepository>().To<FakeCategoryRepository>();
	    }
	}
}

In the above code listing, line 3 creates an instance of StandardKernel which is required for the ninject module to work. The StandardKernel implements the IKernel interface which is used in the overriden GetControllerInstance method to return an instance of the required controller by passing the dependency needed by the controller. Note that, as this class is set to replace the DefaultControllerFactory, it’s very important to override the GetControllerInstance method to return an appropriate controller. If you notice line 3, an instance of the ApplicationIocServices instance is passed to the StandardKernel. This is a private class within the NinjectControllerFactory which is used to specify the bindings between an interface and a concrete instance. This class inherits from the NinjectModule class and overrides the Load method of the NinjectModule class.

Every line within the Load binds an interface to a concrete instance so that ninject can create a concrete type corresponding to the interface type passed when creating a controller instance. So when a controller requests a concrete type for IProductsRepository, ninject module returns an instance of FakeProductsRepository which could be used within the controller.

It’s not over if you just create this class. You have to inform the framework to use this instead of the DefaultControllerFactory using the Application_Start event in the Global.asax.cs file. This is done in line 8. ControllerBuilder class of mvc has the
Current property which is nothing but an instance of a ControllerBuilder for the current
application. The application’s controller factory is set to an instance of the NinjectControllerFactory we created earlier using the SetControllerFactory method of the ControllerBuilder instance. After this point, when a request is received for the HomeController (say), an instance of Home Controller will be created by our custom factory, by injecting in the required dependencies.

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

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}

Following is an example of how this is put to use. Let us assume that the HomeController has an action called Products that displays a list of products that this web site offers for purchase. Without DI, I will have to create an instance of FakeProductsRepository and use it in the controller as shown below:

public class HomeController : Controller
{
	public ActionResult Products()
	{
        FakeProductsRepository repository = new FakeProductsRepository();
	    return View(repository.Products);
	}
}

The above snippet has a strong coupling of the FakeProductsRepository with the HomeController. This is not good because it reduces testability and also makes you modify this code whenever something changes with the FakeProductsRepository class. For example, in case you want the controllers to receive a concrete instance of ProductsRepository instead of an instance of FakeProductsRepository, the only change required is the change in line 9. Thus even if a number of controllers uses the IProductsRepository dependency, nothing would change, as the only change required was in the NinjectControllerFactory class.

public class NinjectControllerFactory : DefaultControllerFactory
{
	// -- snip --

	private class AplicationIocServices : NinjectModule
	{
	    public override void Load()
	    {
		    Bind<IProductsRepository>().To<ProductsRepository>();
		    Bind<ICategoryRepository>().To<FakeCategoryRepository>();
	    }
	}
}

Now that we have set up DI, we can modify the code as shown below. Note that now, the fact that the controller expects a concrete type bound to IProductsRepository could be identified by the parameter to the constructor of the HomeController, which is IProductsRepository. From this point onwards, ninject takes care of creating an instance of the Home controller including passing to it an instance of the FakeProductsRepository because IProductsRepository is bound to FakeProductsRepository.

public class HomeController : Controller
{
	private IProductsRepository productsRepository;

    public HomeController(IProductsRepository productsRepo)
    {
          productsRepository = productsRepo;
    }

	public ActionResult Products()
	{
	    return View(productsRepository.Products);
	}
}

Extending the Ninject Module:

Now, let me get to the most important part of this post. What if I need to create a concrete instance somewhere in a class where Ninject does not come in to the picture? Thats what the remainder of the post is going to deal with. For this part, I again take up one of my favorite area of C# – type constraints :) Let’s add a method called GetConcreteInstance to the NinjectControllerFactory class. This method will be used to get a concrete instance based on the interface type passed. This is a generic method which takes in an interface as a type parameter, finds a concrete instance, casts it to the type T and returns it to the caller.

So, with this method, you don’t have pass every required instance to a controller. This method uses the TryGet method of the StandardKernel to see if a concrete instance exists for the type passed. If not available this method throws an exception.

public class NinjectControllerFactory : DefaultControllerFactory
{
	// -- snip

	public T GetConcreteInstance<T>()
	{
	    object instance = kernel.TryGet<T>();
	    if (instance != null)
        {
		    return (T)instance;
        }
	    throw new InvalidOperationException(string.Format("Unable to create an instance of {0}", typeof(T).FullName));
	}

	// -- snip --
}

Let us look in to an example on how this is put in to use in a controller. Before that let us add a helper class to call this method, so that we abstract the part of getting a reference to the controller factory. Its given below:

public static class InstanceFactory
{
	public static T CreateConcreteInstance<T>()
	{
	    NinjectControllerFactory factory =(NinjectControllerFactory)ControllerBuilder.Current.GetControllerFactory();
	    return (T)factory.GetConcreteInstance<T>();
	}
}

Now, I have added the Categories method to the HomeController. Let’s assume apart from this method, no other method requires the ICategoryRepository. So instead of injecting the dependency to the constructor, within the action method, I use the new helper created earlier to get a concrete instance of ICategoryRepository by passing in ICategoryRepository as the type parameter.

public class HomeController : Controller
{
	private IProductsRepository productsRepository;

	// -- snip --

	public ActionResult Categories()
	{
	    ICategoryRepository categoryRepo = InstanceFactory.CreateConcreteInstance<ICategoryRepository>();
	    return View(categoryRepo.GetCategories());
	}

	// -- snip --
}

In the case of the CategoryController, DI is used as its more likely to be used throughout the controller. So I am just letting ninject take the responsibility for the CategoryController.

public class CategoryController : Controller
{
	private ICategoryRepository categoryRepository;

	public CategoryController(ICategoryRepository categoryRepo)
	{
	    categoryRepository = categoryRepo;
	}

	public ActionResult Index()
	{
	    return View(categoryRepository.GetCategories());
	}
}

Now that I have given you the full picture about DI, let me show how the code in listing 1 can be refactored to free it of the strong coupling.

public class Consumer
{
    private DbAccessor _accessor;

    public Consumer(DbAccessor accessor)
    {
        _accessor = InstanceFactory.CreateConcreteInstance<IDbAccessor>();
    }

    public void DoSomething()
    {
       // -- snip --
    }
}

public class Tester
{
   public static void Main(string[] args)
   {
        Consumer consumer = new Consumer();
        consumer.DoSomething();
   }
}

Given below is another high level implementation of how this new helper class/method could be used.

public class BaseClass
{
	private SomeBusinessFunction func;

	public BaseClass()
	{
	    func = new SomeBusinessFunction();
	}

	public void SomeMethod()
	{
	    func.DealWithSomething();
	}
	}

	public class DerivedClass : BaseClass
	{
	public DerivedClass()
	{

	}
}

public class SomeBusinessFunction
{
	private ICategoryRepository categoryRepo;

	public SomeBusinessFunction()
	{
	    categoryRepo = InstanceFactory.CreateConcreteInstance<ICategoryRepository>();
	}

	public List<Category> DealWithSomething()
	{
	    List<Category> categories = categoryRepo.GetCategories().ToList();

	    // -- do something --

	    return categories;
	}
}

Okay, I know that you have seen a lot code. You can download a sample project here. Hope you enjoyed this post. Happy coding!

Share

Yet Another Ruby Language Post :)

This time, I am back with a post that deals with few interesting aspects of ruby. To begin with, I am going to discuss about YAML (Guess you now know the reason why I gave this title to this post :D ). YAML is an acronym for Yet Another Markup Language. YAML is a way by which data could be serialized in a human readable format. In ruby’s context, YAML could be used to save the state of ruby objects. Ruby makes it really easy to store and retrieve YAML objects. This enables you to accomplish things with a very few lines of code. Conside the following for example:

require 'yaml'
a =['a', 'b']
y(a)

In order to use YAML in ruby, you need to import the YAML library. This is done using the require statement. Then I declare a simple ruby array called ‘a’. Now y is a method from the YAML library that prints the array ‘a’ in the YAML format. The output is given below. The first line --- indicates that this is a YAML serialized data. Then the following lines represent every entry in the array.

---
- a
- b

This technique could also be utilized for saving the state of an instance or a list of instances. Consider the following class and an instance of it.

class Appdata
	attr_accessor :id, :title, :description

	def initialize(p_id, p_title, p_description)
		@id = p_id
		@title = p_title
		@description = p_description
	end
end

i = Appdata.new(1, "Title 1", "Description 1")
y(i)

Executing this snippet would give the following output. The first line as before indicates that this is a YAML serialized data. After —, !ruby/object:Appdata indicates that what follows is an instance of the Appdata object. Following this line, every property of this instance is listed.

>ruby variables.rb

--- !ruby/object:Appdata
description: Description 1
id: 1
title: Title 1
>Exit code: 0

This could very well be put in to a number of useful implementations. For example, an application’s configuration/state could be stored/retrieved using this. Consider the class given below:

require 'yaml'

class Dataclass
	attr_writer :data_id, :data_name

	def initialize(id, name)
		@data_id = id
		@data_name = name
	end

	def getdataid
		@data_id
	end

end

a = Dataclass.new(3,"three")

if (!File.exists?("app_state.config"))
	puts "Dumping app state"
	f = File.new("app_state.config", 'w')
	YAML.dump(a, f)
	f.close
end

$config

if (File.exists?("app_state.config"))
	puts "Reading app state"
	File.open("app_state.config") { |data|
		$config = YAML.load(data)
	}
end

puts $config.getdataid

In the above listing, lines 3 – 15 represent the config class I wish to save. Line 17 creates an instance of Dataclass. Lines 19-24 checks if there is a file named “app_state.config” and if not it creates a new file with the same name and then uses the YAML.dump method to dump the instance a in to the file created using the handle f. Then to demonstrate the fact that this serialized data can be loaded back, I am using the YAML.load method. This is demonstrated using lines 28 – 33. Before this, I have defined a variable $config to store the configuration object stored. In order to do this, the file is opened using the File.open method. The data read from the file is made available to the block that will executed after the read operation using the |data| variable. Then I call YAML.load method to load the Dataclass instance in to the $config variable.

From this point onwards, $config can be used in the application as shown in line 35. I have put YAML in to use in my to-do list application. I use YAML to save / load tasks added by the user. Check out this file to see what I mean. A sample file generated by this application is here.

This greatly simplifies the amount of code required to do this. This is evident when you compare the amount of code involved in text manager which save’s / load’s the tasks in to a text file. Code for this is here. A sample file generated by this application is here.

The next thing I would like to discuss is about class & instance variables and class methods. When I was getting myself acquainted with ruby, I was stumped once even though I knew the difference between a class and instance variable, as it didn’t register well enough in my mind. After identifying the mistake it’s going to be etched forever in my memory! To begin with, in ruby, an instance variable is prefixed with ‘@’ and a class variable is prefixed with ‘@@’. A class method is similar to a c# static method and so an instance is not required to call this method. So, a class variable is similar to a static field.

I am sure you are aware about classes and objects. A class is a blueprint of an object, it’s a collection of properties (representing state) and methods (representing behavior). And, an object is an instance of a class. Every instance variable is specific to an instance as the name suggests and a class variable is common across all the instances and so is specific to the class. Let me make it clear with an example.

class Sampleclass
	@@no_instances = 0

	attr_accessor :initialMessage 

	def initialize(initMessage)
		@@no_instances = @@no_instances + 1
		@initialMessage = initMessage
	end

	def print
		puts "Hello from Sampleclass #{self.inspect}"
	end

	def Sampleclass.printInstanceCount
		puts @@no_instances
	end
end

In the above snippet, line 2 represents a class variable and line 4 represents an instance variable. And line 15 represents a class method, which is similar to a C# static method. A ruby class method, just like other instance methods, starts with the def keyword. Then the method is named in the format ClassName.MethodName as shown in the snippet above. In this case, @@no_instances is used to maintain a count of the number of instances of Sampleclass created so far. The class method in this case is used to print the number of instances created for this object. Line 2 initializes the class variable to 0. Whenever an instance of Sampleclass is created, this counter is incremented. Notice that it is not reset for every instantiation of this class. The class method provides a way by which the user can get to know the number of instances created so far. The snippet below demonstrates this.

a = Sampleclass.new("Hello")
a.print

b = Sampleclass.new("Hello")
b.print

Sampleclass.printInstanceCount

c = Sampleclass.new("Hello")
c.print

Sampleclass.printInstanceCount

When the above snippet is executed, the following is the output.

>ruby variables.rb
Hello from Sampleclass #<Sampleclass:0x5d8a78 @initialMessage="Hello">
Hello from Sampleclass #<Sampleclass:0x5d8988 @initialMessage="Hello">
2
Hello from Sampleclass #<Sampleclass:0x5d8898 @initialMessage="Hello">
3
>Exit code: 0

Notice lines 3 and 5, these are due to the calls to the class method and it displays the number of instances created. Hope this post was informative / refreshing!

Do post your comments!

Share

ASP.Net MVC Extreme – A Deep Dive Inside View Engines

I am back with another post in the ASP.Net MVC extreme series (as promised)! In this post lets dive into the internals of how a view is selected when an action method returns a View. MVC has the following default view engies – webform and razor and also lets us to add custom view engines. For more inforation on custom view engines, refer to my earlier post here. Custom view engines can be added using the Application_Start event as shown below:

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

   ViewEngines.Engines.Clear();
   ViewEngines.Engines.Add(new CustomRazorViewEngine());

   RegisterGlobalFilters(GlobalFilters.Filters);
   RegisterRoutes(RouteTable.Routes);
}

In the above snippet, ViewEngines is a static class provided by the framework in order to manage the view engies that the framework would look for when searching for views to render. The entire action starts with the ViewResultBase class, which is the base class ViewResult which is responsible for rendering html content to the client. There are a number of other result’s such as FileResult, JsonResult, JavaScriptResult etc and all of these derive from the ActionResult class. ViewResultBase has the ViewEngineCollection property and it’s defined as given below. The engines set up in Application_Start is provided to the ViewResult class using this property. More information on how these engines are used follows soon!

// From mvc sources/reflector
public ViewEngineCollection ViewEngineCollection {
   get {
      return _viewEngineCollection ?? ViewEngines.Engines;
   }
   set {
      _viewEngineCollection = value;
   }
}

A simple action method in mvc would resemble the following:

public ActionResult SomeActionMethod()
{
   return View();
}

The action method above returns the result of the View method from the Controller class. This method returns a ViewResult instance depending upong the parameters passed from the action method. Note that it could also be a PartialViewResult instance. The Controller type has multiple overloads of the View method. Their definitions are given below:

// From mvc sources/reflector
protected internal ViewResult View() {
    return View(null /* viewName */, null /* masterName */, null /* model */);
}

protected internal ViewResult View(object model) {
    return View(null /* viewName */, null /* masterName */, model);
}

protected internal ViewResult View(string viewName) {
    return View(viewName, null /* masterName */, null /* model */);
}

protected internal ViewResult View(string viewName, string masterName) {
    return View(viewName, masterName, null /* model */);
}

protected internal ViewResult View(string viewName, object model) {
    return View(viewName, null /* masterName */, model);
}

All of these overloads eventually call the following method:

// From mvc sources/reflector
protected internal virtual ViewResult View(string viewName, string masterName, object model) {
    if (model != null) {
	ViewData.Model = model;
    }

    return new ViewResult {
	ViewName = viewName,
	MasterName = masterName,
	ViewData = ViewData,
	TempData = TempData
    };
}

Similarly, the following method takes in an IView and has the following definition:

// From mvc sources/reflector
protected internal ViewResult View(IView view) {
   return View(view, null /* model */);
}

This method eventually calls the following method:

// From mvc sources/reflector
protected internal virtual ViewResult View(IView view, object model) {
    if (model != null) {
	ViewData.Model = model;
    }

    return new ViewResult {
	View = view,
	ViewData = ViewData,
	TempData = TempData
    };
}

If you notice the implementations of View, it creates an instance of ViewResult by passing the view name, master name, view data and temp data in the case of the first method and an IView object, view data and temp data in the case of the other method.

Coding best practices(feel free to skip this if you are aware of coding best practices): When you have a method that also has corresponding overloads, make sure that you don’t repeat the same code in both (or all) the places. Consider the following case. This method of handling overloads is bad!.

// bad practice, do not use!!!
public void FooMethod(int memberForYears, string userName)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = GetMembershipPoints();
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

public void FooMethod(int memberForYears, string userName, int membershipPoints)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = membershipPoints;
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

A nicer way to do this is given below. The refactored code below does not have repetitive code but utilizes the final method to display the results to the user. If you observe the above 2 methods, the only difference is the _membershipPoints bit which gets the value using the GetMembershipPoints method (not shown). So in the snippet below, the 1st overload is called by passing in the value from the method as the 3rd parameter.

// good practice
public void FooMethod(int memberForYears, string userName)
{
   FooMethod(memberForYears, userName, GetMembershipPoints());
}

public void FooMethod(int memberForYears, string userName, int membershipPoints)
{
   int totalDaysMemberFor = memberForYears * 365; // ignoring the fact about leap years
   int _membershipPoints = membershipPoints;
   Console.WriteLine("User {0} was a member for {1} days and has {2} points", userName, totalDaysMemberFor, _membershipPoints);
}

Before we dig in to the ViewResult class lets get a deeper understanding of the how this class is put in to use.

If you can recollect from my previous post, every controller in mvc implements the IController interface and this has the Execute method. When a request arrives, the Execute method is called. Within this method a call to the ExecuteCore method of the Controller is invoked. The ExecuteCode method then handles the responsibility to the ControllerActionInvoker.InvokeActionResult method. Within this method the ExecuteResult method of the ViewResultBase class is called, after executing the content of the action method according to the request. This method itself certainly deserves a post by the way! After this step the real action starts!!! Lets get in to that :)

The ExecuteResult method is given below:

// From mvc sources/reflector
public override void ExecuteResult(ControllerContext context) {
    if (context == null) {
	throw new ArgumentNullException("context");
    }
    if (String.IsNullOrEmpty(ViewName)) {
	ViewName = context.RouteData.GetRequiredString("action");
    }

    ViewEngineResult result = null;

    if (View == null) {
	result = FindView(context);
	View = result.View;
    }

    TextWriter writer = context.HttpContext.Response.Output;
    ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer);
    View.Render(viewContext, writer);

    if (result != null) {
	result.ViewEngine.ReleaseView(context, View);
    }
}

Note line 13 in the above snippet. This line calls the FindView overridden in the ViewResult (and PartialViewResult) class(es) to find a matching view. This method, uses the ViewEngineCollection in the ViewResultBase class to get a list of the available view engines. And then ViewEngineCollection type’s FindView method is called to find an appropriate view. This is where the engines added come in to play. The ViewEngineCollection.FindView method is given below:

// From mvc sources/reflector
public virtual ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName) {
    if (controllerContext == null) {
	throw new ArgumentNullException("controllerContext");
    }
    if (string.IsNullOrEmpty(viewName)) {
	throw new ArgumentException(MvcResources.Common_NullOrEmpty, "viewName");
    }

    return Find(e => e.FindView(controllerContext, viewName, masterName, true),
		e => e.FindView(controllerContext, viewName, masterName, false));
}

The Find method called in line 10 uses the engines defined for the application to find an appropriate view. To explore more in to this method, it’s important to see the ViewEngines class.

// From mvc sources/reflector
public static class ViewEngines {
	private readonly static ViewEngineCollection _engines = new ViewEngineCollection {
	    new WebFormViewEngine(),
	    new RazorViewEngine(),
	};

	public static ViewEngineCollection Engines {
	    get {
		return _engines;
	    }
	}
}

ViewResultBase class’s ViewEngineCollection property is set to the ViewEngines.Engines property, which is initialized with an instance of the ViewEngineCollection class created by passing the 2 default view engines available in mvc 3. If you remember (yes it’s been a long post ;) ) we use the ViewEngines.Engines property to add custom view engines. The Find method uses the engines set during instantiation to find an appropriate view. The view engine collection would either have the default engines or the custom engines or both. If this process fails, you see the generic error screen (given below) that lists all the locations searched by the framework.

As you may know, the action starts from the controller. Refer to my earlier post for more details about this. In a future post I will also try to connect the dots between these 2 posts, if I feel anything is missing. Also, I am reviewing this post to catch anything I missed, so it may be updated in the following days!

Finally, do post your comments and happy coding!

Share

ASP.Net MVC – Custom View Engines (Using the razor view engine as the base)

Okay, it’s ASP.Net MVC 3 time again! In this post I am going to discuss about custom view engines. I do not have a lot of real-time experience with custom view engines, but I wanted to try out one of my ideas of organizing the folder in a way that I feel was much more clearer. This is what I am talking about:

Views/
...Home/
......Pages/
.........Page1.cshtml
.........Page2.cshtml
......PartialPages/
........._UserControl1.cshtml
........._UserControl2.cshtml

From the textual folder structure above, I guess my intention is clear. In case you are familiar with the folder structure of MVC, There is a single “Views” folder and within this folder there are individual folders for every controller. Finally, the user controls and pages go in to these folders. If a page/user control is being shared it goes in to the “Shared” folder. In simple words, I just wanted to segregate the cshtml files further by creating a “Pages” and “PartialPages” folder.

As the name suggests, pages would go in to the “Pages” folder and user controls would go in to the “PartialPages” folder. To implement this I have created a custom view engine by inheriting the RazorViewEngine class. As the location of every file would change, we have to specify this by overriding the base string arrays that specify the possible locations of a certain type of a file (master, page, partial page).

Given below is the complete class. “%1″ in every possible path would have to be replaced with either “Pages” or “PartialPages” depending upon the method in question.

public class CustomRazorViewEngine : RazorViewEngine
{
	public CustomRazorViewEngine() : base()
	{
	    AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
						     "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
						     "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
						     "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
						       "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
						       "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
						       "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/%1/{0}.cshtml",
							    "~/Areas/{2}/Views/{1}/%1/{0}.vbhtml",
							    "~/Areas/{2}/Views/Shared/%1/{0}.cshtml",
							    "~/Areas/{2}/Views/Shared/%1/{0}.vbhtml" };
	    ViewLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
						 "~/Views/{1}/%1/{0}.vbhtml",
						 "~/Views/Shared/%1/{0}.cshtml",
						 "~/Views/Shared/%1/{0}.vbhtml" };
	    MasterLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
						   "~/Views/{1}/%1/{0}.vbhtml",
						   "~/Views/Shared/%1/{0}.cshtml",
						   "~/Views/Shared/%1/{0}.vbhtml" };
	    PartialViewLocationFormats = new string[] { "~/Views/{1}/%1/{0}.cshtml",
							"~/Views/{1}/%1/{0}.vbhtml",
							"~/Views/Shared/%1/{0}.cshtml",
							"~/Views/Shared/%1/{0}.vbhtml" };
	    FileExtensions = new string[] { "cshtml", "vbhtml" };
	}

	protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
	{
	    return base.CreateView(controllerContext, viewPath.Replace("%1","Pages"), masterPath.Replace("%1","Pages"));
	}

	protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
	{
	    return base.CreatePartialView(controllerContext, partialPath.Replace("%1","PartialPages"));
	}

	protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
	{
	    return (base.FileExists(controllerContext, virtualPath.Replace("%1", "Pages")) ||
		    base.FileExists(controllerContext, virtualPath.Replace("%1", "PartialPages")));
	}
}

To download the file, click here (right click – save as – remove the .txt extension).

As you see above, to implement your custom view engine, you just have to override the following 3 methods:

  • CreateView – This method is called with the corresponding parameters if the view requested is a page
  • CreatePartialView – This method is called with the corresponding parameters if the view requested is a partial page / user control
  • FileExists – This method also has to be overridden in this case because the implementation of this method in the base class won’t know where to look for the file because of the %1 in the path. If this method is not overridden FileExists would always return false which would cause view engine to fail in the process of finding a matching view even if one exists

Now, update _ViewStart.cshtml to specify the location of the master page as shown below:

@{
    Layout = "~/Views/Shared/Pages/_Layout.cshtml";
}

Once we have the class that implements the custom razor engine, and the corresponding change to the _ViewStart.cshtml file, we have to inform the framework to use this instead of the default engine, as the default engine won’t work anymore as the folder structure has changed. To do this modify the Application_Start method in Global.asax.cs to include lines 5 & 6. Line 5 clears all the engines currently added (in this case, just the default engine) and line 6 adds the new custom engine we created.

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

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new CustomRazorViewEngine());

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Also, look forward to another post that dwelves in to internals of view engines in mvc 3!!!

Post your comments and happy coding!

Share