Sunday, August 28, 2011

Integrating NHibernate with Spring.NET and MVC3

We have seen in one of the previous post that its not very difficult to integrate Spring.NET with MVC3 application.  Almost every real project has a need to talk to a database for doing stuff.  When it comes to interacting with the Database, NHibernate does an Awesome job. 

I have used NHibernate with legacy database as well as databases that were designed from scratch.  IMHO, other competing products have a long way to catchup before they can be compared with the flexibility that NHibernate offers!

Recently, in one of MVC3 project we integrated NHibernate using the Fluent API with Spring.NET.  This process is not very difficult but it involves a few steps.  I decided to document the steps for the benefit of the community.

We will continue from where we left in the previous post, if you did not read the previous post already then, I strongly recommend reading it to understand how you can integrate Spring.NET with MVC3 application.

Very well than, Lets start!

To integrate NHibernate using the Fluent API in a Spring.NET MVC3 application one has to do the following
  • Make the Web.config changes to include the Parsers config section in the spring configuration.
  • Register the OpenSessionInView HTTP Module in web.config.  We will be using single session per request, NHibernate session handling strategy.
  • Add the reference to the required DLL's
  • Register the DB provider in the spring configuration file.
  • Register the NHibernate Session Factory in the spring configuration file
  • Write a custom implementation of the NHibernate Session Factory that loads and registers the Assembly that has Fluent NHibernate mappings in it.
  • Register the Transaction Manager in the spring configuration file
  • Enable the Spring AOP Transactions using attributes in the spring configuration file
  • Test out the NHibernate integration
Lets execute the steps one by one.  Please remember I will be continuing from where I left in the previous post.  Hence, I will be assuming that you already have Spring.NET correctly integrated in your MVC3 application.

Step - 1 - Make the Web.config changes to include the Parsers config section in the spring configuration

To integrate only Spring.NET with MVC3 application we had to add a configurationSection called context.  To integrate NHibernate with Spring.NET in a MVC3 application we have to add another configurationSection called parser.  This section will help Spring.NET understand the Database and Transaction configuration.  Lets look at how its done.

Step - 2 - Register the OpenSessionInViewModule HTTP Module in web.config. We will be using single session per request, NHibernate session handling strategy

Why do we need the OpenSessionInViewModule HTTP Module?

This will ensure that before the request is processed by any Controller, NHibernate session is opened and attached to the current thread.  And just before sending the response to the client, the NHibernate Session will be flushed and closed.  This enables us to do lazy loading even when the View is being rendering.  Lets look at the web.config change required to enable this:

Step - 3 - Add the reference to the required DLL's

For integrating NHibernate with Spring.NET and MVC3 application we need to add the references of following spring DLL's
  • Spring.AOP.dll -> Used to enable AOP using Spring.NET.  This will be heavily used when we enable transactions in our application.
  • Spring.Data.dll -> Used to enable the Spring.NET Database module
  • Spring.Data.NHibernate30.dll -> Used to integrate Spring.NET with NHibernate
  • NHibernate.dll -> The core NHibernate DLL
  • Iesi.Collections.dll -> Provides the ISet interface and its implementation
  • FluentNHibernate.dll -> Used to enable FluentNhibernate configuration for NHibernate
  • log4net.dll -> Used by NHibernate for logging.  Lot of effort has been put into making the NHibernate log as detail as possible and as readable as possible.  This is a great tool when it comes to debugging something that you cannot understand easily
  • NHibernate.ByteCode.Castle.dll -> Used by NHibernate to enable Dynamic Proxies
  • Castle.Core.dll -> Used by NHibernate to enable Dynamic Proxies using Castle
Step - 4 - Register the DB provider in the spring configuration file

This step is pretty simple.  We need to inform NHibernate about the Database.  This is done by registering a DbProvider in the spring configuration file.  We will be registering the DbProvider in the web.xml (web.xml was the file we created in the previous post.  This hold all the Spring.NET configuration).  Add following configuration to the web.xml

Notice that we have to define the db name space in the objects root tag. Please update the above configuration with the DB Credentials that you are using.

Step - 5 - Register the NHibernate session Factory in the spring configuration file

Session Factory is a heavy weight NHibernate object.  Only one instance of SessionFactory is create per database.  Lets look at the Spring.NET configuration file for registering the NHibernate Session Factory.

