Showing posts with label integrating spring.net with mvc3. Show all posts
Showing posts with label integrating spring.net with mvc3. Show all posts

Sunday, October 2, 2011

Strongly Typed Session Using MVC3 and Spring.NET - Part - 3

This is the last post in the series of posts to show How we can achieve Strongly Typed Session using MVC3 and Spring.NET.  In previous two posts (first and second) we saw what were the benefits of strongly typed session and how we could enable the session scope using Spring.NET 1.3.1.

The question that we had left unanswered in the previous post was:  

What is "session" scope supposed to do with Strongly typed sessions?

Well the session scope is the key, in this post we will see how it enables us to create a strongly typed session.

The session scope enables us, to register objects with scope=session.  Spring.NET will create one instance per user Session for objects that are configured with scope=session.  This means effectively we can use such an object to hold information that would otherwise be saved in the HTTP Session.  Since, these objects are configured in Spring.NET, they can be injected as dependencies in any other class. 

Where would we want to inject such a class?

MVC Controllers are a good place to do so.

Why? 

Because, controllers are the class that would do some business processing and then would want to set some information in the HTTP Session.

For e.g. Lets consider this scenario, we have a AuthenticationController which has a Login action.  This method takes in the username and password as argument.  This method calls the AuthenticationService to find whether the username and password combination is valid.  If the username and password are valid, AuthenticationController wants to set the username in the session so that it could be used by other pages to show user information on the page.

In our case we do not want to use the HTTP Session.  Hence, our AuthenticationController will put the username in some object, let's call it UserContext, which has been configured in Spring.NET with scope="session".

But wait,

What if two users are trying to login at the same time?  Will one thread overwrite the username saved in the UserContext by the other thread?

As the UserContext object is configured with scope="session", Spring.NET is smart enough to understand that, two requests are coming  to AuthenticationController are coming from two different user sessions, it injects two different instances of UserContext in the AutheticationController for two different user sessions.  Hence, one thread will *not* overwrite the username set in the UserContext by the other thread. 

So far so good.

What happens when, user who had logged in earlier (i.e. UserContext has the UserName property set), sends another request to the server?  How do we ensure that correct UserContext instance is injected in the Controller so that previously set UserName could be retrieved?  

Again, Spring.NET is smart enough to understand that, for the given user session an instance of UserContext was already created, Spring.NET will find the correct UserContext instance associated with the user session and injects it in other Controllers/objects that need it.  This effectively eleminates the direct use of HTTP Session for us.  We can be sure that, whatever information we set in UserContext will be specific for a given User Session and correct UserContext instance will be injected in the controller whenever we need it.

I know, at first it all looks very confusing, but lets look at the code to make things clear.

These are the steps required to configure the UserContext and AuthenticationController
  • Register the UserContext in Spring.NET configuration file with scope="session"
  • Write the implementation for the UserContext
  • Register the AuthenticationController in Spring.NET configuration flie with singleton="false".  Add to this the dependency of UserContext.
  • Write implementation of Login Action to set the UserName Property in the UserContext.  Write another action method let's call it UserInfo which will retrieve the UserName Property from the UserContext object and display it on the UI
  • Write the RazorIndex view to show the UserName from the ViewBag 
  • Test that the setup is working with two different browser windows trying to Login and access the UserInfo at the same time.  We should see correct user names being displayed based on where the request is coming from
Lets look at individual steps in detail

Register the UserContext in Spring.NET configuration file with scope="session"

Update the web.xml and add the configuration for UserContext as follows
Notice that we have registered the UserContext object with scope="session". Spring.NET will understand that the UserContext object is registered with singleton but in session scope i.e. One UserContext object per user session.

Write the implementation for the UserContext 

The UserContext class would be simple enough.
Register the AuthenticationController in Spring.NET configuration flie with singleton="false".  Add to this the dependency of UserContext

Update the web.xml to add the configuration for AuthenticationController as follows. 
Write implementation of Login Action to set the UserName Property in the UserContext

