Showing posts with label session. Show all posts
Showing posts with label session. 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!
Have some Fun!