The above configuration registers a NHibernate session factory which is of type aspnetwebFormsWithMvc3App.NHibernate.FluentNhibernateLocalSessionFactoryObject and is found in the assembly aspnetwebFormsWithMvc3App.  This is a custom class that we will create later in the post.  It has various properties like
  • Which DbProvider to use
  • What are the FluentNhibernateMappingAssemblies.  This is a list of assembly names which our NHibernate Session factory class will search for to locate Fluent Nhibernate mappings
  • What are the MappingAssemblies.  This is a list of assembly names which has normal NHibernate mappings
  • What are the HibernateProperties.  These are the key value pairs of NHibernate properties that we would want to use.  We are setting the connection provider, dialect, driver_class and sql_sql values
Step - 6 - Write a custom implementation of the NHibernate session factory that loads and registers the Assembly that has Fluent NHibernate mappings in it

We have to provide a custom implementation of NHibernate Session Factory class so that we could load our Fluent NHibernate assemblies.  These assemblies will have the Fluent NHibernate mapping classes.  The code of our Custom NHibernate Session Factory looks like this

Step - 7 - Register the Transaction manager in the spring configuration file

NHibernate always interacts with the database using Transactions.  We would definitely want to control how and when the transactions are started and ended.  For that to happen we need to register the transaction manager in the spring configuration file.  Add the following to the web.xml spring configuration file.

Step - 8 - Enable the Spring AOP transactions using attributes in the spring configuration file

We would want to govern how and when the transactions are started using Attributes.  For this to happen we need to inform Spring.NET that we are going to use Attributes to define the transactional behavior we need.  Spring.NET reads these attributes and starts/commits/rollbacks transactions using AOP.  To inform spring.net about our intentions add the following line in web.xml spring configuration file.

Notice that we added the line tx:attribute-driven but we also added the namespace tx in the objects root node declaration.

If you have followed all the steps so far then you have successfully Integrated NHibernate with Spring.NET in an MVC3 application.

Step - 9 - Test out the NHibernate integration

To test out our brand new NHibernate integration with Spring.NET in an MVC3 application, lets change the implementation of the AccountService.UserCount method.  Currently the AccountService.UserCount method returns a hard coded value of 5454We will now replace it with the correct implementation, we will get the record count from the User table.

We will have to create an NHibernate entity that maps to the User table.  Lets create the User class that will map to the User table.  We will also create a class called UserMap class that will hold the NHibernate Fluent Mappings for the User class.

The details are embedded in comments. We have the User entity class and the UserMap mapping class to hold Fluent NHibernate mappings.

Now, its time to actually use the User class to get the count of number of users in the database.  To do that, we will have to inject the SessionFactory instance in the AccountService.  Updated Spring.NET configuration file web.xml would look like

After injecting the SessionFactory its time now to change the implementation of the UserCount method to return the count of users from the users table. Updated AccountService looks like

Since we have registered the OpenSessionInViewModule HTTP Module the GetCurrentSession method of SessionFactory instance will return the same session instance that was created by the HTTP Module. This is absolutely vital for the Lazy loading to work correctly.

Also notice that we have added the [Transaction] attribute to the method UserCount with TransactionPropagation as Required.  This will make sure that whenever the method UserCout is invoked either a new transaction is started or the method will join any existing transaction started earlier in the same thread.

All set!  Its time to run the server and browse the /Home/SpringIndex URL to see if our integration with NHibernate works!
Showing the actual user count using NHibernate
As show in the image we are successfully getting the UserCount from the database.  We have successfully integrated NHibernate with Spring.NET in an MVC3 application!

Sunday, August 21, 2011

India Against Corruption

No matter who you are or what you do, everyone in India has heard about Anna Hazare.  Team Anna Hazare, has been protesting at ramlila maidan (in New Delhi) against the Government and is trying to push the Jan Lokpal Bill.

Over the years, Corruption in India has grown by leaps and bounds.  Everywhere there is some or the other form of corruption.  From getting a motor driving license to getting admission in a school/college, we i.e. the common man has to face corruption at all levels.

At bigger levels there is bigger corruption.  Indian politicians have found a way to exploit the system in the way they want it.  May it be, organizing Common Wealth Games or building roads, corruption is everywhere.

Corruption has made our nation handicapped.  Team Anna hopes that by implementing the Jan Lokpal Bill we can curb the corruption at high level by 60-65%.  I certainly hope that it gets implemented.

