Wednesday, August 18, 2010

Best way to end ASP.NET session

There are mainly three methods in Session object which serve similar purpose.

1. Session.Clear(): This will immediately remove all objects stored inside Session object. Session object basically stores a collection of key(string) vs value(object). After calling this, you will find Session.count equals to zero but Session object itself will still be alive and you can again add new key/value items to it.

2. Session.RemoveAll(): It behaves exactly the same way as Session.Clear. It just wraps Session.RemoveAt at one shot. You can specify index in Session.RemoveAt to remove items one by one. You can also call Session.Remove and pass key to remove that key/value pair item. It could be slower than Session.Clear which essentially is made just to clear all the items.

3. Session.Abandon(): If you have used Session.Clear or Session.RemoveAll, though you have got rid of any and all objects stored in session but session object itself remains alive and could be used further. Session.Abandon just cancels the current session and session object gets destroyed.
The only point to remember here is that if you have used Session.Abandon, it will just mark the session to be destroyed but nothing will happen to session object for that request. As soon as the current request gets completed, session object will be canceled. So don't get surprised if nothing looks to happening to session object just after calling the abandon method, in the next request, you will find that session object to be destroyed and a new one to be created.

Take your web application offline without any change in web server or application

This might come handy when you are in maintenance mode of your application and you want to let your user know it. How would you do it without shutting down your application or without writing additional code to redirect all requests?
The only thing you have to do is to create a file with name app_offline.htm, decorate it however you want and just put it inside the root directory of your application. Rest everything will be taken care of .NET handlers. All users visiting to your site will automatically see your offline page.
Whenever you want your application to be up, just remove that file and that's it.