Programming Web Forms

This section features a collection of three sample applications that illustrate the basics of building ASP.NET Web applications with Visual Basic .NET. The purpose of the samples is to reinforce and extend the key concepts of Web development presented in the prior two sections.

Hello and Goodbye Sample

The standard Hello World sample is an exercise in how to get a computer program to interact with a user. The user performs a task, such as starting the application or clicking a button, and the program responds by sending some variation of the Hello World message. Web applications implemented with Visual Basic .NET do not support a MsgBox function for displaying a reply. However, a Web page can include controls with variable text messages. These text messages can refresh on each round-trip of a page between a browser and a server.

The Hello and Goodbye sample illustrates several standard Web features that you are likely to include in many of your applications. First, the review of the layout procedure for the controls on a page illustrates basic design issues while introducing you to a special Web application control. Second, the sample demonstrates how similar a Page_Load event procedure in a Web application can be to a Form_Load event procedure in a Windows application. This similarity of control layout and programming environments eases the transition process for Access developers who have limited Web development experience. Third, the sample illustrates how to say goodbye to the current Web page (or at least move to another Web page). A Web server Hyperlink control achieves this purpose, and using the HyperLink control demonstrates how to manage this kind of functionality with Visual Basic .NET on a Web page.

Starting the WebPageSamples Project

To start a Web application, you can use the ASP.NET Web Application template. Click New Project from the Start Page in the IDE (or select File, New, Project from the Visual Studio .NET menu). With Visual Basic Projects selected, highlight ASP.NET Web Application in the Templates pane. Specify a Web server name and a Web site location for your new project. Figure 10-2 shows the designation of the WebPageSamples Web site on the localhost Web server.

click to expand
Figure 10-2: Start a new ASP.NET Web application project with the ASP.NET Web Application template.

After you click OK, Visual Studio .NET starts creating folders for the project in two places. First, you might be prompted to authenticate yourself on your chosen server. Enter a valid Windows user ID and password with sufficient permissions to perform project authoring. A Web application s main project folder is within the wwwroot folder of the Web server that you specify when creating the Web application. The project folder on the Web server has your Web pages and other support project files for working with IIS and serving pages to browsers. Visual Studio .NET creates a second project folder for Web application projects in its default location for Visual Studio projects. On my test computer for this book, that project folder is the Visual Studio Projects folder in the c:\\Documents and Settings\Administrator\My Documents\ path . This secondary project folder holds the .sln file that Visual Studio can use to open a project and modify it. The name for the .sln file matches the name for your ASP.NET Web application project.

Laying Out the HelloGoodbye.aspx Web Page

As mentioned previously, a Web application project opens to a blank form. The default name for a new page with the blank form in a new project will be WebForm1.aspx. You can rename the file for the Web page by right-clicking it in Solution Explorer, choosing Rename from the menu, and assigning a new name for the project. I assigned the name HelloGoodbye.aspx to replace WebForm1.aspx.

After you optionally change the page s filename to something meaningful, your next task will likely be adding controls to the page s form. As you can see from the HTML view for your Web page, the whole body of the document consists of a Web form tag. This form is an ASP.NET Web Forms control. You can drag additional controls from the Toolbox onto the form s surface, and the Web Forms Designer will nest those controls within the opening and closing form tags.

Figure 10-3 shows three Web server controls in the HelloGoodbye.aspx Web page. I dragged the controls from the Web Forms tab of the Toolbox onto the form. The Button control appears in its default configuration, but the other two controls appear with minor editing. Programmatically formatting Web controls does not rigidly follow Windows Forms conventions, but many similarities exist. As you start to develop ASP.NET solutions, you might find it more productive to adjust selected control properties manually. For example, the Label control is dragged to a longer length. You can see the control s white background blocking the visibility of the grid behind it. Figure 10-3 shows the HyperLink1 control selected. You can see two of its custom property settings in the Properties window. Clicking in the NavigateURL property in the HyperLink1 property column, and then clicking the button that appears opens the Select URL dialog box to assist you in specifying a destination URL for the HyperLink control. By the way, the URL in this example is the Web site for my favorite seminar tour.

click to expand
Figure 10-3: You can use the Properties window to fine-tune the behavior of controls on Web pages as you get used to the programmatic interface.

Adding Code Behind the Page