But what about us?  

At times, in many situations, we feel helpless against the system.  To get around it, we ourselves fuel the corruption.  Its high time that we change ourselves.  How many times we have given 100 Rs to the traffic cop and not taken a receipt?  I am sure most of us have done this, I certainly have done it.

Corruption is a two way process, person who is taking money is corrupt and person who is giving money is also corrupt.  We common man have to make sure that from now on, we will never every fuel corruption ourselves.  If we can do that, corruption can be reduced even further.  This is the first step!

Team Anna is taking great pains to push the Jan Lokapl Bill, the least we could do is change ourselves and stop fueling corruption.

In my entire life span, I have never seen India as united as it's today!  People of India want to get rid of corruption. 

A few days back, if we asked who he/she was, they would say they are Hindu, Muslim, Christian etc. but today we are all Indians!  Indians who want a change!  We have forgotten our petty differences and have reunited.  It feels like a nation with 1 Billion+ people, aiming for one thing i.e. get rid of corruption!
 
My only message to government is, you better pay attention to our demands, else wait and perish!

There are very few times when we get to be part of history, in India today is that day!  Lets support Team Anna in this historic movement to remove corruption from our country! 

Charity begins at home, lets take a oath today that we will not fuel corruption in any way!  No more bribes!

Lets do whatever we could to support this movement in whatever way we could!  Jai Hind!

Saturday, August 13, 2011

Integrating Spring.net with MVC3

If you are doing any kind of serious project, you sure want to use some sort of dependency injection.

Why do I need dependency injection?

Lot's of people have written lot's about why dependency injection is required.  I am not going to repeat all that, just a few points that I think, cannot be ignored

  • Configuration flexibility - alternative implementations of a given service can be used without recompiling code
  • Testability - Since we can provide alternative implementation of any given service at any time, any class can be unit tested very easily and effectively.  Its easy to inject a fack implementation of a service in the class we want to unit test
  • Reduction of Boiler plate code - Since we no longer need to create instances of classes and inject them with proper dependencies
  • Promotes loose coupling between classes and subsystems - Since classes are not dependent on a specific implementation, they are dependent on the contract that the other classes expose.
Enough said about dependency injection.  At this point if you are still not convinced that you need dependency injection, then I strongly recommend reading the full series of posts on Dependency Injection from Fabien Potencier here

Alright, so we need dependency injection, what next?

How do we implement dependency injection?  Should we hand code the logic and create our own way of doing dependency injection?

Well, take my advice, never ever, never every do that!  Always look for options, you will surely find one depdendency injection framework/container that suites your requirements.  Even if it does not fit your requirement completely, I am sure the framework/container provides enough hooks, based on which you can customize it to you taste!
In the year 2011 and beyond, you cannot be serious if you are wasting your time and someone Else's money writing a dependency injection framework (I know a few people who have done that, can you believe it!)

What is Spring.NET?

Spring.NET is an awesome dependency injection framework (actually its lot more than that).  Its open-source and its design is based on the proven Java based Spring Framework.  The breath of functionality in Spring .NET spans application tiers which allows you to treat it as a "one stop shop" but that is not required.  The best thing about Spring .NET is, its not an all-or-nothing solution.  You can use the functionality in its modules independently.  Spring.NET integrates with a lot of other projects like NHibernate, NUnit, Active MQ, Quartz .NET, Velocity etc.


Enough about Spring.NET, if you want to know more details about Spring.NET, I strongly recommend visiting this site, it has all the info you need.  It has links to the latest documentation, blogs, articles, faq's etc.

By this time we agree that, we should use a dependency injection framework and for the sake of this post, I am going to show how easily we can integrate the Spring.NET dependency injection framework in our MVC3 application.  Lets not waste any more time and jump into the code straightaway to get this part started, shall we!


How do they do it?

To Integrate Spring.NET into the MVC3 application you will need to do the following steps
  • Add the Spring.NET dependencies to the project.
  • Make the web.cofig changes to register the spring context
  • Declare the dependencies in an xml file
  • Write the code to interact with the dependencies in the HomeController
  • Inherit the Global class in the Global.asax.cs file from Spring.Web.Mvc.SpringMvcApplication
Lets have a look at each step one after the other.

Add the spring.net dependencies to the project

