Lesson 2: Responding to Events

Lesson 2: Responding to Events

In this lesson, you will learn about events in the life cycle of a Web application and how this life cycle is different from the life cycle of a Windows application. Web application events occur at the application, page, and server control levels. The sequence of these events and how they are executed affect how you respond to them in code.

After this lesson, you will be able to

  • Understand the sequence of events in an application s lifetime

  • Explain how the events in an application interact

  • List the events for each of the major objects in a Web application

  • Identify the three different types of server control events

  • Use state variables to preserve information in a Web application

Estimated lesson time: 35 minutes

Events in the Life Cycle of a Web Application

A Web application lives as long as it has active sessions, whereas Web forms live for barely a moment. The life of a Web application begins when a browser requests the start page of the application. (See Figure 2-12.) At that point, the Web server swings into action, starting the assembly (DLL) that responds to that request. The executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.

figure 2-12 life begins!

Figure 2-12. Life begins!

When the browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. (See Figure 2-13.) As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.

figure 2-13 life goes on.

Figure 2-13. Life goes on.

When the user stops using the Web application for a period of time (the default is 20 minutes), the user s session times out and ends. (See Figure 2-14.) If there are no other sessions from other users, the application ends. This doesn t always happen right away. The common language runtime (CLR) manages memory using garbage collection rather than reference counting, as OLE did. Garbage collection means that the server periodically traces through the references between objects. When the runtime finds an object that is no longer used, it throws the object away and recovers the memory. This means that you don t know exactly when an Application_End event will occur.

figure 2-14 this is the end.

Figure 2-14. This is the end.

Preserving Data on a Web Form

Because Web forms have very short lifetimes, ASP.NET takes special steps to preserve the data entered in the controls on a Web form, as shown in Figure 2-15. Data entered in controls is sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.

figure 2-15 asp.net preserves web form data.

Figure 2-15. ASP.NET preserves Web form data.

The data that ASP.NET preserves between requests is called the Web form s view state. By default, a Web form s view state is available only within that Web form. To make data entered on a Web form available to other Web forms in an application, you need to save the data in a state variable in the Application or Session objects. These objects provide two levels of scope:

  • Application state variables

    These are available to all users of an application. You can think of Application state as multiple-user global data. All sessions can read or write these variables.

  • Session state variables

    These are available only to a single session (user). Session state is like global data in a standard Windows application. Only the current session has access to its Session state.

Application and Session state variables aren t declared the way you declare regular variables. Instead, they are created on the fly in code. For example, the following code saves the number of button clicks in Session state:

Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ' Save the number of clicks in Session state. Session("Clicks") = Session("Clicks") + 1 ' Display the number of clicks. Response.Write("Number of clicks: " & Session("Clicks")) End Sub

Visual C#

// From Global.asax.cs protected void Session_Start(Object sender, EventArgs e) { // Initialize Clicks Session state variable. Session["Clicks"] = 0; } // From StateNEvents.asax.cs private void Button1_Click(object sender, System.EventArgs e) { // Increment click count. Session["Clicks"] = (int)Session["Clicks"] + 1; // Display the number of clicks. Response.Write("Number of clicks: " + Session["Clicks"] + "<br>"); }

You can save any type of data in a state variable, from a simple integer to whole objects. Because state variables are global data, you need to develop strategies for working with them in your application. Managing state variables in your code is explained in depth in Chapter 3, Working with Web Objects.

IMPORTANT
Application state variables must be initialized in Visual C# before you perform most operations on them. For example, you need to assign a value to the Clicks state variable before performing the cast (int)Session["Clicks"]. Otherwise, you will receive the error Value null was found where an instance of an object was required at run time.

Application and Session Events

You can write code to respond to Application and Session events in the Global.asax file. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don t want to share between sessions. Table 2-3 lists each of the Application event handlers and describes when they occur.

Table 2-3. Application Event Handlers

Event handler name

Occurs when

Application_Start

The first user visits a page within your Web application.

Application_End

There are no more users of the application.

Application_BeginRequest

At the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.

Application_EndRequest

At the end of each request to the server.

Session_Start

A new user visits a page within your application.

Session_End

A user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.

In Web forms, a session is a unique instance of the browser. A single user can have multiple instances of the browser running on his or her machine. If each instance visits your Web application, each instance has a unique session.

To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project:

Visual Basic .NET

Sub Application_Start(ByVal Sender As Object, ByVal E As EventArgs) ' Record application start. Application("AppCount") = Application("AppCount") + 1 End Sub Sub Session_Start(ByVal Sender As Object, ByVal E As EventArgs) ' Count sessions. Application("SessCount") = Application("SessCount") + 1 ' Display Application count. Response.Write("Number of applications: " & _ Application("AppCount") & "<br>") ' Display session count. Response.Write("Number of sessions: " & _ Application("SessCount") & "<br>") End Sub Sub Session_End(ByVal Sender As Object, ByVal E As EventArgs) ' Decrement sessions. Application("SessCount") = Application("SessCount") - 1 End Sub

