Lab: Using Advanced Features
In this lab, you ll create an application that displays multiple pages using frames. This application lets users choose a background color for the application, compose and send mail from the server, and play a simple game. The Advanced Features application demonstrates these key features:
Testing browser capabilities to make sure a user s browser supports frames, cookies, and scripts
Saving cookies on the user s computer and then retrieving those cookies to set the background color for the application
Sending mail from the server using the MailMessage and SmtpMail objects
Displaying pages in frames and controlling the display of those frames from a Contents page
Optionally including Web forms that use the Win32 API, COM objects, and XML Web services
When complete, the Advanced Features application will appear as shown in Figure 7-14.
Figure 7-14. The Advanced Features application
Estimated lesson time: 45 minutes
Exercise 1: Check Advanced Feature Support
In this exercise, you ll create a default page for an application that checks to see whether the user s browser accepts cookies, can display frames, and runs scripts. If any of these features are not available, an appropriate message is displayed.A default page is a page that Internet Information Services (IIS) displays if the user navigates to the Web application directory without specifying a particular page to view. IIS uses the names Default.htm and Default.aspx for the default page unless you change them for the application through IIS.
To create a default page that checks the user s browser for advanced feature support
Add a Web form to your application named Default.aspx, and make that page the start page for your application.
Add the following Page_Load event procedure to the Web form:
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Create a flag to track if any advanced features are disabled. Dim bProceed As Boolean = True ' Check if browser accepts cookies. If Request.Browser.Cookies = False Then Response.Write("Your browser does not accept cookies.<br>" & _ "Change your browser's security settings allow cookies." & _ "<br><br>") bProceed = False End If ' Check if browser supports scripting. If Request.Browser.JavaScript = False Then Response.Write("Your browser does not support scripts.<br>" & _ "Update your browser software to the latest version.<br><br>") bProceed = False End If ' Check if browser supports VBScript. If Request.Browser.VBScript = False Then Response.Write("Your browser does not support VBScript.<br>" & _ "Install the latest version of Internet Explorer.<br><br>") bProceed = False End If ' If browser passes other tests, see if scripting is enabled by ' trying a script. If bProceed Then ' If scripts are disabled, the following line is ignored. ' Otherwise, it displays the frameset. Response.Write("<script>window.navigate('frameset.htm')</script>") Response.Write("Scripting is disabled due to your browser " & _ "security settings.<br> Change your browser's security " & _ "settings allow scripting.<br><br>") End If End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { // Create a flag to track if any advanced features are disabled. bool bProceed = true; // Check if browser accepts cookies. if (!Request.Browser.Cookies) { Response.Write("Your browser does not accept cookies.<br>" + "Change your browser's security settings allow cookies." + "<br><br>"); bProceed = false; } // Check if browser supports scripting. if (!Request.Browser.JavaScript) { Response.Write("Your browser does not support scripts.<br>" + "Update your browser software to the latest " + "version.<br><br>"); bProceed = false; } // Check if browser supports VBScript. if (!Request.Browser.VBScript) { Response.Write("Your browser does not support VBScript.<br>" + "Install the latest version of Internet Explorer.<br><br>"); bProceed = false; } // If browser passes other tests, see if scripting is enabled by // trying a script. if (bProceed) { // If scripts are disabled, the following line is ignored. // Otherwise, it displays the frameset. Response.Write("<script>window.navigate('frameset.htm')" + "</script>"); Response.Write("Scripting is disabled due to your browser " + "security settings.<br> Change your browser's security " + "settings to allow scripting.<br><br>"); } }
Add the following HTML content to the Web form:
<p>This Web application uses features that are either not available in your browser or are disabled through your browser's security settings. You cannot run this application until you update your browser as described above. Then click <a href="default.aspx">here</a> to try again.</p>
When the default page you created with the preceding steps loads, it checks each of the advanced features that a browser might or might not support. If there are problems using any of those features, the page displays a warning message, as shown in Figure 7-15.
Figure 7-15. Warning message
If no problems are encountered, the user never sees the default page. Instead, he or she is redirected immediately to frameset.htm, which displays the other pages in the application.
Exercise 2: Store User Information
In this exercise, you ll create a Web form that allows the user to select a background color. The form remembers the user s choice between sessions by saving the background in a cookie on the user s machine. When complete, the Web form will appear as shown in Figure 7-16.
Figure 7-16. The Background.aspx Web form
To create the Background Web form
Create a new Web form named Background.aspx.
Add a DropDownList server control to the Web form containing list items for some different background colors. This step is probably easier to do in HTML than in Design mode, because you can use cut and paste to create the list items quickly in HTML. The following HTML shows the definition for the DropDownList and its list items:
<asp:dropdownlist AutoPostBack="True" Runat="server" Width="128px"> <asp:ListItem Value="White">White</asp:ListItem> <asp:ListItem Value="Silver">Grey</asp:ListItem> <asp:ListItem Value="LightSteelBlue">Light steel blue</asp:ListItem> <asp:ListItem Value="Honeydew">Honeydew</asp:ListItem> <asp:ListItem Value="Azure">Azure</asp:ListItem> <asp:ListItem Value="Linen">Linen</asp:ListItem> <asp:ListItem Value="MintCream">Mint cream</asp:ListItem> </asp:dropdownlist>
Modify the Web form s <body> element to specify a background color using data binding from the DropDownList. The following HTML shows the changes to the <body> element:
<body bgColor="<%# drpBackground.SelectedItem.Value %>">
Add the following code to the Page_Load event procedure to check for a cookie, create the cookie if it does not exist, or set the background color from the cookie if it does exist. The Page_Load event procedure also performs data binding for the page to update the background color.
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' On first display If IsPostBack = False Then ' Check if cookie doesn't exist... If Request.Cookies("BackgroundColor") Is Nothing Then ' Create a cookie with the default background color. Dim cookBackground As New HttpCookie("BackgroundColor", "0") ' Set the cookie to expire in one day. cookBackground.Expires = DateTime.Now.AddDays(1) ' Add the cookie to the response object. Response.Cookies.Add(cookBackground) Else ' Get the user's background color from the cookie. drpBackground.SelectedIndex = _ CInt(Request.Cookies("BackgroundColor").Value) End If End If ' Update bound field to set background color Page.DataBind() End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { // On first display if (!IsPostBack) { // If cookie doesn't exist... if (Request.Cookies["BackgroundColor"] == null) { // Create a cookie with the default background color. HttpCookie cookBackground = new HttpCookie("BackgroundColor", "0"); // Set the cookie to expire in one day. cookBackground.Expires = DateTime.Now.AddDays(1); // Add the cookie to the response object. Response.Cookies.Add(cookBackground); } else { // Get the user's background color from the cookie. drpBackground.SelectedIndex = Convert.ToInt16(Request.Cookies["BackgroundColor"] .Value); } } // Update bound field to set background color Page.DataBind(); }
Add the following code to update the cookie through the Response object when the user selects a background color from the DropDownList:
Visual Basic .NET
Private Sub drpBackground_SelectedIndexChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Handles _ drpBackground.SelectedIndexChanged ' Record color selection in a cookie. Dim cookBackground As New HttpCookie("BackgroundColor") ' Set the cookie's value. cookBackground.Value = drpBackground.SelectedIndex ' Set the cookie's expiration. cookBackground.Expires = DateTime.Now.AddDays(1) ' Add the cookie to the Response object. Response.Cookies.Add(cookBackground) End Sub
Visual C#
private void drpBackground_SelectedIndexChanged(object sender, System.EventArgs e) { // Record color selection in a cookie. HttpCookie cookBackground = new HttpCookie("BackgroundColor"); // Set the cookie's value. cookBackground.Value = drpBackground.SelectedIndex.ToString(); // Set the cookie's expiration. cookBackground.Expires = DateTime.Now.AddDays(1); // Add the cookie to the Response object. Response.Cookies.Add(cookBackground); }
Exercise 3: Create a Mail Web Form
In this exercise, you ll create a Web form that allows you to compose and send a mail message from the server. When complete, the Mail Web form will appear as shown in Figure 7-17.
Figure 7-17. The Mail.aspx Web form
To create the Mail Web form
Create a new Web form named Mail.aspx.
Add text and server controls to the Web form, as shown in the following HTML:
<P> From: <asp:TextBox Runat="server" Width="376px"></asp:TextBox> <asp:RequiredFieldValidator ControlToValidate="txtFrom" Runat="server" ErrorMessage="Required field."> </asp:RequiredFieldValidator> <br> To: <asp:TextBox Runat="server" Width="377px"></asp:TextBox> <asp:RequiredFieldValidator ControlToValidate="txtTo" Runat="server" ErrorMessage="Required field."> </asp:RequiredFieldValidator> <br> Subject: <asp:TextBox Runat="server" Width="376px"></asp:TextBox> </P> <asp:TextBox Runat="server" TextMode="MultiLine" Width="432px" Height="208px"></asp:TextBox> <br> <asp:Button Runat="server" Text="Send"></asp:Button> <input type="reset" value="Cancel"> <br> <asp:literal runat="server"></asp:literal>
The RequiredFieldValidator controls in the preceding HTML are needed because the From and To properties of the MailMessage object must be set before the message can be sent.
Add the following Imports or using statement to the beginning of the Web form s code module so that you can use short names for members of the System.Web.Mail namespace:
Visual Basic .NET
Imports System.Web.Mail
Visual C#
using System.Web.Mail;
Add the following code to the butSend_Click event procedure to create a MailMessage object and to send the message from the server:
Visual Basic .NET
Private Sub butSend_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butSend.Click ' Create message. Dim msgMail As New MailMessage() ' Set message properties. msgMail.From = txtFrom.Text msgMail.To = txtTo.Text msgMail.Subject = txtSubject.Text msgMail.Body = txtMessage.Text ' Send message. SmtpMail.Send(msgMail) ' Clear To, Subject, and Message fields. txtTo.Text = "" txtSubject.Text = "" txtMessage.Text = "" ' Show success. litStatus.Text = "<p>Message sent.</p>" End Sub
Visual C#
private void butSend_Click(object sender, System.EventArgs e) { // Create message. MailMessage msgMail = new MailMessage(); // Set message properties. msgMail.From = txtFrom.Text; msgMail.To = txtTo.Text; msgMail.Subject = txtSubject.Text; msgMail.Body = txtMessage.Text; // Send message. SmtpMail.Send(msgMail); // Clear To, Subject, and Message fields. txtTo.Text = ""; txtSubject.Text = ""; txtMessage.Text = ""; // Show success. litStatus.Text = "<p>Message sent.</p>"; }
Add the following code to the Page_Load event procedure to clear the status message if the user cancels sending a message after successfully sending an earlier message:
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Clear status message. litStatus.Text = "" End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { // Clear status message. litStatus.Text = ""; }
Exercise 4: Create a Frame-Based User Interface
In this exercise, you ll create a frameset containing regions for a table of contents, a banner, and a body. You ll create a table of contents page that displays selected pages in the body frame and updates the banner frame using a script. When complete, the frameset will appear as shown in Figure 7-18.
Figure 7-18. The completed frameset at run time
To create the frame-based user interface
Create a new HTML page named Contents.htm.
Add the following hyperlinks to the Contents page:
<a href="Background.aspx" target="main" onclick="ShowBanner('Choose Background')">Choose Background</a> <br> <a href="Mail.aspx" target="main" onclick="ShowBanner('Send Mail From Server')">Send Mail</a> <br>
The hyperlinks shown in the preceding HTML provide a way to navigate to the other pages in the application and will display those pages in the main frame of the frameset you will create in the following steps.
Add the following script procedure to the Contents page:
VBScript
<script language="vbscript"> ' Updates the text in the banner frame. Sub ShowBanner(Message) ' Write text to banner frame. parent.frames("banner").document.write("<h2>" & Message & "</h2>") ' Close document so next write replaces the current text. parent.frames("banner").document.close End Sub </script>
JScript
<script language="javascript"> // Updates the text in the banner frame. function ShowBanner(Message) { // Write text to banner frame. parent.frames["banner"].document.write("<h2>" + Message + "</h2>"); // Close document so next write replaces the current text. parent.frames["banner"].document.close(); } </script>
This ShowBanner script displays a title in the banner frame of the frameset from each of the hyperlinks created in step 2.
Create a frameset in which to display the project pages. From the Project menu, choose Add New Item, and then select Frameset from the Templates list and name the file Frameset.htm. When you click Open, Visual Studio displays the Select A Frameset Template dialog box.
Select the Banner And Content frameset template and click OK. Visual Studio displays a new, empty frameset in the Design window.
Right-click in the leftmost frame, and select Set Page For Frame from the shortcut menu. Visual Studio displays the Select Page dialog box.
Select Contents.htm in the Select Page dialog box, and click OK to display the Contents page in the frame.
Make the frameset the start page for the application. In Solution Explorer, right-click the Frameset.htm file, and select Set As Start Page from the shortcut menu.
Exercise 5: Extra Practice Using Advanced Features
Exercises 1 through 4 walked you through some of the tasks you explored in this chapter. Now strike out on your own by attempting to complete the following tasks that extend the Advanced Features application:Add a Web form that displays information using a COM object from your system or the ShapesCOM object included on the companion CD.
Add a Web form that uses the SystemInfo Win32 API to display system information or select another unmanaged procedure to call through platform invoke.
Add a Window_OnLoad script to the Contents page to display a welcome message in the banner frame the first time the page is displayed.
Add the Guess A Number Web form created at the end of Lesson 4 to the Advanced Features application.
Create a cookie within the Mail Web form to remember the From address entered by the user.
Use the background color set on the Background Web form to change the background color displayed on each page in the frameset.
When you have finished, compare your results to the Advanced Features application included on the companion CD. Good luck!