Home > Articles > Web Development > ASP.NET

  • Print
  • + Share This
Like this article? We recommend

State Management Examples

The code examples shown in Listings 1 through 5 demonstrate the use of application and state management within an application. For these examples, the timeout value for the session needs to be set to 1 minute.

Listing 1—Global.asax.vb

1  Imports System
2  Imports System.ComponentModel
3  Imports System.Web
4  Imports System.Web.SessionState
5
6  Public Class Global
7   Inherits System.Web.HttpApplication
8
9  #Region " Component Designer Generated Code "
10
11   Public Sub New()
12     MyBase.New()
13
14     'This call is required by the Component Designer.
15     InitializeComponent()
16
17     'Add any initialization after the InitializeComponent() call
18
19   End Sub
20
21   'Required by the Component Designer
22   Private components As System.ComponentModel.Container
23
24   'NOTE: The following procedure is required by the Component Designer
25   'It can be modified using the Component Designer.
26   'Do not modify it using the code editor.
27   <System.Diagnostics.DebuggerStepThrough()> _
28   Private Sub InitializeComponent()
29    components = New System.ComponentModel.Container()
30   End Sub
31
32 #End Region
33
34  Sub Application_OnStart(ByVal Sender As Object, _
35   ByVal e As EventArgs)
36   Application("Application Start Time") = Now.ToLongTimeString
37   Application("SessionCount") = 0
38   Application("RequestCount") = 0
39  End Sub
40
41  Sub Session_OnStart(ByVal Sender As Object, _
42   ByVal e As EventArgs)
43   Dim lngCount As Long
44
45   Application.Lock()
46   lngCount = CLng(Application.Get("SessionCount").ToString) + 1
47   Application("SessionCount") = lngCount
48   Application(Replace(System.Guid.NewGuid.ToString, "-", "")) = _
49    "Session " + Session.SessionID + _
50    " Started " + Now.ToLongTimeString
51   Application.UnLock()
52  End Sub
53
54  Sub Application_BeginRequest(ByVal Sender As Object, _
55   ByVal e As EventArgs)
56   Application.Lock()
57   Application("RequestCount") = _
58    CLng(Application("RequestCount").ToString) + 1
59   Application.UnLock()
60  End Sub
61
62  Sub Application_EndRequest(ByVal Sender As Object, _
63   ByVal e As EventArgs)
64
65  End Sub
66
67  Sub Session_OnEnd(ByVal Sender As Object, ByVal e As EventArgs)
68   Dim lngCount As Long
69
70   Application.Lock()
71   lngCount = CLng(Application("SessionCount").ToString) - 1
72   Application("SessionCount") = lngCount
73   Application(Replace(System.Guid.NewGuid.ToString, "-", "")) = _
74    "Session " + Session.SessionID + _
75     " Ended " + Now.ToLongTimeString
76   Application.UnLock()
77  End Sub
78
79  Sub Application_OnEnd(ByVal Sender As Object, _
80   ByVal e As EventArgs)
81
82  End Sub
83
84 End Class

Listing 2—WebForm1.aspx

1  <%@ Page Language="vb" AutoEventWireup="false" 
2   Codebehind="WebForm1.aspx.vb" 
3   Inherits="Chapter9.WebForm1"%>
4
5  <html>
6   <head>
7    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
8    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
9   </head>
10  <body>
11
12   <form id="WebForm1" method="post" runat="server">
13   <table>
14    <tr>
15     <td valign=top>
16      Session ID
17     </td>
18     <td>
19      <% response.write(Session.SessionID) %>
20     </td>
21    </tr>   
22    <tr>
23     <td valign=top>
24      Application Contents
25     </td>
26     <td>
27      <asp:listbox id=lstSessions runat=server rows=15>
28       
29      </asp:listbox>     
30     </td>
31    </tr>
32    <tr>
33     <td valign=top>
34      Session Timeout
35     </td>
36     <td>
37      <% response.write(Session.TimeOut) %>
38     </td>
39    </tr>
40   </table>
41   </form>
42
43  </body>
44 </html>

Listing 3—WebForm1.aspx.vb

1  Public Class WebForm1
2   Inherits System.Web.UI.Page
3   Protected WithEvents lstSessions As System.Web.UI.WebControls.ListBox
4
5  #Region " Web Form Designer Generated Code "
6
7   'This call is required by the Web Form Designer.
8   <System.Diagnostics.DebuggerStepThroughAttribute()> _
9    Private Sub InitializeComponent()
10
11   End Sub
12
13  Protected Sub Page_Init(ByVal Sender As Object, _
14   ByVal e As System.EventArgs) Handles MyBase.Init
15   'CODEGEN: This method call is required by the Web Form Designer
16   'Do not modify it using the code editor.
17   InitializeComponent()
18  End Sub
19
20 #End Region
21
22  Private Sub Page_Load(ByVal sender As Object, _
23   ByVal e As EventArgs) Handles MyBase.Load
24   Dim txtCount As New System.Web.UI.WebControls.TextBox()
25
26   Dim obj As IEnumerator
27
28   lstSessions.Items.Clear()
29   Application.Lock()
30   obj = Application.AllKeys.GetEnumerator
31   Do While obj.MoveNext
32    lstSessions.Items.Add(obj.Current.ToString + ": " _
33     + Application(obj.Current.ToString).ToString)
34   Loop
35   obj = Nothing
36   Application.UnLock()
37  End Sub
38
39 End Class

Listing 4—WebForm2.aspx

