Events in the life cycle of a web application - Part 4

In a web application, events can occur at 3 levels
1. At the Application Level(Example: Application Start)
2. At the Page Level(Example: Page Load)
3. At the Control Level (Example: Button Click)

In this video, we will learn about Application Level events. Before understanding Application level events, lets talk about Session State and Application State variables. In Part 3 of this video series we have learnt about ViewState. ViewState variables are used to preserve data across page post back. By default, ViewState of one webform is not available in another webform.

For example, if you define ViewState["MyData"] = "View State 
Example" in WebForm1. ViewState["MyData"] is only available in WebForm1. ViewState["MyData"] will be null on any other web form in the application.

If you want to make your data available on multiple web forms, there are several techniques in ASP.NET, as listed below.
1. Query Strings
2. Cookies
3. Session State 
4. Application State

We will discuss about Query Strings and Cookies in a later video. 

Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.

Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.

In an ASP.NET web application, Global.asax file conatins the application level events. 
void Application_Start(object sender, EventArgs e)
{
    // Code that runs on application startup
}

void Application_End(object sender, EventArgs e)
{
    //  Code that runs on application shutdown
}

void Application_Error(object sender, EventArgs e)
{
    // Code that runs when an unhandled error occurs
}

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. 
    // Note: The Session_End event is raised only when the sessionstate mode
    // is set to InProc in the Web.config file. If session mode is set to StateServer 
    // or SQLServer, the event is not raised.
}



In general, Application events are used to initialize data that needs to be available to all the current sessions of the application. Where as Session events are used to initialize data that needs to be available only for a given individual session, but not between multiple sessions.

Now, let's write a simple application, using session and application level events. Create a new asp.net web application, and copy paste the following code in Global.asax file.
1. Application_Start() event gets fired, when a first request is made, and if the application is not already running. 
2. Session_Start() event is fired every time a new browser instance, with a different session-id, visits the application.
3. Session_End() event is fired when the user session times out. The default is 20 minutes. This can be configured in the web.config file.
void Application_Start(object sender, EventArgs e)
{
    // Create Application state variables
    Application["TotalApplications"] = 0;
    Application["TotalUserSessions"] = 0;
    // Increment TotalApplications by 1
    Application["TotalApplications"] = (int)Application["TotalApplications"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
    // Increment TotalUserSessions by 1
    Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] + 1;
}
void Session_End(object sender, EventArgs e)
{
    // Decrement TotalUserSessions by 1
    Application["TotalUserSessions"] = (int)Application["TotalUserSessions"] - 1;
}

Copy and paste the following code in WebForm1.aspx.
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("Number of Applications: " + Application["TotalApplications"]);
    Response.Write("<br/>");
    Response.Write("Number of Users Online: " + Application["TotalUserSessions"]);
}



Now, when you run the application, you get the following output:
Number of Applications: 1
Number of Users Online: 1

Copy the URL and open a new instance of the browser. Paste the URL and press enter. In the new instance of the browser, we still see the same output. 

We expected the Number of Users Online to be 2. The new instance of the browser, is treated as part of the same session, because, by default the browser uses cookies to store session id. The session id is read from the same cookie when you opened the new browser window. Hence, Number of Users Online is not incremented.

How to get a new session-id and force the Session_Start() event to execute?
1. Close the browser: Close the existing browser window, which automatically deletes the session cookie. Now, open a new brwoser instance. Since, the existing session cookie associated with the previous browser instance is deleted. The new instance of the browser, will get a new session-id and a session cookie.Now, if you navigate to WebForm1.aspx, Session_Start() event gets fired and Number of Users Online is incremented to 2.

2. Open a new instance of a different browser: For example, if you first visited the application with Google Chrome, now try accessing the same page with internet explorer, Session_Start() event gets fired and Number of Users Online is incremented to 2.

3. Use Cookie-less Sessions: To use cookie-less sessions set the cookieless attribute to true in web.config as shown below.
<sessionState mode="InProc" cookieless="false"></sessionState>

What is a Session, in a web application?
A session is a unique instance of the browser. A single user can have multiple sessions, by visiting your application, with multiple instances of the browser running with a different session-id on his machine.

17 comments:

  1. it's very use full videos and u have a great job. thanks venkat. please tell me how to implement a Real time project as company standareds and master pages in asp.net

    ReplyDelete
  2. in my web.config, there is no session tag , which as video says
    ??

    ReplyDelete
  3. Hello.. sir..
    here sessionState mode="InProc" what it means???

    ReplyDelete
  4. Hello Sir,

    just help me, where should i paste the code of application and session events. and how webform1.aspx is connected with global.aspx in your code, if there no need of connection then how to get correct answer

    ReplyDelete
  5. Hi Venkat,
    just one question. In Application_Start method you create the TotalApplications state variable with the initial value equals to 0. After that its value is increased by 1. I suppose that the first assignment have to be done only once, when the variable is created, therefore I thought to add the if condition like this:
    if (Application["TotalApplications"] == null) Application["TotalApplications"] = 0;
    Is it correct?

    ReplyDelete

  6. I couldnot get this tag in my web.config file.. and What is here Inproc...
    Sir .. I too live near marathali. Are u assciated with Pragim Tech

    ReplyDelete
  7. What if I open a browser window e.g.Chrome, and without closing that open a new browser window(Chrome) again. Will it have the same session id?

    ReplyDelete
  8. hello. i dont understand, when open app online user show n when eit app again show n ,why dont show n-1 ????

    ReplyDelete
  9. What about cache variables what category do they belong and where are session ids located in my server how can I find them and can I removed them if so how can I remove them by myself manually ?

    ReplyDelete
  10. Great job, i follow your tutorials :)

    ReplyDelete
  11. When we close the browser, and open a new one, won't the session end there, and when we open a new browser window, ain't the "Application["TotalUserSessions"]" value supposed be 1? Please correct me if I am wrong.

    ReplyDelete
    Replies
    1. Yes...Application["TotalUserSessions"] value supposed to be 1.Because when you close your browser ,the cookie is automatically deleted of that browser instance,when you open another instance of the browser new session-id will generate.

      Delete
    2. Yes, session will end there and this also automatically deletes the session cookie. When you a open new browser instance after closing the previous one then a new session id will be assigned to that instance and Application["TotalUserSessions"] valu will be 2.

      Delete
  12. that session in process here u can set the cookieless is either true or false where true gives you to use cookieless session and
    false false gives you cookies.

    ReplyDelete
  13. The best Web Forms tutorial in the world !

    ReplyDelete

It would be great if you can help share these free resources