We have all seen many websites dislaying the number of online users. In this article, we will learn how to display the number of online users in an ASP.NET Web Application / Website.
Procedure
Let's begin.
- Go to File -> New -> Website then select ASP.NET Empty Web Site
- Right-click on the Website Project (in Solution Explorer) then select Add then click on Add New Item
- Select Global Application Class (Global.asax) then click on the Add Button
You will see various events in the Global.asax file, for example Application_Start, Application_End and so onThe . Application_Start event is called once when the application starts. The Session_Start event is called every time a new session is started. The Session_End event is called when a user session ends. In the Application_Start event, we will initialize our Application state variable.
<%@ Application Language = "C#" %>
< script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["TotalOnlineUsers"] = 0;
}
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
Application.Lock();
Application["TotalOnlineUsers"] = (int)Application["TotalOnlineUsers"] + 1;
Application.UnLock();
}
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.
Application.Lock();
Application["TotalOnlineUsers"] = (int)Application["TotalOnlineUsers"] - 1;
Application.UnLock();
}
</script>
In the Web.config file, add SessionState within the system.web element. By default the session uses Cookies (cookieless="false") and the default timeout period is 20 minutes.
<system.web>
<sessionState mode = "InProc" cookieless="false" timeout="20"></sessionState>
</system.web>
Now add a Webform and drop a label control from the Toolbox.
Default.aspx Code:
<form id = "form1" runat="server">
<div>
<p>No.of Online Users:<asp:Label ID = "Label1" runat="server" Text="Label" ForeColor="#CC0000"></asp:Label></p>
</div>
</form>
Default.aspx.cs Code:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Application["TotalOnlineUsers"].ToString();
}
No comments:
Post a Comment