Top 10 custom JavaScript functions of all time Wednesday, Sep 29 2010 

UPDATE: For anyone who lands on this article months after the fact, there is now a podcast entry about this article reviewing each and every function.

If there was ever a universal common.js shared among the entire develosphere, you’d fine these ten (plus one bonus) functions. It would be the swiss army knife no developer would go into production without. They have no doubt been tested tried and true and have proven usefulness and helpfulness to all those who’ve used them. So without further ado, here are what I believe to the top ten greatest custom JavaScript functions in use today.

Upon further reading this article, it is suggested that for this article in particular the reader should use an alternate style with cleaner whitespace and larger margins. This is available by selecting Clean with Whitespace available on the side bar.


Surely a staple to event attachment! Regardless to what version you use written by whatever developer, it does what it says it does. And of course as you might of known, I’ve put together quite a handy version myself recently of addEvent() with some help from the contest winner and Mark Wubben along with a few minor syntax adjustments. But just to be fair to Scott Andrew, here is the original that started it all.


function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	else {
		elm['on' + evType] = fn;


Originally written by Simon Willison and highly adopted by many others as a simple way to add events to trigger after the page has loaded. This of course attaches all your events to the onload event handler which some still see as necessary, nevertheless it does exactly what it’s supposed to, and does it well.


function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	else {
		window.onload = function() {

Of course another method is to simply assign multiple event listeners to the window by using addEvent() as described in number 10 as follows:




Originially written by nobody in particular. Several developers have implemented their own version and no one single version has proven to be better than another. As you might expect, my humble self has even had acrack at it. This function was spawned from developers needing a quick and elegant way of grabbing elements by a className and to a developer’s surprise, it’s not an original DOM method as one might think…afterall, we have getElementByIdgetElementsByName()getElementsByTagName, what the hell happened togetElementsByClass??? Here it is in all its glory:


function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\\\s)'+searchClass+'(\\\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
	return classElements;

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!


Originally written by Dean Edwards as a way to query the DOM according to CSS properties which supports amultitude of selectors. However in all fairness, this is more like a mini-library and not quite so light on the weight factor, but still, a very kick-ass function. Due to its length (and CC lisencing) I won’t post it on this site. Full documentation can be found on the myCssQuery reference and download page.


To be totally honest, there are probably more variations of this function than there needs to be. The history of ‘toggling’ basically comes down to showing/hiding an element upon an event being fired. To make matters much simpler, I too have put one together. But by no means is it considered the ultimate toggle function, but it does do the basic functionality of showing and hiding.


function toggle(obj) {
	var el = document.getElementById(obj);
	if ( != 'none' ) { = 'none';
	else { = '';


As far as I know, Jeremy Keith sort of came up with this idea even though one would have thought this too would be a DOM core method. But just like getElementsByClass, it isn’t. So rather than pulling the function straight out of the book, I’ll leave that up to you to buy it yourself. Instead I’ve pulled this simple method from public domain:


function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);


This too is very sad that this isn’t part of the DOM core functionality. But hey, it makes for fun references like this! This function however isn’t quite a function; it’s a prototype that extends the DOM Array object. I remember one day thinking to myself “surely I can do this in PHP, it’s gotta be in JavaScript.” Well, this extension makes it work just like you’d expect if you’re a PHP developer. Here is a version from EmbiMEDIA


Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
	return false;


I honestly don’t know what I would do without these guys. I hate the DOM implementations of setting cookies in JavaScript. In PHP it’s so easy, and it’s easy for one main reason, they work just like the functions below. All three of these functions were found to be public domain and free to use.


function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		( ( path ) ? ';path=' + path : '' ) +
		( ( domain ) ? ';domain=' + domain : '' ) +
		( ( secure ) ? ';secure' : '' );

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';


This function straight up kicks so much ass. First of all, just look at it.


function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (arguments.length == 1)
			return element;
	return elements;

// Sample Usage:
var obj1 = document.getElementById('element1');
var obj2 = document.getElementById('element2');
function alertElements() {
  var i;
  var elements = $('a','b','c',obj1,obj2,'d','e');
  for ( i=0;i

Tell me that’s not beautiful! Short not only by name, but by reference. It not only takes in strings, it takes objects too. You can pass it one argument, or pass it many! This by far is my favorite function of all time which will provide years and years of handiness.

Source is taken from:

Using Bookmark in Visual Studio Wednesday, Sep 29 2010 


As the name suggests, bookmarking speedup your code navigation in Visual Studio. There may be some portion of code where we need to move very frequently. Generally we scroll the page and move to that section, but Visual studio provides great features by which we can move to a particular section very quickly using some shortcut keys. This is called Bookmarking of Code.
Below are the set of Icons which are used to navigate the code using Bookmark.


How To Use

We can place the bookmark by clicking on Bookmark icon or using keys Ctrl + K, Ctrl + K. Below is the sample code where I have put two bookmarks in different sections of code.


Now we can easily navigate among those breakpoints using Ctrl + K, Ctrl + N for Next Bookmark and Ctrl + K , Ctrl + p for Previous mark. We can achieve the same using the following toolbar icon.


This is very much easy to use and it gives you very fast navigation throughout the code.

Using Bookmark Window

Visual Studio provides you a Bookmark window where you can get a list of all bookmarked sections.


Now, by selecting a particular bookmark from the Bookmarks list, we can easily move to the particular section.


Renaming BookMarks

For easy reference, we can also rename bookmark so that we can easily identify them. This helps us to easily move to a particular code block based on the name given. This is useful when we are having many bookmarks in the bookmark list.


As I have renamed my bookmark list as below:



This may not be new to many of us, but it may helpful for some beginners. Using this feature, we can navigate our code very easily. Please provide your valuable suggestions and feedback.

Source is taken from:

What does the character ‘~’ mean in ASP.NET applications? Wednesday, Sep 29 2010 

The character tilde (~) in the ASP.NET paths points to the root of the web application.

Web developers are familiar with using relative paths for all links, including hyperlinks, images and style sheets to be able to move around web pages collectively.

In ASP.NET when using User controls the relative paths can be difficult to use. The typical solution to this is to use web-root absolute paths instead here, such as ’~/UserControl1.ascx’, resulting in the hard-coded sub-directories that are common on ASP.NET sites.

The correct solution to this problem is to use app-relative paths instead, which ASP.NET nicely makes possible through the use of the tilde (~) prefix. Instead of <a href=”/UC/Page.aspx”>, use <a id=”A1″ href=”~/Page.aspx”runat=”server”>. The same ~ notation works for images also, as long as you add runat=”server”. There is also a ResolveUrl method that allows you to use ~ in your own code, which is one possible way to get stylesheet paths app-relative.

For more information about ASP.NET Web Site Paths, please see:

How to speed up your ASP.NET pages? Wednesday, Sep 29 2010 

You can improve your ASP.NET application performance using:

  • Use Page.IsPostBack
  • Use SQL Server Stored Procedures for Data Access
  • the HttpServerUtility.Transfer method
  • Save View State Only When Necessary.
  • Don’t Rely on Exceptions.
  • Restrict Use of Session State.
  • Limit ASP.NET Server Controls
  • Precompile Your Apps
  • Use ASP.NET Caching

For more information, please refer to: Speed Up Your ASP.NET Pages and Developing High-Performance ASP.NET Applications.

How to insert a special non-ASCII characters into a database? Wednesday, Sep 29 2010 

When you try to insert a special non-ASCII characters into a database, such as ‘Poor’s’, you find that they can’t be inserted, by using “INSERT INTO table VALUES(1,’Poor’s’)”, only “Poora€?s” can be inserted.

You can insert the value as parameter into the database.

     string ConStr = @"your connection string";
        string InsertQuery = "INSERT INTO table VALUES (1,@name)";
        SqlConnection InsertCon = new SqlConnection(ConStr);
        SqlCommand InsertCmd = new SqlCommand(InsertQuery, InsertCon);
            InsertCmd.Parameters.Add(new SqlParameter("@name", SqlDbType.NVarChar,200));
            InsertCmd.Parameters["@name"].Value = Server.HtmlEncode(TextBox1.Text); 

        catch (Exception Ex)

        string QueryCon = "SELECT name FROM table where ID=1";
        SqlConnection NorthWindCon = new SqlConnection(ConStr);
        SqlDataAdapter NorthWindDa = new SqlDataAdapter(QueryCon, ConStr);
        DataSet Ds = new DataSet();
        NorthWindDa.Fill(Ds, "table");

        string Dv = Ds.Tables["table"].Rows[0][0].ToString();

In fact, Server.HtmlEncode is not what you want. it is converting the string into html code so that it’ll not conflict with sql statement. Such as the quotation mark. In your scenario, “™” won’t be converted into anything in HTML. so it can be fine without Server.HtmlEncode. Using parameter is what you need. However, use them both will be better.

Using this approach also prevents potential SQL injection attacks.

Related thread:

How to check if the users are online or offline? Wednesday, Sep 29 2010 

Many developers tend to use ‘Session_End’ event to mark a user as ‘Offline’, but this may not be a good idea, because there are no one-to-one mappings between an ASP.Net session and a user. For example if a user opens 2 separate instances of Internet Explorer (e.g. 2 separate IE processes) on his workstation, he can have 2 ASP.Net sessions open. The ‘Session_End’ event of one of the session does not necessarily mean that the user is offline, they can still be using the website.

In addition, ‘Session_End’ event is only available in the ‘InProc’ session mode. If you are trying to store session states in the State Server or SQL Server, ‘Session_End’ event, it will never fire.

I would suggest using the last visiting time as the ideal approach.

Membership helps build the user database and there is a convenient approach to get it viaMembership.GetUser(string userName).IsOnline.

If you don’t use Membership, you can use the method below which uses the same principle in Membership:

1. In the application, you can define a global dictionary membershipDictionary to store the information about users online and offline.

2. Use an AJAX Timer (or simply XmlHttpRequest in client side JavaScript) in the pages to update theLastVisitTime of the user and store it into membershipDictionary at intervals.

3. From time to time, visit the dictionary membershipDictionary to filter out the idle users (who have not visited the page for a long time) and also retrieve information on how many users are still online.  Regular maintenance can be done in a separate thread or a server-based timer. Please also be aware of thread synchronization issues.

Related thread:

Beginner’s Guide To ASP.NET Cookies Wednesday, Sep 29 2010 

Following are some more articles  for the Beginner’s

Cookies, Session, and Application Object are in Queue. Now, It’s time for reading about cookies. I have spend a lots of times to prepared this article. And you will be very surprised to know that Introduction part is the last topic which I am writing before posting article. I have read many articles, books before writing this article. Done some hands on also. Hope I have explained this well , and hope you people also like it. Please give your suggestion and feedback.

Cookies are the small files that are created on the client’s system or client browser memory (if temporary). Its use for State management that I have already discuss on my view state article.  So we can store small piece of information in a client system and we can use it when we needed. Most interesting thing is that Its works transparently with the user. It can be easily used any where of you web application.  Cookies store information in a plain text format. If any web application using cookies, Server  send  cookies and client browser will store it. The browser then returns the cookie to the server at the  next time the page is requested. The most common example  of using  a cookie is to store  User information, User  preferences , Password Remember Option etc. Cookies has many advantages and disadvantages. I will comes to this points , but first  have a look how cookies are started.

When client request to the server, server send the cookies into client . The same cookies can be referred for subsequent request. As for example, stores session id as a cookies, when any client hits first times on the server, server generates the session id and send it as a cookies to client. [As given in Fig 1.0]


Fig 1.0 : Initial state of cookie creation

Now for all other subsequent from the same client it uses the session-id from cookies, just like the picture below:


Fig 1.1 : Subsequent request for other pages

Browser and web server are responsible for exchange cookies information. For different sites, browser keeps cookies differently. If any pages need information from cookies, when that URL is being hit, first its search for local system for cookies information then its moved to server with that information.

Following are main advantages of using cookies in web application:

  • It’s very simple to use and implement.
  • Browser’s taking care send data.
  • For multiple sites cookies, Browser automatically arranges them.

Main disadvantages of cookies are:

  • Its store data in a simple text format. so it’s not secure at all.
  • There is a size limit of cookies data ( 4096 bytes / 4KB).
  • Number if cookies also limited. Most Browser provides limits of storing cookies is 20. If new cookies came, it will discard the old one. Some of browser support up to 300.
  • We need to configure browser. It will not work on a high security configuration of browser. [I have explained about this in details.]

For working with cookies we need to use namespace System.web


Now , have a look, on the code , that how can we create a cookies and add it with web response .3


The cookies which has been created will persist , until browser has been closed.  we can persist the cookies. But how? Just after few point I have discussed it.

Now , its times to retrieve data from cookies.  Ok, before reading cookies, first of all we need to check whether a cookies was found or not. “Its always good practice to check cookie before read it, because is browser is disable cookies.


We can classified  cookies in two way,

  • Persistent Cookies
  • Non Persistent Cookies

Persistent Cookies : This can be called as permanent cookies, which is  stored in client  hard-drive until it expires . persistent cookies should have set with expiration dates. Sometimes its stays  until the user deletes the cookie. Persistent cookies are used to collect identifying information about the user from that system. I have discuss about the creation of persistent cookies on  “How to make Persist Cookies ?”  section.

Non Persistent Cookies : This can be called as Temporary Cookies. If there is no expires time  defined then the cookie is  stored in browser memory . The Example which I have given already its a Non-Persistent Cookies.

Therefore there is no difference between modifying persistent or non-persistent cookies.  Only difference between them are Persistent cookies should have an Expatriation time defined within it.

I have already given an example of non-persistent cookies, For Persistent cookies we need only add to expiry times of cookies.  In that given code I have added Expire time to 5 days. Just check the example.

        //Creting a Cookie Object
        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");

       //Setting values inside it
        _userInfoCookies["UserName"] = "Abhijit";
        _userInfoCookies["UserColor"] = "Red";
        _userInfoCookies["Expire"] = "5 Days";

        //Adding Expire Time of cookies
         _userInfoCookies.Expires = DateTime.Now.AddDays(5);

        //Adding cookies to current web response

Now , Looks the most interesting things that where they are store in hard drive.

This is one of the interesting things to find out the cookies in your local drive. First of all, From “Explorer Folder Option “, Select, show hidden files and folder.


Fig 1.2 : Show Hidden files and Folder Settings

Now Browse into document & settings of the current user and  open the cookies folder. Now looks the picture.


Fig 1.3 : Reading Cooking info in local System

This is also a funny task. If you want to remove some persistent cookies before its Expiration date, the only way to replacing the cookies with some before expiration date.

        HttpCookie _userInfoCookies = new HttpCookie("UserInfo");
        //Adding Expire Time of cookies before existing cookies time
        _userInfoCookies.Expires = DateTime.Now.AddDays(-1);
        //Adding cookies to current web response

We can controlling the scope of cookies by following way

  • Limiting Cookies to Path
  • Limiting Cookies Domain

By Default ASP.Net uses cookies to stores session ID’s , but I have already discuss some browser does not support cookies, To over comes this problem, ASP.NET uses "Cookie Munging" to manages session variable with out cookies.

[Though this is also related with Session, I am just giving a Basic overview. I will explain it in details on my Next article which will be on session.]

There are some specific reason to use cookie munging in ASP.NET

  • Some Browser does not support cookies.
  • Sometimes, user disable cookies in Browser.

When user request for a page on a server, Server  encoded the session id and add it with every  href  link  in page. When user click any links ASP.NET decodes that session id and passes it the page that user requesting. Now the requesting page can retrieve any session variable. This all happens automatically, if ASP.NET detects that the users browser does not support cookies.


Fig 1.4 : Steps of Cookie Munging

For that we have to make session state to Cookie less.

<sessionState cookieless= "true />

Ooo… Now I am stopping here on this topic. I will explain it in details when I write an article of Session.

How to Configure cookies in Browser ?

Now, we can just have a look on how can we configure browser for enabled /Disabled cookies.  Here I have discussed about settings of IE Browser.  Click on Tool -> Internet Option -> Go To Privacy Tab. There you will able to see a scroll bar, with following options

  • Accept All Cookies
  • Low
  • Medium
  • Medium High
  • Block All Cookies

First option will Accepts All cookies and Last Option Will block all cookies. you can get the details of those settings while scrolling the bar.


There are many  topics to learn with cookies . I have covered a small portion hope this will helps all the beginners to startup. Please give your feedback and suggestion.


Exploring Session in ASP.Net Wednesday, Sep 29 2010 


First of all I would like to thank all the readers who read and vote for my article. In Beginner’s Guide series, I have written some articles on state management. Probably this is my last article on state management. Now coming back to the topic of this article “Exploring Session in ASP.Net” . This article will give you a very good understanding of session. In this article I have covered basic of session, different types of storing session object, Session behavior in web farm scenarios , Session on Load Balancer etc. I have also explained details of Session Behavior in a Live production environment. Hope you will enjoy this article and provide your valuable suggestion and feedback.

What is Session ?

Web is Stateless, which means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, it can’t hold the client information on page. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information. So what we need? we need to store information. Session provides that facility to store information on server memory. It can support any type of object to store along with our custom object. For every client Session data store separately, means session data is stored as per client basis. Have a look at the following diagram.


Fig : For every client session data store separately

State Management using session is one of the best features, because it is secure, transparent from users and we can store any kind of object with in it. Along with advantages, some times session can causes performance issue for heavy traffic sites because its stored on server memory and clients read data from the server itself. Now lets have a look at the advantages and disadvantages of using session in our web application.

Advantages and Disadvantages of Session ?

Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages :

  1. It helps to maintain user states and data to all over the application.
  2. It can easily be implemented and we can store any kind of object.
  3. Stores every client data separately.
  4. Session is secure and transparent from user.

Disadvantages :

  1. Performance overhead in case of large volume of user, because of session data stored in server memory.
  2. Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Besides these, there are many advantages and disadvantages of session that are based of session Types. I have Discussed all of them.

Storing and Retrieving values from Session

Storing and Retrieving values in session are quite similar with ViewState. We can interact with Session State with System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.

Following code is used for storing a value to session

//Storing UserName in Session
Session[“UserName”] = txtUser.Text;
Now, let see how we can retrieve values from Session

//Check weather session variable null or not
if (Session[“UserName”] != null)
//Retrieving UserName from Session
lblWelcome.Text = “Welcome : ” + Session[“UserName”];
//Do Something else
we can also store some other object in Session. Following Example shows how to store a DataSet in session.

//Storing dataset on Session
Session[“DataSet”] = _objDataSet;
and following code shows how we can retrieve that dataset from the session

//Check weather session variable null or not
if (Session[“DataSet”] != null)
//Retrieving UserName from Session
DataSet _MyDs = (DataSet)Session[“DataSet”];
//Do Something else
Ref & for more Information: Read Session Variable Section

Session ID

Asp.Net use 120 bit identifier to track each session. This is secure enough and can’t be reverse engineered. When client communicate with server, only session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data. This is done in following steps,

  • Client hits web site and some information is stored in session.
  • Server creates a unique session ID for that clients and stored in Session State Provider .
  • Again client request For some information with that unique session ID from Server.
  • Server,looks on Session Providers, and retrieve the serialized data from state server and type cast the object .

Just have a look on the pictorial flow,

Fig : Communication of Client, web server, and State Provider

Ref. & for more Information: SessionID in MSDN

Session Mode and State Provider

In ASP.NET there are following session mode available,

  • InProc
  • StateServer
  • SQLServer
  • Custom

For every session State, there is Session Provider. Following diagram will show you how they are related.

Fig : Session State Architecture

we can choose the session State Provider based on which session state we are selecting. When ASP.NET request for any information based on session ID, session state and its corresponding provider are responsible for sending the proper information based on user. Following tables show, the session mode along with there provider Name.

Session State Mode State Provider
InProc In-Memory Object
StateServer Aspnet_state.exe
SQLServer DataBase
Custom CustomProvider

apart from that, there is another mode, “Off”. If we select this option the session will be disabled for the application. But our objective is to use session, so we will look into that four session State Mode.

Ref. & for more Information: Session State Providers

Session States

If we consider about session state, It means all the settings that you have made for your web application for maintaining the session. Session State, it self is a big thing, It says all about your session configuration, Either in web.config or from code behind. In web.config, elements used for setting the configuration of session. Some of them are Mode, Timeout, StateConnectionString, Custom provider etc. I have discussed about each and ever section of connection string. Before I discussed Session Mode, just take a brief overview of Session Event

Session Event

There are two types of session events available in

  • Session_Start
  • Session_End

you can handle both this event in global.asax file of your web application. When a new session initiate session_start event raised and Session_End event raised when a session is abandoned or expired.

void Session_Start(object sender, EventArgs e)

// Code that runs when a new session is started


void Session_End(object sender, EventArgs e)
// Code that runs when a session ends.

Ref. and for more Information : Application and Session Events

Session Mode

I have already discussed about the session mode in ASP.NET, Following are the different types of session modes available in ASP.Net.

  • Off
  • InProc
  • StateServer
  • SQLServer
  • Custom

If we set Session Mode=”off” in web.config, Session will be disabled to all over the application. For this we need to configure web.config in following way

InPorc Session Mode :

This is the default session mode in Asp.Net. Its stores session Information in Current Application Domain. This is the best session mode which is based on web application Performance. But main disadvantage is that, It will lose the data if we restart the server. There are some more advantages and disadvantages of InProc session mode. I will come to those points again .

Overview of InProc Session Mode :

As I have already discussed InProc mode session data will be stored on the current application domain. So It is easily and quickly available.

So, InProc session mode store its session data in a memory object on that application domain. This is handled by worker process in application pool. So If we restart the server we will lose the session data. If Client request for the data , state provide read the data from In-Memory Object and return it to the client. In web.config we have to mention Session mode and also we have to set the Timeout.


This Session TimeOut Setting keeps session alive for 30 minute. This can be configurable from Code behind too.


There are two type of session events available in Session_Start() and Session_End. It is the only mode that supports the Session_End() event. These events will call after the session timeout period is over. The general flow for the InProc Session State is some thing like this.

Now, when the Session_End() will call that depends on Session Time Out. This is a very fast mechanism because no serialization occurs for storing and retrieving data, and data are staying inside the same application domain.

When Should we use InProc Session Mode ?

InProc is the default session mode. It can be very helpful for a small web sites and where the number of user are very less, We should avoid InProc in case of Web Garden (I will come to this topic in details) Scenario .

Advantages and Disadvantages

Advantages :

  1. It store Session data in memory object of current application domain. So accessing data is very fast and data is easily available.
  2. There is not requirements of serialization to store data in InProc Session Mode.
  3. Implementation is very easy, just similar to using View State.

Disadvantages :

  1. although InProc Session is fastest, common and default mechanism, It has lots of limitation.
  2. If the worker Process or application domain recycles all session data will be lost.
  3. Though its fastest, but more session data and more users can affects performance, because of memory.
  4. we can’t use it in web Garden scenarios .
  5. This session mode is not suitable for web farm scenarios also.

So as per above discussion, we can conclude InProc is very fast session storing mechanism but suitable for small web application. InProc Session Data will get lost if we Restart the server, application domain recycles It is also not suitable for Web Farm and Web Garden Scenarios.

Now have a look that what are the other option available to overcome these problem. First Come to StateServer Mode.

StateServer Session Mode :

Overview of StateServer Session Mode :

This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Services, which is Independent to IIS and can also run on a separate server. This session state is totally managed by aspnet_state.exe. This server may runs on the same system, but it’s out side of that main application domain where your web application is running. This allow if you restart your process restarted your session data will be alive. This approaches has several disadvantages due to the overhead of serialization and de-serialization, its also increases the cost of data access because of every time when user retrieves session data, our application hits a different process.

Configuration for StateServer Session Mode

In StateServer the Session data is stored in a separate Server which is Independent to IIS and Its handled by aspnet_state.exe. This process is run as windows Services. you can start this service from windows MMC or from command prompt.

By default “Startup Type” of ASP.NET state service is set to manual, we have to set it as “Automatic” startup type.

from command from just typing “net start aspnet_state”. By default this services listen TCP Port 42424 , but we can change the port from registry editor as given in below picture .

Now have a look on the web.config configuration for StateServer Setting. For State Server Setting we need have to specify the stateConnectionString. This will identify the system that is running state server. By default stateConnectionString used ip as (localhost) and Port 42424.


When we are using StateServer, we can configure stateNetworkTimeOut attributes to specify the maximum number of seconds to wait for the service to respond before canceling the request. Default time is 10 seconds.


For using StateServer, the object which we are going to store that should be serialized and at the time of retrieving we need to De-Serialize. I have described it with an Example.

How StateServer Session Mode Works?

We used StateServer Session Mode to avoid unnecessary session data loss during restart of web Server. StateServer is maintained by process aspnet_state.exe as a windows Services. This process maintains the all the session data. But need to serialize the data before storing it in StateServer Session Mode.

As shown in above figure, that client request to the web server, then web server stores the session data on state server. StateServer may be the current system or may be the different system. But it is totally independent of IIS. Destination of StateServer will depend on the web.config stateConnectionString attribute settings. If we set it as, It will store data on that local system itself. For change the StateServer destination, we need to change the IP. and make sure, aspnet_state.exe is up and running on that system. other wise you will get the following exception while trying to store data on session.

When we are storing any object on session, that should be serialized. That data will be stored to StateServer system using State Provider. and at the time of retrieving the data, State provider will return the data. The complete flow is given in the below picture.

Example Of StateServer Session Mode :

Here is one simple example of using StateServer Session mode. I have created this sample web application directly on the IIS so that we can easily understand its usage.

Step 1 : Open Visual Studio > File > New > Web Sites . Choose Location as HTTP and create the web application .

Now if you open the IIS you will see a Virtual Directory created with the name of your web application , as in my case it is StateServer.

Step 2 : Create s simple UI that will take Roll No and Name of a student . We will store the name and roll in a state server session. I have also create one same class “StudentInfo” . This class is given below


public class StudentInfo
//Default Constructor
public StudentInfo()

/// Create object of student Class
Int RollNumber ///
String Name public StudentInfo(int intRoll, string strName)
this.Roll = intRoll;
this.Name = strName;

private int intRoll;
private string strName;
public int Roll
return intRoll;
intRoll = value;

public string Name
return strName;
strName = value;
Now , have a look on the code behind code. I have just added two button one for storing session and another for retrieving session.

protected void btnSubmit_Click(object sender, EventArgs e)

StudentInfo _objStudentInfo = new StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);
Session[“objStudentInfo”] = _objStudentInfo;
protected void btnRestore_Click(object sender, EventArgs e)
StudentInfo _objStudentInfo = (StudentInfo) Session[“objStudentInfo”];
txtRoll.Text = _objStudentInfo.Roll.ToString();
txtUserName.Text = _objStudentInfo.Name;


Step 3 : Please Configure your web.config for state server. As I have already discussed. And Please make sure aspnet_state.exe is up and running on that configured server.

Step 4 : Run the Application

Enter the data, Click on Submit.

Now there are following Test that I have made which will totally clear your doubts that how exactly StateServer is useful.

First :Remove the [ Serializable ] key word from the studentinfo class and try to run the application. When you will click on Submit Button you will get following error

Which clearly says that you should have to serialize the object before store.

Second: Run the Application, Store data by clicking on Submit Button. Restart IIS

Now, In case of InProc, you have already lost your session data, But Its StateServer, Click on Restore Session, You will get your original data. Because State server data does not depend on IIS. Its keeps it separately.

Third : Stop the aspnet_state.exe from the Windows Services MMC and Submit the Data. You will get following error,

Because your State Server Process is not running.

So, Please keep in mind about those three points .

Advantages and Disadvantages.

So based on the above discussion

Advantages :

  • Its keeps the data separate from IIS so, any Issue with IIS does not hamper Session data.
  • It is useful in web farm and web garden scenarios.

Disadvantages :

  • Process is slow due to Serialization and De-Serialization
  • State Server always need to be up and running.

Now, I am stopping here on StateServer, You will find some more interesting points on Load balancer, Web Farm, Web Garden Section.

Ref & for more Information:

  1. State Server Session Mode
  2. Asp.Net Session State

SQL Server Session Mode :

Overview of SQL Server Session Mode :

This session mode provide us more secure and reliable Session management in In this session mode, the Session data is serialized and stored in the SQL Server database. Main disadvantages of this session storage methods is overhead related with Data Serialization and De-Serialization. It is the best option for using in the web farms.

To setup SQL Server we need to take help of two sql Script.

  • For Installing: InstallSqlState.sql
  • For Un-Installing: UninstallSQLState.sql

The most easiest way to configure SQL Server, is using aspnet_regsql command.

I have explained the detailed use of these file in configuration section. This is the most useful state management in the web farm scenario.

When should we use SQL Server Session Mode ?

  • SQL Server Session mode is more reliable and secure session state management.
  • Its keeps data in a centralized location (database).
  • We should use SQL server session mode when we need to implement Session with some more security.
  • If there happens to be frequent server Restart we can implement SQL server.
  • This is perfect mode that fits in web farm and web garden scenarios (I have explained in details later) .
  • we can use SQL server Session mode when we need to share session between two different application .

Configuration for SQL Server Session Mode

In SQL Server  Session mode, we are storing session data in a SQL Server, so we need to first provide the database connection string in web.config .sqlConnectionString attribute is used to provide the connection string in web.config.

After setup the connection string we need to configure the SQL Server. I am explaining how to configure your your SQL server using aspnet_regsqlcommand.

Step 1: From Command prompt, Go to your Framework Version Directory

E.g :c:\windows\\framework\<version>.

Step 2 : Run aspnet_regsql command with following parameters

Have a look on the parameter and there uses

Parameters Description
-ssadd Add support for SQLServer mode session state.
-sstype p P is stands for Persisted. Its persist the session data on server
-S Specify Server Name
-U Specify User Name
-P Specify Password

After run you will get the following message,

that’s all .

Step 3 : Open SQL Server Management Studio, Check, A new database ASPState has been created  and there should be two tables,

  • ASPStateTempApplications
  • ASPStateTempSessions

Now, Just change the configuration string of the State Server Example and Run the same application that  I have explained in State Server.

Just store Roll and User Name and Click on Submit button, and open ASPStateTempSessions Table from SQL Server Management Studio.. WoW… here is your session data,

Now. do the following Test that I have already explained in State Server Mode.

  1. Remove The Serialize Key word from StydentInfo Class
  2. Reset IIS and Click on Restore Session
  3. Stop the SQL Server Services

I think I have explained the SQL Server Session mode well.

Advantages and Disadvantages

Advantages :

  • Session data do not  affected if we restart the IIS.
  • It is the most reliable and secure session management.
  • It keeps data located centrally ,  It can be easily accessible from other application.
  • It is  very useful in web farm and web garden scenarios.

Disadvantages :

  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead  for application.
  • As the session data is handled in different server, so we have to take care of SQL server. It should be always up and running.

Ref & for more Information : Read SQL Server Mode

Custom Session Mode

Overview of Custom Session Mode :

Generally we use either of InProc, StateServer or SQL Server  Session mode for our application, but we also  need to know the fundamental of Custom Session mode. This session mode is quite interesting, because Custom session gives full control to us to create every thing even session ID. you can write your own algorithm to generate session ID.

You can implement custom providers that store session data in other storage mechanisms simply by deriving fromSessionStateStoreProviderBase Class. You can also Generate New Session Id by Implementing ISessionIDManager.

This are the following methods  are called  during  implementation of Custom Session

In Initialize methods we can set the Custom Provider. This will initialize the connection with that specified provider. SetItemExpireCallback used to set SessionTimeOut, we can register any methods that will call at the time of session expire. InitializeRequest is called on every request and CreateNewStoreData used to create a new instance of SessionStateStoreData .

When should we use Custom Session Mode ?

we can use custom session mode in following of the cases,

  • We want to store session data rather than SQL Server.
  • When we have to use some Existing table to store session data.
  • When we need to create our own session ID.

What configuration do we need for it?

We need to configure our web.config like below,

If you want to Explore some thing more please Check Further study section

Advantages and Disadvantages

Advantages :

  • We can use some existing Table for the store session data, It is useful when we have to use some old database rather than SQL Server.
  • It’s not depending on IIS , So Restarting web server does not make any effects on session data.
  • We can crate our own algorithm for generating Session ID.

Disadvantages :

  • Processing of Data is very slow.
  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.

Its always recommended to use any third party provider rather than creating your own.

Ref and More Information : Custom Mode

If you want to know more about details session Mode please Read this MSDN Article

Overview of Production Deployment

Generally Production environments means when we deploy the application on our live production server. This is a major and Big Challenge for the web developer to deploy there application on Live Server. because in a Big production environment there are no of user and its not possible to handle the load of so many users by a single server. Here the concepts came of Web Farm, Load BalancerWeb Garden etc.

Just few month back I have deployed one of our web application In a live production environment which is accessible by  million of user and there were more than 10 Active Directory, more than 10 Web Server Over  Load Balancer and Many DB Server, Exchange  Server, LCS Server etc. If we look at the number of web server, this is multiple. The major risk involves in multiple server is Session Management. Following picture shows the general diagram for a Production environments.

I will try to explain the different scenario that you need to keep in mind while deploying your application.

Application Pool :

This is one of the most important thing that you should create for your own application in Production environment. Application pools used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.

Identity Of Application Pool

Application pool identity configuration is an important aspect of security in IIS 6.0  and IIS 7.0, because it determines the identity of the worker process when the process is accessing resource. This Settings comes from IIS 6.0 In IIS 7.0 there are Three predefine Identity , that are same with IIS 6.0.

Applicationpool Identity Description
LocalSystem LocalSystem is a built-in account that has administrative privileges on the server. It can access both local and remote resources. For any kind accessing of server files or resources we have to set the Identity of application pool to Local System.
LocalServices LocalServices Built-in account has privileges of an authenticated local user account. It does not have any network access permission
NetworkServices This is the default Identity of Application Pool NetworkServices has privileges of authenticated local user account.

Now hope you are familiar with Session, Use of it, how to apply it in web farms etc in ASP.NET 2.0. So as a summary,

  • The In-Process(InProc) Session provider is the fastest method, because  of  everything stored  inside the memory. Session data will be loss if we restart web server  or if Worker Process Recycles. You can use in small web application where number of users are less. Do not use InProc in Web Farm.
  • In StateServer Session modes Session data maintain by aspnet_state.exe. Its keeps session data out of Web server. So any  issue with web server does not affect  session data. You need to Serialized object before storing data  in StateServer Session. we can use it in web farm also.
  • SQLServer Session modes store data in SQL Server, we need to provide the connection string. Here we also need to serialize the data before storing it to session. This is very useful in production environment with web farm mode.
  • we can use Custom provider for custom data source or when we need to use some existing table to store session data. We can also create our custom sessionID in Custom mode. But it is not recommended to create your own custom provider. Its recommended to use any third party provider.

Hope you have enjoyed the article. Please give your suggestion and Feedback for further  improvement. Again Thanks for Reading .

Further Study and Reference

Reference I have already added with different section.  Here I am giving few of the link which will really help you for further study.

Source is taken from:

How to zip a file or a folder using c#? Tuesday, Sep 28 2010 

It can be achieved by using, ICSharpCode.SharpZipLib.Zip or other library assemblies.

You can make use of to deal with zip files:

You can also try SharpZipLib:

This DLL file can be downloaded from:

You can choose the edition you need after downloading. The samples below demonstrate how to zip files.

using ICSharpCode.SharpZipLib.Zip;
using System.IO;

ZipOutputStream zos = null;
protected void Button1_Click(object sender, EventArgs e)
string[] pathCollection = new string[2];
PathCellction[0] = “c:\\folder1”;
PathCellction[1] = “c:\\folder2”;
StartZip(pathCollection, “filename”);

protected void StartZip(string[] pathCollection, string strFileName)
MemoryStream ms;
Response.ContentType = “application/octet-stream”;
strFileName = HttpUtility.UrlEncode(strFileName).Replace(‘+’, ‘ ‘);
Response.AddHeader(“Content-Disposition”, “attachment; filename=” + strFileName + “.zip”);
ms = new MemoryStream();
zos = new ZipOutputStream(ms);

protected void addZipEntry(string[] pathCollection)
for (int i = 0; i < pathCollection.Length; i++)
string strPath = pathCollection[i];
addZipEntry(strPath, strPath.LastIndexOf("\\") + 1);

protected void addZipEntry(string strPath, int baseIndex)
DirectoryInfo di = new DirectoryInfo(strPath);
foreach (DirectoryInfo item in di.GetDirectories())
addZipEntry(item.FullName, baseIndex);
foreach (FileInfo item in di.GetFiles())
FileStream fs = File.OpenRead(item.FullName);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
string strEntryName = item.FullName.Remove(0, baseIndex);
ZipEntry entry = new ZipEntry(strEntryName);
zos.Write(buffer, 0, buffer.Length);


How to download files using C#? Tuesday, Sep 28 2010 

Please check the sample code below, the page ‘link.aspx’ lists all of the files available in a folder, when clicking the hyperlinks in ‘link.aspx’, the user can download the files via ‘downloading.aspx’.


using System.IO;

protected void Page_Load(object sender, EventArgs e)
DirectoryInfo di = new DirectoryInfo(Server.MapPath(“~/downloadstuff”));
int i = 0;
foreach(FileInfo fi in di.GetFiles())
HyperLink HL = new HyperLink();
HL.ID = “HyperLink” + i++;
HL.Text = fi.Name;
HL.NavigateUrl = “downloading.aspx?file=”+fi.Name;
Page.Controls.Add(new LiteralControl(“<br/>”));

using System.IO;
using System.Threading;

protected void Page_Load(object sender, EventArgs e)
string filename = Request[“file”].ToString();
fileDownload(filename, Server.MapPath(“~/downloadstuff/”+filename));

private void fileDownload(string fileName, string fileUrl)
bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
if (!success)
Response.Write(“Downloading Error!”);

public bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullUrl, long _speed)
FileStream myFile = new FileStream(_fullUrl, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
_Response.AddHeader(“Accept-Ranges”, “bytes”);
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers[“Range”] != null)
_Response.StatusCode = 206;
string[] range = _Request.Headers[“Range”].Split(new char[] { ‘=’, ‘-‘ });
startBytes = Convert.ToInt64(range[1]);
_Response.AddHeader(“Content-Length”, (fileLength – startBytes).ToString());
if (startBytes != 0)
_Response.AddHeader(“Content-Range”, string.Format(” bytes {0}-{1}/{2}”, startBytes, fileLength – 1, fileLength));
_Response.AddHeader(“Connection”, “Keep-Alive”);
_Response.ContentType = “application/octet-stream”;
_Response.AddHeader(“Content-Disposition”, “attachment;filename=”
+ HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength – startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
if (_Response.IsClientConnected)
i = maxCount;
return false;
return false;
return true;

Related thread:


Next Page »