The code behind the page for this sample requires a couple of event procedures. A Page_Load event procedure assigns the Text property values to the Button and Label controls on the form. By embedding the assignments within an If Then statement, the procedure can make the specifications just once. The condition for the If Then statement is Not IsPostBack . This condition is true just once in any Web session: the first time that a user opens the page. Therefore, the code within the If Then statement executes only on the first view that a user gets of the page. After that, the built-in ASP.NET page logic automatically populates the Button and Label controls with the initial values set from within the If Then statement. Custom logic for a page s IsPostBack property offers a convenient way of isolating code that needs to run just once. This, in turn , speeds the performance of your applications and reduces the load on your Web server.

Notice that the Page_Load event automatically inserts a greeting in the Label control: This is my initial hello. However, a user can change the greeting by clicking the Button control on the Web page. In a fashion similar to that of the Page_Load procedure, the Button1_Click procedure adds the new greeting ( Hi, again. ) only if it does not already appear. Conditional execution is less important outside the Page_Load event procedure. This is because the Page_Load event procedure operates on each round-trip for a Web page between a browser and a server, but event procedures for other controls fire only when those specific events get raised based on user actions. It s good practice to keep all event procedures lean, but this is especially so for the Page_Load procedure.

 Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If not posted back, set initial conditions If Not IsPostBack Then Button1.Text = "Hello again" Me.Label1.Text = "This is my initial hello." End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If not updated message, then update message If Me.Label1.Text <> "Hi, again." Then Me.Label1.Text = "Hi, again." End If End Sub 

Demonstrating the Sample

To test the application from Visual Studio .NET, right-click the HelloGoodbye.aspx file in Solution Explorer and choose Build And Browse. Choosing this option compiles your code and opens a browser session from within Visual Studio .NET. Figure 10-4 shows the built-in browser session after the HelloGoodbye.aspx page initially opens. Notice that the Button and Label controls have nondefault Text property settings that differ from those shown in Figure 10-3. The HelloGoodbye.aspx file appears selected in Solution Explorer because the file was last selected to open the page.

click to expand
Figure 10-4: The built-in browser makes it easy to verify the operation of ASP.NET Web applications in Visual Studio .NET.

Clicking Button1 or HyperLink1 revises the contents of the browser session on the Browse ” WebForm1 tab in Figure 10-4. In the case of a click to Button1 , the contents of the Label control on the Web page change. Clicking HyperLink1 changes the whole page to the home page for my favorite seminar tour. For the hyperlink to operate , you need an open connection to the Internet. In this day of always-on broadband connections, the availability of such a connection is growing. If you do even a moderate amount of Web development work, such a connection is likely to prove useful.

Hello and Refresh Sample

As simple as the HelloGoodbye.aspx Web page was, it suffered from a flaw typical of many ASP.NET Web applications. Clicking a browser s Refresh control might or might not refresh the Web page, but it almost always brings up a dialog box similar to the one shown in Figure 10-5. The user must choose between two options. This is probably not what you would prefer. An alternative is to create your own Refresh button inside the application. The next sample revises the previous one to include a custom Refresh button. In addition, the sample disables and hides the Hello Again button after a click to the button alters the Label control display from its initial message to a revised one. When the sample disables the Hello Again button, it moves the HyperLink1 control to occupy the button s location. A manipulation such as this can have a definite impact on the performance of an application because it removes the possibility of unnecessary round-trips back to the server while concurrently reducing network traffic.

click to expand
Figure 10-5: Clicking the Refresh button in the browser for an ASP.NET Web application will often bring up this dialog box.

Laying Out the HelloRefresh.aspx Web Page

This new sample can exist within a Web page of its own in the WebPageSamples project folder on the localhost Web server. Therefore, within the current project, choose Project, Add Web Form. If you are progressing along with the sample, this will create a new Web page named WebForm2.aspx. You can right-click the page in Solution Explorer, select Rename, and give the file a more relevant name, such as HelloRefresh.aspx.

Add controls to the form in the arrangement that Figure 10-6 shows. Use the same settings for the HyperLink control as in the previous sample. The major design change for the new sample is the addition of a second Button control. A click to the new button handles the function that you expect from a Refresh control on the browser s toolbar. When a user clicks the new button, our application will refresh the application exactly as we ve instructed it to in our program. For example, this revised refresh capability does not show the dialog box appearing in Figure 10-5.