For integrating Spring.NET in your MVC3 application you will need to add references of following Spring.NET assemblies.
  • Spring.Core.dll
  • Spring.Web.dll
  • Spring.Web.Mvc.dll
These dll's can be found in the downloaded Spring.NET zip package from this link.

Make the web.config changes to register the spring context

In this step we add a <configSection> for the Spring.NET configuration.  In the spring config section we would like to register the spring context.  Update web.config should look like

What we are doing here is, telling Spring.NET to look for a file called web.xml inside the Config directory.

What will the web.xml file contain?  

It will contain the dependency injection configurations for the classes in our application. 

Declare the dependencies in an xml file

Spring will search for a file named web.xml inside the Config directory, directly under the root of you application.  Lets make sure, Spring finds the file.  Create a directory called Config at the root level of your MVC3 application and create a file called web.xml inside it.  The project structure should look somewhat like this

Project Structure with web.xml included in the project
Now, its time to register our dependencies in the web.xml.  We are going to add a very simple dependency of IAccountService that will give us total number of users in the system.  The web.xml would look like this

The web.xml is just a plain XML file that uses Spring.NET xml schema to inject the AccountService into the HomeController. We have given an id to the HomeController its Home in our case. We are also declaring that HomeController has a property Called AccountService. This property will be auto injected by the Spring.NET container with the reference of type AccountService.

Notice that the HomeController is not a singleton class.  MVC3 framework creates a new instance of the Controller every time a request comes for that controller.  Hence, Spring needs to know that, the HomeController is not supposed to be a singleton class.  This is done by adding the attribute singleton="false" in the declaration of the HomeController.

The next declaration in the web.xml is that of AccountService.  For the sake of this example this class has no dependencies.  For our example this class is going to be very simple it will return some hard coded values.

Notice that the singleton attribute has not be specified for the declaration of AccountService.  By default the singleton value is true, this means that the AccountService is a singleton class.  Spring.NET will  instantiate only one instance of the AccountService for the entire application!

Write the code to interact with the dependencies in the HomeController

As seen in Step - 2, HomeController is going to have a property of type AccountService.  We are going to query the AccountService to get the user count which will be eventually be shown on the UI.

As you can see there is no magic in our classs. HomeController simply calls the AccountService to get the UserCount and sets the value in the ViewBag. The AccountService implementation is extremely simple, it returns a hardcoded value of 5454.

Lets look at the view SpringIndex.cshtml that will show the UserCount from the ViewBag.

As you must have guessed, the view could not have been any simpler. It simply shows the message with the UserCount in it.

Inherit the Global class in the Global.asax.cs file from Spring.Web.Mvc.SpringMvcApplication

We are almost done with all the plumbing required to integrate Spring.NET with MVC3 but, one last thing is left.  We need to inherit our Global class in the Global.asax.cs file from Spring.Web.Mvc.SpringMvcApplication instead of System.Web.HttpApplication.  This is required so that Spring registers the controller factory to instantiate the Controllers when the request comes.  This is done so that Spring gets an opportunity to dependency inject the controllers.

And we are done! Lets run the application and browse the URL /Home/SpringIndex to see what happens. If you have followed the post till this point, browsing the url will result in a page like this
SpringIndex renders with UserCount value
The User count 5454 is coming from the AccountService which we successfully injected into the HomeController.

When the request for SpringIndex action of the HomeController comes to the server  following things occur
  • Spring intercepts the call and instantiates HomeController 
  • Injects all the dependencies of HomeController i.e. AccountService in our case
  • Calls the action method SpringIndex to complete the request
  • SpringIndex method calls the AccountService to get the UserCount and sets it in the ViewBag
  • SpringIndex.cshtml is rendered which shows UserCout!
We have successfully integrated Spring.NET with a MVC3 application!  That's all folks!

Saturday, August 6, 2011

Asp.Net MVC3 and Asp.Net Web Forms Side-By-Side in One Project - With Razor Views

In The previous post, I explained how we could use MVC3 and Asp.Net Web Forms Side-By-Side in One Project.  In that post, we were rendering MVC3 pages using the ASPX View Engine.  ASPX View Engine is the legacy view engine, Razor View Engine has significant advantages over the ASPX View Engine.  In this post we will see how we could use the Razor View Engine instead of the ASPX View Engine. 

The Asp.Net MVC 3 has always supported the concept of view engines – which are the pluggable modules that implement different template syntax options.  Razor view engine is optimized around HTML generation using a code-focused templating approach.