AuthenticationController will have a Login Action and UserInfo Action.  Login Action will set the UserName in the UserContext.  For demonstration purpose we will append the SessionId to the UserName.  This will show us that, when we request the login action method from two different browser windows we will see different user name on the UI.
Write the RazorIndex view to show the UserName from the ViewBag

The RazorIndex.cshtml will simply show the UserName from the ViewBag if its not null. Else it will show no user logged in yet message.
Test that the setup is working with two different browser windows trying to login and access the UserInfo at the same time

Enough theory, lets see the setup in action.  As they say,

Real test is in the real world!

Let's try and browse the URL Authentication/UserInfo from FireFox and Internet Explorer and see what happens

User not logged in - FireFox

User not logged in -IE
As the UserName is not set in UserContext we see no user name set message.

Now in IE, lets browse the URL Authentication/Login and see what happens.
User Successfully Logged in.  UserName and SessionID shown - IE
As we can see, the page redirect to the Authentication/UserInfo User name with session id is shown.

Lets reload the Authentication/UserInfo the page on FireFox.  Remember that, we have not yet visited the Login page on FireFox, but we have visited the Login page on IE.
Even after user is logged in on IE, he/she is not logged in on FireFox
Yep even though we have set the UserName in the user session started from IE, it does not effect the UserContext reference in the User Session started from FireFox.

Now lets visit the Authentication/Login URL in FireFox as well to see what happens.


Now user is logged in even in FireFox





As you can see it redirects to Authentication/UserInfo with UserName set.  Notice that the session id in FireFox window is different from the session id in IE.
Notice that the Http SessionId are different in two images

This effectively proves that UserContext reference plugged in by Spring.NET when request comes from IE is different from the one that gets plugged in when request comes in from FireFox i.e. We have successfully injected different UserContext reference per User Session. UserContext object can now be used to hold any information that would have be placed in HTTP Session. This effectively eliminates the use of HTTP Session and gets us a strongly typed object which can be used as a replacement to the HTTP Session.

That's it! we have successfully achieved Strongly Typed Session in an MVC3 application using Spring.NET.

Tuesday, September 27, 2011

Strongly Typed Session Using MVC3 And Spring.NET - Part - 2

In my previous post, we saw why its a good idea to have strongly typed HTTP Session. In this post we will do the real thing (well at least first part of the real thing).

Using Sping.NET we can control the objects lifecycle. By default the Objects configured in Spring.NET are Singleton for the entire application (singleton for scope="application"). Singleton for the entire application means, Spring.NET will create only one instance of the given object for the life-cycle of the application.  Service classes, DAO classes etc are a good fit for Singleton Pattern.

However, there are other Object Scopes that can be configured in Spring.NET.  These Scope's tell Spring.NET that, A given object is singleton but in a given scope.

One of the interesting scope is session.  Session scope is only available if we use a web-aware Spring IApplicationContext implementation.  For such objects, Spring.NET would create one instance per HTTP Session.  In this post we will see how we could take advante of the session scope, to create Strongly typed session in an MVC3 application.


Enough blabber.  Let see how exactly its done.

How do they do it!

As we had seen in one of the previous post to Integrate Spring.NET with MVC3 application, we had used the Spring.Context.Support.MvcContextHandler.  This class instantiates Spring.Context.Support.MvcApplicationContext, which in turn initializes the spring application context.

Support for session scope is porivded by spring.web.dll.  Unfortunately, as of Spring.NET 1.3.1, spring.web.mvc.dll does not depend on spring.web.dll, which effectively means, MvcApplicationContext is unaware of the session scope.

Hence, using just the MvcApplicationContext there is no way we can eable the session scope for a certain objects.  Its a bug you can find more details here.  But where there is will, there is a way!  There is obviously a way around this problem.