10-6 : The highlighted button shows the new control added to the previous application sample.

Demonstrating the Sample

The operation of this application will help you understand the code review. Therefore, I demonstrate the code before discussing the syntax and organization of the code behind the Web page. The application opens to the window shown in the top left corner of Figure 10-7. This window shows the initial greeting in Label1 along with the other controls, featuring their custom text property settings. The top right window displays the Web page after the first click to Button1 (Hello Again). A second click to Button1 causes the application to resemble the lower left window in Figure 10-7. The window shows that the HyperLink control moves from its initial position to the right of Button1 to the same position as Button1 . In addition, Button1 disappears from the page s form.

click to expand
Figure 10-7: Four windows from the Hello and Refresh sample

Clicking Button2 (Refresh) within the lower left window in Figure 10-7 restores the Web page to its initial appearance. The bottom right window in Figure 10-7 shows the restored page. You can confirm the operation by comparing the lower right and top left windows in Figure 10-7.

Adding Code for the HelloRefresh Page

In addition to the refresh code, this sample demonstrates code for changing the position of, disabling, and hiding a control. By applying logic such as that developed for this sample, you can readily give your Web pages a dynamic and highly interactive feel.

Managing the location of controls on a Web page is more challenging than doing so with a Windows form for a couple of reasons. First, the position for a control on a Web page is not a Structure (two ordered Integer values comprising a Point structure). Instead, displacements from the top and left of the Web page appear within the style attribute setting for a control when you are using absolute coordinate positioning as this sample does. This style attribute includes other formatting specifications for the control as well. You can switch to the HTML view for the form shown in Figure 10-6 to confirm the design of the style attributes for the Button1 and HyperLink1 controls. The sample application moves the HyperLink control twice: once from its initial location to the location occupied by the Button1 control, and a second time from the initial location for Button1 back to the initial position for HyperLink1 . Clicking the Refresh button moves the HyperLink control back to its initial position on the page s form.

The second challenge to moving controls around a Web page stems from the fact that Web pages have no memory in transit from a browser to a server (unless special measures are taken). Therefore, simply copying the DHTML style attribute settings for the control tags on a Web page to a memory variable in the code behind the page does not solve the problem ”even if you define the variable at the module level ”because the values of the memory variable are normally lost in transit from a browser to a server. Numerous techniques can help you work around this issue.

This sample demonstrates a simple and relatively familiar technique for Visual Basic developers. It uses the Shared access keyword to declare the memory variables for storing style attribute settings for the Button1 and HyperLink1 controls. This approach has the advantage of using a technique that emerges from your Windows (and even classic Visual Basic) programming experience. The Shared access modifier in Visual Basic .NET behaves similarly to the Static keyword in classic Visual Basic in that both ways of declaring a variable enable the variable to maintain values over the lifetime of an application.

The sample application stores the original style attribute settings for the Button1 and HyperLink1 controls in the str1 and str2 memory variables, respectively. This enables the writing over of the original HyperLink1 style attribute setting with the original attribute setting for Button1 . The saved memory variables also enable the restoring of the original style attribute setting for the HyperLink1 control.

After the module-level declaration of the str1 and str2 memory variables with Shared access modifiers, the sample listing shows the code for the Page_Load event procedure. This event procedure is identical to the Page_Load event for the preceding sample, except for the setting of the Text property for the new Button control with a value of Refresh . This button refreshes the page s form without displaying the dialog box that appears in Figure 10-5.

The Button1_Click procedure is almost entirely new. The If Then Else statement that comprises the core of this procedure saves the style attributes for the Button1 and HyperLink1 controls and saves the original style attribute for the Button1 control over the original attribute setting for the HyperLink1 control. The copying of the style attribute for Button1 to the style attribute for HyperLink1 is what causes the HyperLink1 control to move to the position occupied by the Button1 control. To avoid distracting users with Button1 in the background behind HyperLink1 and to ensure that clicks do not activate Button1 , the application disables Button1 and makes it invisible.

