Mega Code Archive

 
Categories / ASP.Net Tutorial / Sessions
 

Session counter and application counter (VB)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"  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" Text="Post" />&nbsp;</div>     </form> </body> </html> File: Default.aspx.vb Partial Class _Default     Inherits System.Web.UI.Page     Dim iSessionCount As Integer     Protected Sub Page_Load(ByVal sender As Object, _             ByVal e As System.EventArgs) Handles Me.Load         If Session("Count") Is Nothing Then             iSessionCount = 0         Else             iSessionCount = CType(Session("Count"), Integer)         End If     End Sub     Protected Sub btnPost_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPost.Click         iSessionCount += 1         lblSessionClicks.Text = "You have clicked the button " & iSessionCount & " times."         Application.Lock()         Dim iApplicationCount As Integer = CType(Application("HitCount"), Integer)         iApplicationCount += 1         Application("HitCount") = iApplicationCount         Application.UnLock()         lblApplicationClicks.Text = "All users have clicked the button " & iApplicationCount & " times."     End Sub     Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender         Session("Count") = iSessionCount     End Sub End Class File: Global.asax <%@ Application Language="VB" %> <script runat="server">     Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)         ' Code that runs on application startup         Application.Add("HitCount", 0)     End Sub          Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)         ' Code that runs on application shutdown     End Sub              Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)         ' Code that runs when an unhandled error occurs     End Sub     Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)         ' Code that runs when a new session is started     End Sub     Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)         ' 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.     End Sub         </script>