Here are the steps to enable full session scope support for any object in Spring.NET 1.3.1
  • Update the web.config to use a custom WebContextHandler
  • Register the spring WebSupportModule in web.config under the <httpModule> section for IIS6 and under the <modules> section for IIS7+
  • Implement the custom WebcontextHandler.  Override the property DefaultApplicationContextType.  This property informs Spring.NET about the class type of ApplicationContext that Spring.NET should instantiate.  This will be again a custom class that extends from Spring.Context.Support.MvcApplicationContext.
  • Implement the custom class that inherits from Spring.Context.Support.MvcApplicationContext.  This class will basically override two methods
    • CreateXmlObjectDefinitionReader to return the instance of WebObjectDefinitionReader
    • CreateObjectFactory to return the instance of WebObjectFactory
That's it!  We have now successfully enabled the session scope for Spring.NET 1.3.1.  Let look at the actual code.

Step - 1 - Update the web.config to use a custom WebContextHandler

Update the web.config configSection to look like

The class aspnetwebFormsWithMvc3App.Context.MvcWebContextHandler is our custom class where we will override the property DefaultApplicationContextType.

Step - 2 - Register the spring WebSupportModule in web.config under the <httpModule> section for IIS6 and under the <modules> section for IIS7+ 

Adding the spring module for IIS6 and IIS7

Step - 3 - Implement the custom WebcontextHandler

Lets look at the custom WebcontextHadler class aspnetwebFormsWithMvc3App.Context.MvcWebContextHandler

As you can see this class is pretty simple, it just overrides the property DefaultApplicationContextType to return the class type of custom WebApplicationContext.

Step - 4 - Implement the custom class that inherits from Spring.Context.Support.MvcApplicationContext

This is the class where the real work is done.
That's it! We have successfully enabled the session scope in MVC3 application using Spring.NET.

Question is: What is all this supposed to do with Strongly typed sessions?

In the next and the final post in this series, we will see how we can take advantage of session scoped objects to create the Strongly Typed Session in an MVC3 application using Spring.NET. 

Wednesday, September 21, 2011

Strongly typed Session with MVC3 and Spring.NET - Part - 1

In every Web project I have worked so far, always there is a need to store some or the other information in HTTP Session.

I am very finicky about putting things in the HTTP Session.  IMHO HTTP Session should be kept as light as possible.  There should be a very very strong and compelling reason to put a certain value in the HTTP Session.  Having said that, I do agree that there are times when we want to put certain information in the HTTP Session like user name, user id, etc.

With me so far?  Till now we understand that, we do not like to put things in HTTP Session, however, we understand that there is a definite need to put certain things in HTTP Session for the app to work correctly.

Question is, Is there an alternate to putting things in HTTP Session?

In this series of three posts we will try to answer this question.  We will try to use MVC3 and Spring.NET to eliminate the need of putting stuff in HTTP Session.

But wait a minute, let's first answer this question,

Why is putting things in HTTP Session is such a bad idea?  

Lets start by looking at the code that will put UserName into the HTTP Session.
Does it remind you of code that you have seen in one of your applicatoin? It certainly reminds me of code that is used all over the place in one of the projects that I had worked.

I totally hate to see code like this.  Why whats wrong with such code?

Session is used like a Hash Table:

In our example, key of the hash table would be UserName and value will be Git Shah.  Imagine while putting/retrieving values to/from the HTTP Session, if incorrect keys are used, results could be catastrophic.  Even a small typo like one shown in the example below would yield incorrect results
Ofcourse there are ways to get around this problem. Simplest of them is to use a Static Class that holds all the keys as constants.

However, you can still not gaurentee that every programmer on your team will always always use constant keys from the static class.  Believe me, because of human error or some other unexplainable reason, someone would use hardcoded inline key to put value in the Session and rest of the team will curse him/her for eternity! 

Session values are not strongly typed:

We have inserted a string value Git Shah in the HTTP Session against the key UserName but when we want to retrieve the value from the session we will have to typecast to its correct type.  In our example to retrieve the value of UserName key in HTTP Session code would look like
I have a name for code like that, I call it A Time Bomb!

Its just a matter of time before which you start getting a class cast exception.

Dude, whats in my Session? Where are these values used?

Can we say for sure what all values are stored in our session?  

Another important question to answer is, Can we say for sure, from what all places in the code are these values accessed?

These are a very important questions.  Answers to these questions are absolutely vital for the health of your application.