Visual C#

protected void Application_Start(Object sender, EventArgs e) { // Create Application state variables. Application["AppCount"] = 0; Application["SessCount"] = 0; // Record application start. Application["AppCount"] = (int)Application["AppCount"] + 1; } protected void Session_Start(Object sender, EventArgs e) { // Count sessions. Application["SessCount"] = (int)Application["SessCount"] + 1; // Display Application count. Response.Write("Number of applications: " + Application["AppCount"] + "<br>"); // Display session count. Response.Write("Number of sessions: " + Application["SessCount"] + "<br>"); } protected void Session_End(Object sender, EventArgs e) { // Decrement sessions. Application["SessCount"] = (int)Application["SessCount"] - 1; }

To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.

It s important to realize that intrinsic objects such as Session and Response are not available at Application_Start. To use these objects, you have to wait until their creation event occurs.

Web Form Events

You use Web form events to process and maintain data used on a Web page, to respond to data binding, and to handle exceptions on the Web page. Table 2-4 lists the events that occur on a Web form; the first five events are shown in order of occurrence.

Table 2-4. Web Form Events

Event handler name

Occurs when

Page_Init

The server controls are loaded and initialized from the Web form s view state. This is the first step in a Web form s life cycle.

Page_Load

The server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.

Page_PreRender

The application is about to render the Page object.

Page_Unload

The page is unloaded from memory.

Page_Disposed

The Page object is released from memory. This is the last event in the life of a Page object.

Page_Error

An unhandled exception occurs.

Page_AbortTransaction

A transaction is aborted.

Page_CommitTransaction

A transaction is accepted.

Page_DataBinding

A server control on the page binds to a data source.

You can couple the Page_Load event with the IsPostback property to initialize data the first time a user visits a Web form. This is similar to a Session_Start event; however, it occurs at the page level rather than the application level. The following code initializes an object and stores it in the Session state the first time a page is viewed:

Visual Basic .NET

' Declare a new object. Dim FlashCard As New FlashCardClass() Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' If this is the first time the page is viewed... If Not (Page.IsPostBack) Then ' Shuffle the FlashCards. FlashCard.Shuffle() ' Store the object in a Session variable. Session("FlashCard") = FlashCard End If ' Get the Session FlashCard variable. FlashCard = Session("FlashCard") RefreshDisplay() End Sub

Visual C#

// From the Web Form Designer generated code region. private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } // Declare a new object. FlashCardClass FlashCard = new FlashCardClass(); private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) { // Shuffle the FlashCards. FlashCard.Shuffle(); // Store the object in a Session variable. Session["FlashCard"] = FlashCard; } // Get the Session FlashCard variable. FlashCard = (FlashCardClass)Session["FlashCard"]; RefreshDisplay(); }

The other page events let you customize the appearance of the page and respond to data events. Data binding, transaction processing, and rendering are covered in greater detail in subsequent chapters.

Server Control Events

Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events:

  • Postback events

    These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server.

  • Cached events

    These events are saved in the page s view state to be processed when a postback event occurs.

  • Validation events

    These events are handled on the page without posting back or caching. The validation server controls use these types of events.

Figure 2-16 shows the sequence of server control events on a Web form. The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.

figure 2-16 a web form s sequence of events

Figure 2-16. A Web form s sequence of events

The Button, Link Button, and Image Button controls all cause postback events. The TextBox, DropDownList, ListBox, RadioButton, and CheckBox controls provide cached events; however, you can override this behavior by setting the AutoPostBack property to True.

To see how validation, cached, and postback events interact, create a Web form with a TextBox control, a RequiredFieldValidator control, and a Button control. Set the ControlToValidate property of the validator control to TextBox1, and then add the following code to the TextBox and Button event handlers:

Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Response.Write("Button Clicked!<br>") End Sub Private Sub TextBox1_TextChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles TextBox1.TextChanged Response.Write("Text has changed!<br>") End Sub

Visual C#

private void Button1_Click(object sender, System.EventArgs e) { Response.Write("Button Clicked!<br>"); } private void TextBox1_TextChanged(object sender, System.EventArgs e) { Response.Write("Text has changed!<br>"); } // From the Web Form Designer generated code region. private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.TextBox1.TextChanged += new EventHandler(this.TextBox1_TextChanged); this.Load += new System.EventHandler(this.Page_Load); }

If you leave the TextBox control blank and click OK, the RequiredFieldValidator control is displayed no other events are processed and the page is not posted back to the server. If you type text in the TextBox control and click OK, the page is posted back and the TextChanged event occurs before the Click event.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net