Mega Code Archive

 
Categories / ASP.Net Tutorial / Sessions
 

Session counter and application counter (C#)

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs"  Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">     <title>Chapter 8: Counter</title> </head> <body>     <form id="form1" runat="server">     <div>         <asp:Label ID="lblSessionClicks" runat="server"></asp:Label><br />         <br />         <asp:Label ID="lblApplicationClicks" runat="server"></asp:Label><br />         <br />         <asp:Button ID="btnPost" runat="server" OnClick="btnPost_Click" Text="Post" />&nbsp;</div>     </form> </body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page  {     int sessionCount;     protected void Page_Load(object sender, EventArgs e)     {         if (Session["Count"] == null)         {             sessionCount = 0;         }         else         {             sessionCount = Convert.ToInt32(Session["Count"]);         }     }     protected void btnPost_Click(object sender, EventArgs e)     {         sessionCount++;         Session["Count"] = sessionCount;         lblSessionClicks.Text = "You have clicked the button " + sessionCount + " times.";         Application.Lock();         int applicationCount = Convert.ToInt32(Application["HitCount"]);         applicationCount++;         Application["HitCount"] = applicationCount;         Application.UnLock();         lblApplicationClicks.Text = "All users have clicked the button " + applicationCount + " times.";     }      } File: Global.asax <%@ Application Language="C#" %> <script runat="server">     void Application_Start(object sender, EventArgs e)      {         // Code that runs on application startup         Application.Add("HitCount", 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     }     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.     }         </script>