ASP.NET Applications

Until now, we examined single-paged Web Forms. However, when programming more ambitious Web systems, developers divide the functionality between several Web Forms that are responsible for different aspects of interacting with the user or performing other tasks. In other words, the code resides in multiple .aspx pages that are related. Such Web pages are unified under a Web application. You may create a Web application using IIS by right-clicking on the directory, choosing Properties, and clicking on the Create button on the displayed dialog box (see Figure 16-10). All the Web pages under the chosen directory will be considered as belonging to the newly created Web application.

Figure 16-10. Creating a Web application with IIS for the GuessingGame sample.


There are many advantages of unifying a set of pages under the same Web application. You may share values among the application pages using Session or Application scopes. We illustrate this on the GuessingGame sample that resides in the NetPerl virtual directory. To work with the sample, you must create for it a Web application, as explained above. In this sample you first choose the upper bound for the game. Then the computer generates a random integer number between 1 and the number you provided in the upper bound. Your task is to guess the number and not to exceed the maximum attempts number. After each guess, the program indicates whether your guess was greater or less than the correct number. In the case of a successful guess you will be redirected to the WellDone.aspx page, and if you run out of attempts, you will be sent to the GameOver.aspx page.

Sessions

To appreciate the Web application support provided by ASP.NET, we need to understand the concept of a Web session. HTTP is a stateless protocol. This means that there is no direct way for a Web browser to know whether a sequence of requests is from the same client or from different clients. A Web server such as IIS can provide a mechanism to classify requests coming from a single client into a logical session. ASP.NET makes it very easy to work with sessions.

Global.asax

An ASP.NET application can optionally contain a file Global.asax, which contains code for responding to application-level events raised by ASP.NET. This file resides in the root directory of the application. If you do not have a Global.asax file in your application, ASP.NET will assume you have not defined any handlers for application-level events.

Global.asax is compiled into a dynamically generated .NET Framework class derived from HttpApplication.

Here is the Global.asax file for our GuessingGame sample.


<SCRIPT language="Perl" runat="server">

=for interface
    void Application_Start(any sender, System.EventArgs e);
    void Session_Start(any sender, System.EventArgs e);
=cut

sub Application_Start
{
    my $this = shift;
    # Set Maximum number of guesses allowed
    $this->{Application}->set_Item("MaxAttempts", 10);
}

sub Session_Start
{
    my $this = shift;

    # Redirect use to the start page
    $this->{Response}->Redirect("Default.aspx");
}

</SCRIPT>

The most common application-level events are shown in this code. The typical life cycle of a Web application consists of these events:

  • Application_Start is raised only once during an application's lifetime, on the first instance of HttpApplication. An application starts the first time it is run by IIS for the first user. In your event handler you can initialize a state that is shared by the entire application.

  • Session_Start is raised at the start of each session. Here you can initialize session variables.

  • Application_BeginRequest is raised at the start of an individual request. Normally, you can do your request processing in the Page class.

  • Application_EndRequest is raised at the end of a request.

  • Session_End is raised at the end of each session. Normally, you do not need to do cleanup of data initialized in Session_Start, because garbage collection will take care of normal cleanup for you. However, if you have opened an expensive resource, such as a database connection, you may wish to call the Dispose method here.

  • Application_End is raised at the very end of an application's lifetime, when the last instance of HttpApplication is torn down.

For each event, you may declare an event handler in the same manner as we did for Application_Start and Session_Start.

In our sample, we set the maximum number of attempts for our guessing game in Application_OnStart. We store it as application variable.

$this->{Application}->set_Item("MaxAttempts", 10);

Its value may be then retrieved in the Web pages of our application.

In the Session_Start event handler we redirect the user to the Default.aspx page.

$this->{Response}->Redirect("Default.aspx");

It is a useful technique when you want all the users to start browsing your application from a certain page (like log-in page) at the beginning of the session. Figure 16-11 shows the start page of the guessing game.

Figure 16-11. Start page of the guessing game application.


State Management in ASP.NET Applications

Preserving state across HTTP requests is a major problem in Web programming, and ASP.NET provides several facilities that are convenient to use. There are two main types of state to be preserved.

  • Application state is global information that is shared across all users of a Web application.

  • Session state is used to store data for a particular user across multiple requests to a Web application.

APPLICATION OBJECT

You can store global application information in the built-in Application object, an instance of the class HttpApplicationState. You can conveniently access this object through the Application property of the Page class. The HttpApplicationState class provides a key-value dictionary that you can use for storing both objects and scalar values.

