Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Asp.net application state real time example - Part 68

Suggested Videos
Part 65 - StateServer asp.net session state mode management
Part 66 - SQLServer asp.net session state mode management
Part 67 - Asp.net Application state

In this video we will discuss about a real time example, where we can use application state variables. 

Application state variables are global, and all sessions have access to them. So, these variables can be used to track the number of users online. Every time a new user connects to your application, we want to increase the number of users online by 1. Along, the same lines, when ever a user session ends, then we need to decrease the number of users online by 1. But how do we know, when a new user connects to our application. Session_Start() event is fired when ever a new session is established. When the session ends, Session_End() event is fired. The event handlers are in global.asax file.



Global.asax code:
public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs when the application starts
        Application["UsersOnline"] = 0;
    }
    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new user session is started
        Application.Lock();
        Application["UsersOnline"] = (int)Application["UsersOnline"] + 1;
        Application.UnLock();
    }
    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when an existing user session ends. 
        Application.Lock();
        Application["UsersOnline"] = (int)Application["UsersOnline"] - 1;
        Application.UnLock();
    }
}



The application state variable is accessible across the entire application. Copy and paste the following code in the Page_Load() event of any webform.
if (Application["UsersOnline"] != null)
{
    Response.Write("Number of Users Online = " +
        Application["UsersOnline"].ToString());
}

By default, the browser instances share the session cookie. To have a new session id assigned, when a new browser instance requests the webform, set cookieless="true" for the sessionstate element in web.config. Now run the application. The following message should be displayed.
Number of Users Online = 1

Open a new browser window, copy and paste the URL from the other window. Make sure to delete the session-id, so the web server, assigns a new session-id to the second request. At this point, Number of Users Online should be incremented to 2.

No comments:

Post a Comment

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