1  <%@ Page Language="vb" 
2   AutoEventWireup="false" 
3   Codebehind="WebForm2.aspx.vb" 
4   Inherits="Chapter9.WebForm2"%>
5
6  <HTML>
7   <HEAD>
8    <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
9    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
10   <META HTTP-EQUIV="Refresh" CONTENT="5">
11  </HEAD>
12  <body>
13
14   <form id="WebForm2" method="post" runat="server">
15   <table>
16    <tr>
17     <td valign=top>
18      Session ID
19     </td>
20     <td>
21      <% response.write(Session.SessionID) %>
22     </td>
23    </tr>   
24    <tr>
25     <td valign=top>
26      Current Time
27     </td>
28     <td>
29      <% 
30       response.write(Now.ToLongDateString)
31       response.write(" ")
32       response.write(Now.ToLongTimeString)
33      %>
34     </td>
35    </tr>   
36    <tr>
37     <td valign=top>
38      Application Contents
39     </td>
40     <td>
41      <asp:listbox id=lstSessions runat=server rows=15>      
42       
43      </asp:listbox>     
44     </td>
45    </tr>   
46   </table>
47   </form>
48
49  </body>
50 </HTML>

Listing 5—WebForm2.aspx.vb

1  Public Class WebForm2
2   Inherits System.Web.UI.Page
3   Protected WithEvents lstSessions As System.Web.UI.WebControls.ListBox
4
5  #Region " Web Forms Designer Generated Code "
6
7   'CODEGEN: This procedure is required by the Web Form Designer
8   'Do not modify it using the code editor.
9   Private Sub InitializeComponent()
10
11  End Sub
12
13 #End Region
14
15  Private Sub Page_Init(ByVal sender As Object, _
16   ByVal e As EventArgs) Handles MyBase.Init
17
18   Dim obj As IEnumerator
19
20   Application.Lock()
21   obj = Application.AllKeys.GetEnumerator
22   Do While obj.MoveNext   
23    lstSessions.Items.Add(obj.Current.ToString + ": " _
24     + Application(obj.Current.ToString).ToString)
25   Loop
26   Application.UnLock()
27   obj = Nothing
28  End Sub
29 End Class

To start this application, first view the WebForm1.aspx page in a browser window. Next, open a new browser window and then open the WebForm1.aspx page again (don't use the menu option in your browser because the new browser will share the same session as the first browser). Now open the WebForm2.aspx page in a third new browser window. The WebForm2.aspx page has a header value that causes this page to be refreshed every 5 seconds:

<META HTTP-EQUIV="Refresh" CONTENT="5">

When the window first opens, the Application Contents list box should indicate that three sessions have started. As this page refreshes, the request count increases. If you refresh one of the other browser windows, you'll notice that the request count increases. If you let the WebForm1.aspx browser windows remain idle for a full 60 seconds, the WebForm2.aspx page will reflect the shutdown of the sessions in the other two browser windows as well as in the first.

Figures 1 through 5 demonstrate the preceding examples.

Figure 1 The first WebForm1.aspx browser.

Figure 1 illustrates the first session being created as WebForm1.aspx is launched. Notice that the session count equals 1 and a unique session ID has been assigned to this session.

Figure 2 The second WebForm1.aspx browser.

Figure 2 illustrates a second session of WebForm1 being created. Notice that the application session count now equals 2. Also, a new unique session ID has been assigned to this second instance of the WebForm1.aspx file.

Figure 3 Initial WebForm2.aspx browser output showing three active sessions.

Figure 3 illustrates the first instance of the WebForm2.aspx file. This is the first instance created of the WebForm2.aspx file, but it's the third session created for the application. Notice in the Application Contents box that the session count is now equal to 3. This Application Contents box also displays each current session's unique identifier (session ID) with the start time of when the session was created. These IDs and start times can be cross-referenced with the previous figures.

Figure 4 WebForm2.aspx browser output after the initial two sessions have ended due to timing out.

Figure 4 illustrates the timing out of the two WebForm1.aspx sessions. As mentioned earlier, if we let the browsers stay idle for the timeout period (set to 1 minute in this example), the browsers will time out and their sessions will end. Figure 4 illustrates in the Application Contents box that the session count is now 1. This last active session is the WebForm2.aspx session. Also notice that the session IDs of the active session and the closed sessions, with their corresponding start times, are listed in the Application Contents box. This box also displays the newly closed session IDs and end times of the initial WebForm1 sessions.

The following list contains code snippets seen in the previous listings. These bullets illustrate code integral in our previous State Management example.

Creates a new globally unique identifier (GUID)

Application(replace(System.Guid.NewGuid.ToString, "-", "")) = "Session " + Session.SessionID + " Started " + Now.ToLongTimeString
  • Data type conversion

  •     lngCount = CLng(Application.Get("SessionCount").ToString) + 1
  • Locking and unlocking the Application object

  • 	Application.Lock()
        Application("RequestCount") = _
        CLng(Application("RequestCount").ToString) + 1
        Application.UnLock()
  • Retrieving session properties

  • 	<% response.write(Session.SessionID) %>
    	<% response.write(Session.TimeOut) %>
  • Looping through the items in the application collection

  • 	Dim obj As IEnumerator
    	obj = Application.AllKeys.GetEnumerator
    	Do While obj.MoveNext
    	lstSessions.Items.Add(obj.Current.ToString + ": " + Application(obj.Current.ToString).ToString)
    	Loop
    	obj = Nothing
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020