Why Razor View engine?

Razor View engine is build with the following design goals (read the detail design goals here)
  • Compact, Expressive, and Fluid: Razor minimizes the number of characters and keystrokes required in a file, and enables a fast, fluid coding workflow. Unlike most template syntax's, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
  • Easy to Learn: Razor is easy to learn and enables you to quickly be productive. You use all your existing language and HTML skills.
  • Is not a new language: Razor enables developers to use their existing C#/VB (or other) language skills and deliver a template markup syntax that enables an awesome HTML construction workflow with language of our choice.
  • Works with any Text Editor: Razor doesn’t require a specific tool and enables you to be productive in any plain old text editor (notepad works great).  That said, I have to mention this, Resharper 6.0 has one of the best support for Razor Syntax.  Its a paid tool but its definitely worth the price.
  • Has great Intellisense: While Razor has been designed to not require a specific tool or code editor, it will have awesome statement completion support within Visual Studio.
  • Unit Testable: This is one of the most important Design Goal.  Razor implementation supports the ability to unit test views (without requiring a controller or web-server and can be hosted in any unit test project – no special app-domain required).
If you want to see a detailed reasoning of why Razor is better then ASPX View Engine, I strongly recommend vising this link

Now that we are convinced that, Razor View Engine is better than ASPX View Engine, lets integrate the Razor views in our Asp.Net Web Forms application with MVC3 integrated in it.

How Do they do it?

Initially, I though there must be setting somewhere in the project properties which will enable us to use the Razor View Engine, however, after several wasteful minutes of searching and researching in the project properties I found that, there is no such setting, we can directly go ahead and create the Razor view in the project.

Razor views have an extension of cshtml.  Lets create our first Razor view called RazorIndex.cshtml right next to the Index.aspx that we had created in the previous post.  This view will have nothing special, it will display one message that we set in the ViewBag.

Notice that we are displaying the UserName from the ViewBag.  Notice that, in the new Razor syntax, we have to use the @ sign to access any objects and properties.

Let's add one more method in our HomeController which will render the RazorIndex view and set the UserName in the ViewBag.  The controller code will look no different from how it looked for rendering ASPX pages.

This is a very good example of showing, how well the Seperation of Concerns Design Pattern has been implemented in MVC3.  Even though we want to use a different View Engine, controller code remains unchanged.  In fact, Controller has no idea about which View Engine will be used to render the view.  This is an excellent example of why things should be loosely coupled to achieve modular and clean code!

Before we can see if our Razor view is rendered correctly or not let's not forget to add one more route to our routes collection in Global.asax.cs file

We have just added one route called RazorHome. All set! Lets build the project and access the URL /home/razorindex and see whats the outcome.
First attempt to render Razor View results in an compilation error
OK does not look too good.  The error states that The type or namespace name 'Helpers' does not exist in the namespace 'System.Web'  To fix this we will have to do a change in the web.config.  We will need to add a few assemblies in the  <system.web><compilation> section.  The updated web.config would look like

After this lets build and access the URL /home/razorindex and les see what happens
Second attempt at rendering the Razor view also results in compilation error, this time it cribs for ViewBag
Still not quite there, but getting closer.  This time the error says that The name 'ViewBag' does not exist in the current context.  The problem is that the compiled class RazorIndex_cshtml is extending System.Web.WebPages.WebPage class.  As we had seen in the previous post, MVC views needs to extend from System.Web.Mvc.WebViewPage and not System.Web.WebPages.WebPage. 

How do we fix this issue?

We need to some how tell the framework that the Razor pages should extend System.Web.Mvc.WebViewPage class.  This is done by adding another web.config in the Views directory.  The project structure would now look like this
Project Structure with two web.config's
The content of this new web.config should look like

The element <pages pageBaseType="System.Web.Mvc.WebViewPage"> tells that, the Razor views will have base class of System.Web.Mvc.WebViewPage.

Lets Rebuild the app and browse the URL /home/razorindex and see what happens.
Success! Razor view renders correctly
Bingo!  We have an Asp.Net Web Forms application with MVC3 Razor views integrated in it!

PS: Now you have no reason to not move to ASP.NET MVC3 from Web Forms, we have proved that MVC3 can co-exist with a Web Forms in the same project!
Have some Fun!