The Button2_Click procedure handles the refresh operation for the application. If the initial message for the Label1 control is visible, the application simply exits. Otherwise , the procedure performs a sequence of restore operations to refresh the application. In the end, the Button1 control is visible again and works as it did initially.

 Shared str1 As StringShared str2 As String Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If not posted back, set initial conditions If Not IsPostBack Then Button1.Text = "Hello again" Button2.Text = "Refresh" Me.Label1.Text = "This is my initial hello." End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click If showing updated message and attribute store is empty, disable/hide Hello again button and move hyperlink in place of button; otherwise assign updated message to Label1 If Me.Label1.Text = "Hi, again." And _ str1 = "" Then Button1.Visible = False Button1.Enabled = False str1 = Me.Button1.Attributes("style") str2 = Me.HyperLink1.Attributes("style") Me.HyperLink1.Attributes("style") = str1 Else Me.Label1.Text = "Hi, again." End If End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click If initial message showing, ignore click; otherwise, restore controls on and behind HelloRefresh web form If Me.Label1.Text = _ "This is my initial hello." Then Exit Sub Else Restore attribute with position settings Me.HyperLink1.Attributes("style") = str2 Restore other conventional button and label properties Me.Button1.Visible = True Me.Button1.Enabled = True Me.Label1.Text = "This is my initial hello." Restore attribute stores str1 = "" str2 = "" End If End Sub 

Logging In to a Protected Page Sample

The final sample in this chapter demonstrates a simple version of a security-by-form sample. The purpose of the sample is to demonstrate how to use Session variables to manage state ”that is, variables associated with some aspect of an application, such as the whole application, a user s session, or even values for an individual form outside the control values that ASP.NET automatically persists for your applications. This particular application remembers whether a user input MemberID and Password values. If the user did set these Session variables, the application checks their values to authenticate the user. Session variables are ideal for this kind of an application because their lifetime is the duration of a session. Furthermore, a user can have values for his MemberID and Password variables that differ from another user s values. A user logs out by closing the browser session or after a fixed period of inactivity (typically 20 minutes).

Figure 10-8 shows an overview of the sample s design. The design spans four Web pages. Two likely pages from which users can enter the application are the ASPNETMenu.aspx page and the LoginPage.aspx page. If a browser session opens on the ASPNETMenu.aspx page without first setting MemberID and Password Session variables, the application reminds the user of the missing values and offers a link to the LoginPage.aspx page. The LoginPage.aspx page contains two text box controls for accepting the login information and some code behind the page s form for saving the contents of the text boxes as Session variables. If the user inputs invalid MemberID or Password values, the application sends her to a page describing the problem with a link to the LoginPage.aspx page so that she can correct the problem. Users can exit the application at any page, but the pages informing users about missing Session variable values or invalid Session variable values are particularly appropriate. For example, a message on each page can contain a telephone number for requesting further assistance, such as help for remembering a forgotten password.

click to expand
Figure 10-8: A flowchart indicating the logic for the sample demonstrating the use of Session variables

Two pages serve as the foundation of the sample application. The LoginPage.aspx page lets a user designate Session variables. The ASPNETMenu.aspx page uses the Session variables in two tests. The code behind both of these pages is critical to the application. The NotLoggedIn.htm and BadMemberIDPassword.htm pages are basic Web pages with text messages containing a hyperlink.

The LoginPage.aspx Web Page

Figure 10-9 shows a Browse window view of the form for the LoginPage.aspx file. The two TextBox controls accept values for the two Session variables that authenticate the user in the current browser session. Clicking the Login button saves the Text property value of each TextBox control in a Session variable and transfers control to the ASPNETMenu.aspx page.

click to expand
Figure 10-9: A basic custom login page for an ASP.NET Web application
Note  

The purpose of this sample is to introduce you to Session variables “not to demonstrate best practices for a login application. In a practical application, you will want to encrypt at least the Password value that you pass from a browser client to a Web server.

Two short event procedures exist behind the form in Figure 10-9. The Page_Load procedure merely assigns Text property values for controls on the form. You might be wondering why these assignments are conditional on the IsPostBack property of the current Page instance being False . After all, you might think that a user should log in just once during a session. No matter how reasonable this assumption, nothing in the application requires only one user per session. If a user knows multiple valid MemberID and Password values, he can successively log in with these values in a single session.