In our GuessingGame sample we stored the MaxAttempts variable inside the Application object. We used this value to check whether a player exceeded the maximum number of attempts guessing the number. Here is the fragment from the code-behind Guess.aspx.pm file for the Guess.aspx Web form:

if ($attempt_num >= 
  int($this->{Application}->get_Item("MaxAttempts")))
{
   $this->{Response}->Redirect("GameOver.aspx");    
}

Additionally, we display the current number of attempts and total number of allowed attempts at the bottom of the page (see Figure 16-12).

Figure 16-12. Guess.aspx Web Form.


SESSION OBJECT

You can store session information for individual users in the built-in Session object, an instance of the class HttpSessionState. You can conveniently access this object through the Session property of the Page class. The HttpSessionState class provides a key-value dictionary that you can use for storing both objects and scalar values, in exactly the same manner employed by HttpApplicationState.

In our guessing game Web application, we store the player's attempt number and number to guess inside the Session object. We initialize the AttemptNum session variable in the code for Default.aspx Web Form as a response to pressing the Start button:

sub btnStart_Click
{
   my $this = shift;
   my $ubound = int($this->{txtUbound}->{Text});
   if ($ubound > 0)
   {
      my $session = $this->{Session};
      my $num = int(rand($ubound))+1;
      $session->set_Item("Number", $num);
								$session->set_Item("AttemptNum", 1);
      $this->{Response}->Redirect("Guess.aspx");
   }
}

Guessing Game

Most of the interesting things in this sample go on inside Guess.aspx Web Form and its Guess.aspx.pm code-behind file. Here is the full code for both files. If you followed our explanations, the code should be self-explanatory for you.

<!-- Guess.aspx -->
<%@ Page Language="Perl" SRC="Guess.aspx.pm" Inherits=GuessPage %>
<HTML>
<HEAD>
<TITLE>Guessing Game</TITLE>
</HEAD>
<BODY>
<CENTER>
<H2>
<FONT color="red">
Number Guessing Game
</FONT>
</H2>
<BR>
<P>
<B>
Enter your guess in the textbox and press the "Guess" button.
</B>
</P>
<P>
<asp:Label RUNAT="SERVER" id=lblMsg></asp:Label>
</P>
<FORM RUNAT="SERVER">
Your Guess: &nbsp;
<asp:TextBox RUNAT="SERVER" id=txtGuess></asp:TextBox>
<BR>
<BR>
<asp:Button RUNAT="SERVER" id=btnGuess Text="Guess" onClick=btnGuess_Click></asp:Button>
</FORM>
<BR>
<P>
Current attempt number: 
<FONT size="5">
<B><%= $this->{Session}->get_Item("AttemptNum") %></B>
</FONT>
</P>
<P>
Maximum number of attempts:
<FONT size="5">
<B><%= $this->{Application}->get_Item("MaxAttempts")  %> </B>
</FONT>
</P>
</CENTER>
</BODY>
</HTML>

Note that we used <%= … %> ASP.NET tags (bolded in the code) for displaying Session and Application variables. The expression within these tags is evaluated on the server, and its value is displayed in the resulting HTML.

Here is the code-behind.

#
# Guess.aspx.pm
#

package GuessPage;
use namespace "System";
use namespace "System.Web";
use namespace "System.Web.UI";
use namespace "System.Web.UI.WebControls";

=for interface
   [extends: System.Web.UI.Page]
   void btnGuess_Click(any sender, System.EventArgs e);
   protected field Label lblMsg;
   protected field TextBox txtGuess;
=cut

sub btnGuess_Click
{
   my $this = shift;

   # get the Answer number
   my $number = int($this->{Session}->get_Item("Number"));
   # get the guessed number
   my $guess = int($this->{txtGuess}->{Text});
   # get the current attempt number
   my $attempt_num = int($this->
                  {Session}->get_Item("AttemptNum"));
   if ($guess > $number)
   {
      if ($attempt_num >= int($this->{Application}->
                            get_Item("MaxAttempts")))
      {
         $this->{Response}->Redirect("GameOver.aspx");           
      }
      $this->{lblMsg}->{Text} = "Your Guess is Greater";
   }
   elsif ($guess < $number)
   {
      if ($attempt_num >= int($this->{Application}->
                            get_Item("MaxAttempts")))
      {
         $this->{Response}->Redirect("GameOver.aspx");           
      }
      $this->{lblMsg}->{Text} = "Your Guess is Less";
   }
   else
   {
      $this->{Response}->Redirect("WellDone.aspx");
   }
   $attempt_num++;
   $this->{Session}->set_Item("AttemptNum", $attempt_num);
}

All the code is executed in response to the user pressing the Guess button. We compare the guess with the correct answer stored in the Session variable and act accordingly.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.240.222