In one of the projects that I had worked, we were extremely confused for a very long period of time.  The question that was bothering us was, who was setting a specific value in the session and in what condition?

Consider an example

UserName key is populated in the LoginController.Login method. Lets look at another place where UserName is used.
AccoutController.UpdateUser updates the value of the UserName key in the HTTP Session to the new value passed as argument and AccountController.GetUserDetails method fetches the value of the UserName key from the HTTP Session and sets the ViewBag.UserName property.

As you can see in our simplistic example UserName key of the HTTP Session is used at three places.  In real life, it would be used in many more places than this.  The code that accesses the UserName key from the HTTP Session would be littered all over the place!

How will we find the exact places where UserName key is populated/fetched into/from the HTTP Session?

There is no easy way to find the exact places where UserName key of the HTTP Session is used.  We can extract a constant for the UserName and then search for its usages, but still this is not a full proof way, as I mentioned earlier, there are many fools out there who will not bother to use the constant and use an Hardcoded string key instead.

These are few of the problems that are a big concern to me.  Question to be answered is,
  • How can we avoid such code?  
  • How can we achieve an alternate option that will discourage people from writing such code?
Before we dig deeper into the solution, lets first focus on some of the design goals that this new solution should have.
  • Things that we put into and fetch from the session should be strongly typed objects.  There should not be any cast of any sort.  This will avoid Time Bomb like code.
  • Session should not be used as a Hash Table.  Whatever we put into the session should become a property of the session which can be accessed from anywhere in the code.  Moreover, because it becomes a property of the HTTP Session, we would get all sorts of intelli-sense on it.  There is no chance of any typo in this case.  For e.g. the existing code
Should no longer be required instead we should have code that looks like
  • At any point in time, it should be easy enough to find the exact places where a certain property of HTTP Session is used. In some ways this point is related to the previous point. If we are able to convert Keys of session into strongly typed Properties then we can just search for the usages of those properties and we know exactly where those properties were used!
Enough goals to start with.  Question is, Can these goals be implemented in real life? 

Well, the good news is, these goals are definitely implementable.  In fact its not too difficult to implement these goals when we use Spring.NET with MVC3. 


What is the bad news?  You will have to wait for my next posts to see how exactly we could implement these goals :)

Stay tuned folks in the next couple of posts we are going to have some fun with HTTP Session Management!

Monday, September 5, 2011

Fixing the The virtual path '/test/currentcontext.dummy' maps to another application, which is not allowed

We have recently integrated Spring.NET in an MVC3 application.  In one of my previous post, I have already documented the detailed process of integrating Spring.NET with MVC3 application.  Spring.NET is really helpful when it comes to writing Modular, Testable code.  I totally recommend Spring.NET as Dependency Injection framework of choice!

We did a fresh deployment of our application on a new server.  On this computer, when we tried to access any of the pages of our application we got an error which looked like

Virtual Path Maps to Another Application, is not allowed
That was not very encouraging.  How can an application that was working correctly on all other servers stared giving exceptions for this particular server?

We tried to find out what were the differences between the other server and this new server.  We narrowed it down to one very interesting difference,  we used to deploy our project as a website in IIS on all other server.  While on the server that was giving us exceptions, we deployed our application as a virtual directory under the default website.  This very curious difference was giving us exceptions while initializing the spring context.

I Googled a little and found out that this is a known issue which has been reported here and here.

The workaround to this issue was simple enough, we just have to give a name the spring context in web.config. 

Would any random name work?  Do we have to follow some convention?

Our Spring.NET section in web.config file looked like
By now it should be clear that, we have to add a name attribute to node. But the question is, what value should it hold?

The answer is pretty simple, the Spring.NET context should be named after the virtual directory under which the application is deployed.  For example, if the virtual directory under which the application is deployed is called springmvc.  The updated web.config should look like

This did the trick! After making this change we were able to browse all pages in our application and Spring.NET integration with MVC3 application was working well!

Small issues like these have very simple solutions but, one might end up spending quite some time before finding a satisfactory solution.  I decided to document my finding for the benefit of the community!

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!
Have some Fun!