Lab: Building a Simple Web Application
In this lab, you will create the FlashCards application. FlashCards is a simple, one-form Web application that displays math problems and evaluates the entered result just like the flash cards used in an elementary-school math class.
To complete the FlashCards application, you will create a Web form, add server controls to the form, and control those server controls from the Page_Load event procedure. The completed Web form will look like Figure 2-19.
Figure 2-19. The completed FlashCard Web form
Estimated lesson time: 20 minutes
Exercise 1: Create the User Interface
In this exercise, you will start the FlashCards project and create the user interface by adding server controls to the FlashCard Web form.
To create a new Web application project
On the File menu of Visual Studio .NET, point to New and choose Project. In the New Project dialog box, select ASP.NET Web Application, change the path in the Location box to end with FlashCards, and click OK.
In the Properties window, change the name of the WebForm1.aspx file to FlashCard.aspx.
To add the controls to the user interface
Add server controls to the Web form, as shown in Figure 2-19, and define the following properties:
Control | Control type | Property | Value |
Label1 | Label | ID | lblFeedback |
Font | Arial, Bold, XXL | ||
Text | Flash Cards | ||
Label2 | Label | ID | lblFirst |
Font | Arial, Bold, XXL | ||
Label3 | Label | ID | lblSecond |
Font | Arial, Bold, XXL | ||
<HR> | Horizontal Rule | Size | 4 |
Color | #000000 | ||
TextBox1 | Text Box | ID | txtAnswer |
AutoPostBack | True | ||
Font | Arial, Bold, XXL |
TIP
If you want to create several controls with similar properties, create the first control, set its properties as desired, and then copy and paste to create new controls with the same properties. In Web forms, this does not create a control array as it does in Windows forms.
Exercise 2: Create a Class Named FlashCardClass
In this exercise, you will create a class to contain the logic and data that the FlashCards application uses. A class is a definition of an object used to perform a task in a program. Chapter 3, Working with Web Objects, has more information about object-oriented programming.The FlashCardClass class created here generates random math problems to display on the Web form. This is the logic that the application uses. In this application, and in most Web form applications, the logic (FlashCardClass) is separated from the user interface (the Web form).
To create a class
From the Project menu, choose Add Class. Visual Studio .NET displays the Add New Item dialog box. Name the class FlashCardClass, and click Open.
In the Code window, add the following code:
Visual Basic .NET
Public Class FlashCardClass Dim mintFirstNumber, mintSecondNumber As Integer Dim mstrOp As String = "+" Dim mrndNumber As Random Public Sub New() ' Initialize the random number generator object. mrndNumber = New Random() End Sub Public Sub Shuffle(Optional ByVal Min As Integer = 1, _ Optional ByVal Max As Integer = 12) ' Get random numbers. mintFirstNumber = mrndNumber.Next(Min, Max) mintSecondNumber = mrndNumber.Next(Min, Max) End Sub Public ReadOnly Property FirstNumber() Get FirstNumber = mintFirstNumber End Get End Property Public ReadOnly Property SecondNumber() Get SecondNumber = mintSecondNumber End Get End Property Public Property Operation() As String Get Operation = mstrOp End Get Set(ByVal Value As String) mstrOp = Value End Set End Property ' Calculates answer based on current operation. Public Function Answer() As Integer Select Case mstrOp Case "+" Answer = mintFirstNumber + mintSecondNumber Case "x", "*" Answer = mintFirstNumber * mintSecondNumber Case "-" Answer = mintFirstNumber - mintSecondNumber End Select End Function End Class
Visual C#
public class FlashCardClass { int mintFirstNumber, mintSecondNumber; string mstrOp = "+"; Random mrndNumber; public FlashCardClass() { // Initialize the random number generator object. mrndNumber = new Random(); } public void Shuffle(int Min, int Max) { // Get random numbers. mintFirstNumber = mrndNumber.Next(Min, Max); mintSecondNumber = mrndNumber.Next(Min, Max); } // Shuffle with no parameters defaults to Min = 0, Max = 12. public void Shuffle() { // Get random numbers. mintFirstNumber = mrndNumber.Next(0, 12); mintSecondNumber = mrndNumber.Next(0, 12); } public int FirstNumber { get { return mintFirstNumber; } } public int SecondNumber { get { return mintSecondNumber; } } public string Operation { get { return mstrOp; } set { mstrOp = value; } } // Calculates answer based on current operation. public int Answer() { switch(mstrOp) { case "+": return mintFirstNumber + mintSecondNumber; case "x": return mintFirstNumber * mintSecondNumber; case "*": return mintFirstNumber * mintSecondNumber; case "-": return mintFirstNumber - mintSecondNumber; default : return 0; } } }
Exercise 3: Store a FlashCardClass Object in Session State
In this exercise, you will add code to initialize a Session state variable containing the FlashCardClass object that your Web form will use. The FlashCardClass is stored in a Session variable, so it is retained during the user s session.
To create a Session state variable
In the Code View window for the Web form FlashCard.aspx, add the following code to the Page_Load event procedure:
Visual Basic .NET
' FlashCard.aspx.vb Dim FlashCard As FlashCardClass Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Create a Session FlashCard object the first time page displays. If Not IsPostBack Then ' Create a new FlashCard object FlashCard = New FlashCardClass ' Store the object in a Session variable. Session("FlashCard") = FlashCard Else ' Get the Session FlashCard object. FlashCard = Session("FlashCard") End If RefreshDisplay() End Sub
Visual C#
// FlashCard.aspx.cs FlashCardClass FlashCard; private void Page_Load(object sender, System.EventArgs e) { // Run the following code the first time the page is displayed. if(!IsPostBack) { FlashCard = new FlashCardClass(); Session["FlashCard"] = FlashCard; } else { // Get the Session FlashCard object. FlashCard = (FlashCardClass)Session["FlashCard"]; } RefreshDisplay(); }
Exercise 4: Use the FlashCardClass Object from Web Form Events
In this exercise, you will add code to the Web form to use the FlashCardClass object stored in the Session state variable. This links the logic (FlashCardClass) to the user interface (FlashCard.aspx).
To use the FlashCardClass object from event procedures in the Web form
In the Design window, double-click the TextBox control to automatically create the event procedure and wire the TextChanged event. Add the following code to the Text_Changed event procedure:
Visual Basic .NET
Private Sub txtAnswer_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles txtAnswer.TextChanged If txtAnswer.Text = FlashCard.Answer Then lblFeedback.Text = "Correct!" ' Get another set of numbers. FlashCard.Shuffle() ' Refresh display to show new numbers. RefreshDisplay() ' Clear answer txtAnswer.Text = "" Else lblFeedback.Text = "Oops! Try Again." End If End Sub
Visual C#
private void txtAnswer_TextChanged(object sender, System .EventArgs e) { if(txtAnswer.Text == FlashCard.Answer().ToString()) { lblFeedback.Text = "Correct!"; // Get another set of numbers. FlashCard.Shuffle(); // Refresh display to show new numbers. RefreshDisplay(); // Clear answer txtAnswer.Text = ""; } else { lblFeedback.Text = "Oops! Try Again."; } } // From the Web Form designer generated code region (create automatically // when you double-click the TextBox control. private void InitializeComponent() { this.txtAnswer.TextChanged += new System.EventHandler(this.txtAnswer_TextChanged); this.Load += new System.EventHandler(this.Page_Load); }
In the WebForm1 class, add the following helper procedure to refresh the labels on the display:
Visual Basic .NET
Private Sub RefreshDisplay() lblFirst.Text = FlashCard.FirstNumber lblSecond.Text = FlashCard.Operation & _ FlashCard.SecondNumber End Sub
Visual C#
private void RefreshDisplay() { lblFirst.Text = FlashCard.FirstNumber.ToString(); lblSecond.Text = FlashCard.Operation + FlashCard.SecondNumber.ToString(); }
Run and test the application.
TIP
Using a form-level variable to hold data stored in Session or Application state variables, as shown in steps 2 and 3, helps you catch errors. Visual Studio .NET does not require you to declare state variables. Misspelling a state variable name simply creates a new, empty state variable.