The application invokes the Button1_Click procedure when a user clicks the Login button on the form shown in Figure 10-9. The first two lines of the procedure assign the Text property values for TextBox1 and TextBox2 to MemberID and Password Session variables. As you can see, the syntax is straightforward. The procedure s third and final line transfers control to the ASPNETMenu.aspx page in the current application. The line uses the Redirect method of the Response object. The Redirect method transfers control to a new URL. The method acts similarly to a hyperlink that a user does not have to click. Because ASPNETMenu.aspx resides in the current folder, you do not need to designate a path. A more general format for the string argument of the Redirect method is http://path/pageinpath.xxx , in which xxx denotes the extension type, such as aspx or htm.

 Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Set text property values for labels and button If Not IsPostBack Then Label1.Text = "MemberID" Label2.Text = "Password" Button1.Text = "Login" End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Assign text box contents to two Session variables Session("MemberID") = TextBox1.Text Session("Password") = TextBox2.Text Response.Redirect("ASPNetMenu.aspx") End Sub 

The ASPNETMenu.aspx Web Page

The ASPNETMenu.aspx page is a simple menu implemented with hyperlinks . Figure 10-10 shows the page in Design view from within Visual Studio .NET. To add a hyperlink to a Web page, select the text for the hyperlink and choose Insert, Hyperlink. The Hyperlink dialog box lets you type the destination URL for the hyperlink or browse to the desired page. The Properties window in Figure 10-10 shows that the third hyperlink is selected because it points at the LoginPage.aspx file on the ccs1 Web server, which is an intranet server in my office. Because the page includes just text, including a header for the menu and the hyperlink text, this page is a likely candidate for using a FlowLayout setting for the pageLayout property and a ShowGrid property value of False . When you select a FlowLayout setting, the Web Forms Designer automatically sets the ShowGrid property to False . The FlowLayout property setting permits you to add text to a page without embedding it in controls and to manage the text as you would any text in a word processor.

click to expand
Figure 10-10: A basic menu page implemented with hyperlinks but with ASP.NET code behind it

What makes the ASPNETMenu.aspx page special is the code behind it. As the flowchart in Figure 10-8 indicates, the page poses two questions about the MemberID and Password Session variables. First, the page asks whether the variables have assigned values. Second, the page assesses whether the MemberID and Password Session variables are valid. The Page_Load procedure in ASPNETMenu.aspx has two code blocks. The first block shows one approach to handling the first question. If either Session variable is an empty string, the default value, the procedure transfers control to the NotLoggedIn.htm page. The second code block authenticates the values in the two Session variables. The code accepts just two sets of MemberID/Password pairs as valid. These are Rick/ 123 and Virginia/456 . Either of these value pairs entered in TextBox1 and TextBox2 on the LoginPage.aspx page prompts the menu of hyperlinks in the ASPNETMenu.aspx page to appear. Any other value pairs transfer control to the BadMemberIDPassword.htm page.

Note  

A user can specify either a MemberID or a Password Session variable without designating the other Session variable. The application identifies this result as a not-logged-in condition instead of a bad- memberid-password one. This choice of functionality is not important in the current context because the discovery of either condition offers a chance to log in again.

 Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If no Session variables for MemberID or Password, redirect to NotLoggedIn.htm page If Session("MemberID") = "" Or Session("Password") = "" Then Response.Redirect("NotLoggedIn.htm") End If Authenticate login credentials If Session("MemberID") = _ "Rick" And Session("Password") = "123" Then ok ElseIf Session("MemberID") = _ "Virginia" And Session("Password") = "456" Then ok Else Response.Redirect("BadMemberIDPassword.htm") End If End Sub 

Figure 10-11 shows the two information Web pages in the sample application. Each page includes a statement about the problem and a link that points at the LoginPage.aspx where you can remedy the problem. Both pages in Figure 10-11 are standard HTML pages. You can create them in Visual Studio .NET by choosing Project, Add HTML Page. Then, change the pageLayout property setting to FlowLayout . After making that setting, you can edit text on the pages just as you would with any word processing document. Alternatively, you can create and manage the pages within a program that can create text messages with hyperlinks.

click to expand
Figure 10-11: A pair of informational pages in the login sample application
 


Programming Microsoft Visual Basic. NET for Microsoft Access Databases
Programming Microsoft Visual Basic .NET for Microsoft Access Databases (Pro Developer)
ISBN: 0735618194
EAN: 2147483647
Year: 2006
Pages: 111
Authors: Rick Dobson

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