Ch15

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ch15 as PDF for free.

More details

  • Words: 9,304
  • Pages: 31
Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

15

CHAPTER

Web Forms and User Interface In this chapter, you will • Implement right-to-left and left-to-right mirroring of User Interface elements • Prepare culture-specific formatting • Localize the user interface • Implement navigation tools for the user interface • Validate user input • Implement error handling in the user interface • Configure custom error pages • Implement global.aspx, application, page-level, and page-event error handling • Implement online user assistance

The Importance of the User Interface First impressions count, and that’s never truer than when applied to the user interface (UI) of an application. If the user finds the UI hard to navigate or confusing, the user will always dislike the application, and no amount of change or redesign will bring that user back as a supporter. The best way to avoid UI problems is to follow some basic rules when designing the UI. These rules reflect a variety of concerns: • Put the user in control The user wants to be the one initiating an action, so the application should be as responsive and interactive as possible. After the user selects an action, that action should be easy to cancel. • Personalize the application Save the state of the user and the application so that when the user returns, the application will be in the same state. This is especially important if the application allows the user to change colors or layouts.

1 P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:53 PM

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

2 • Let the user manipulate the objects Let the user directly manipulate the objects that are used in the application using ToolTips and shortcut keys. Use very clear object models and metaphors. • Be consistent Be consistent in the use of colors, layout, and tools for controlling the application. Do not use different metaphors within an application; for example, don’t use the recycling bin to perform a hard delete (with no way of retrieving the item from the bin) in one part of the application and then as a true recycling bin (from which you can get back deleted items) in another part of the same application. • Keep it simple Simplify the layout of the form so the information is presented clearly in an uncluttered way. Use progressive disclosure to let the user drill deeper into the information at their own pace. • Make sure the application is forgiving Always give the user a way out from any situation they might have ended up in by their selections. For instance, if the user selects the command to delete the entire database, make sure there is at least one chance to reconsider that command before performing the deletion. You might even create an undelete function for those kinds of dead-end operations. Forgiveness also means that you should supply meaningful default values to minimize errors, and if an error occurs, the error-handling process should return the user to a meaningful place in the application with an explanation of the error. • Provide feedback Keep the user informed about what is happening in the application. If something will take time, communicate the progress of the process to the user. Never leave the user hanging, wondering what happened, wondering whether the system broke or the network disconnected. Always communicate, but do not use modal message boxes (alerts) that require action from the user; instead, use labels or status areas on the form to keep the user informed. • Pay attention to visual design Get a graphic designer to design the physical layout of the forms to ensure that the form clearly conveys the information without being confusing or overwhelming. • Provide user assistance Build documentation and help functions into the application. The assistance should be as topical as possible to help the user learn while using your application. • Provide localization Let the user view and use the application using the culture of the user’s locale. This way, numbers will be displayed in the user’s format, as will the string resources created for the application. The UI rules are many, and they are open to debate. The preceding points are based on the UI rules published by Microsoft for application developers. The MSDN (Microsoft Developer Network) has references for many UI design rules, but even so, there are times when the developer can, and will, break the rules in order to present

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:53 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

3 some specific information in a more effective way. In the following sections, we will look at the specifics of UI design as it relates to the 70-315 exam.

Localization In Chapter 7, we introduced localization and used manual techniques to create the default (fallback) as well as the specific language resources. The Resource Manager will locate the appropriate resource assembly based on the client’s settings; and if there is no resource for a particular locale, the Resource Manager will use the fallback locale, which is the locale that the web site was created with. The fallback locale is also called the default locale. The resource assembly for the fallback locale is located in the bin directory, while additional locales are added in subdirectories of the bin directory.

Let’s take a look at how you can use a resource to build a localized ASP.NET application. To begin this example, create an application called Locale on the localhost server. Instead of creating the resources manually, and adding satellite assemblies to the bin directory as we did in Chapter 7, we’ll look at how to use the resource editor in Visual Studio .NET to create the resources for a couple of languages. We happen to speak English, Swedish, German, and French between us, so those are the languages we will use, as well as some culture-specific resources. The International Organization for Standardization (ISO) has issued definitions of two-letter abbreviations to identify languages and countries. The following list contains just a small sample of the language codes; for a complete listing, see the MSDN library. en fr de sv sw

English French German (Deutch) Swedish (Svenska) Swahili

Languages like English, French, German, and Swedish are used in many different countries throughout the world, so the countries are referred to by the country codes. The following list gives the country codes for a few countries: UK US CA SE SF

United Kingdom United States of America Canada Sweden Finland (Suomi-Finland)

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:54 PM

PART III

EXAM TIP The fallback locale is the locale that will be used when there are no resources for the user’s locale.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

4 DE AT

Germany Austria

Now that you’ve seen the codes, let’s put the languages and countries together into cultures. The culture defines the language, data formats, calendar format, and so on, and it consists of the combination of the language and the country codes. The “en-UK” culture code is for English in the United Kingdom, and “sv-SE” is Swedish in Sweden, whereas “sv-SF” is Swedish in Finland. These codes are important when we build the resource files—the name of the resource file will contain the culture code, and the compiler will build the assembly for the resources by using the culture codes. When you create a resource file for the localized application, that file will have a name format based on this pattern: .<culture>.resx

The culture is either the language code (if the resource is valid for all cultures that use that language) or the culture code. The resource is the type of resource you are working with, and it will be string for strings, icon for icons, and so on. There is one very specific resource file that has the name .resx. This file defines the default or fallback resource, and it is the resource that will be used if there is no culture that matches the user’s settings. Getting back to the example project, we are going to create resources for the default (en), French France (fr-FR), English Canada (en-CA), and Swedish (sv) cultures. There are four steps in creating a resource file for a project: 1. Add a resource file to the project. Select Project | Add New Item. In the Template list, select the Assembly Resource File template, enter the name for the .resx file, and create the resource. The file will be added to the project, and the XML Designer will open. 2. Select Data in the Data Tables pane. 3. Position the cursor in the Name column of the empty row in the Data pane, and enter the appropriate information. To enter a new row, click in the Name column for the new row. Note that the type and mimetype information is not used with strings; it is only used with objects. 4. Save the .resx file. First, you need to create the default resource. Follow steps 1 through 4, giving the resource the name strings.resx and entering the information found in Table 15-1. The result should look like what you see in Figure 15-1. Table 15-1 Data for the Default String Resource

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:54 PM

Value

txtWelcome txtClick txtHello

Welcome to the localized Application. Please click me. Hello Localized World.

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

5

The XML Designer with the default resource strings

TIP

Use the most common language for the default resource.

Now you can repeat steps 1 through 4, using the data in Table 15-2. Once you’re done, save the four resource files. NOTE You can enter the accented characters by using the charmap.exe application.

After you have created the resource files, you need to create the code necessary for the application to access the resources. To do so, open the codebehind module, and import the System.Globalization and System.Resources namespaces. The import

strings.en-CA.regx strings.fr-FR.regx strings.fr-FR.regx strings.fr-FR.regx strings.sv.regx strings.sv.regx strings.sv.regx Table 15-2

Name

Value

TxtWelcome TxtWelcome TxtClick TxtHello TxtWelcome TxtClick TxtHello

Welcome to the ASP.NET application eh. Bienvenue à m’application localisée! Cliquetez ici! Allô localisé monde! Välkommen till vår ASP.NET applikation Var snäll ock klicka här Hej på dig, lokaliserade Värld

The Additional Resource Files

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:54 PM

PART III

Figure 15-1

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

6 entries should be placed before the namespace declaration, as in the following code segment: using System.Resources; using System.Globalization; namespace Locale

Now declare a protected member variable for the ResourceManager at the beginning of the class definition for the project, as shown next. (We’ll discuss the ResourceManager class a bit later in this section.) public class WebForm1 : System.Web.UI.Page { protected ResourceManager locRM; … }

Finally, add the instantiation code for the ResourceManager object in the Page_Load() method of the codebehind module, as in this code segment: LocRM = new ResourceManager("Locale.strings", typeof(WebForm1).Assembly);

At this point, you can start using the application. Add the following lines of code inside the form element of the HTML document, and you will have access to the localized strings.

<%=locRM.GetString("txtWelcome")%>



Running the application results in the display shown in Figure 15-2 (assuming an English locale). It demonstrates that it has access to the strings through the ResourceManager object. If you want to use the strings in the codebehind module, however, you need to first change the current thread to use the client’s locale. We’ll continue with this example and look at how to change the current thread's locale and how to programmatically set the text by using controls. Now you will change the current thread's locale to reflect the client settings, and then display localized information in the Web Form. The codebehind module is executed on the server while the client is running on a different computer; this process will synchronize the two. The first thing to do is create a button and a label in our Web Form, in Design view, and then clear the default content of the Text property for the Button and Label controls. You will also need to import the System.Threading namespace by inserting the following line at the beginning of the codebehind module: using System.Threading;

In order to set the locale for the current thread at the server, we need to use the locale setting from the client. To do so, the CurrentUICulture of the current thread on the

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:55 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

7

PART III

Figure 15-2

The first localized display

server must be set to the locale setting for the client that is available in the Request object's UserLanguages collection. The following two lines will perform that task and must be inserted at the beginning of the Page_Load() method: Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.UserLanguages[0]);

Then, in the codebehind module, add the following line of code to the end of the Page_Load() method: Button1.Text = locRM.GetString("txtClick");

Finally, you’ll need to create an event handler for the click event of the Button1 control. The event handler should look like this: private void Button1_Click(object sender, System.EventArgs e) { Label1.Text = locRM.GetString("txtHello"); }

Once you’re done, save the project and then build it by selecting Build | Build Locale. Run the project by pressing the F5 key. After you click the button, the display should be as shown in Figure 15-3, assuming that the client is set to English.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:55 PM

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

8

Figure 15-3

The locale application, using the English language

To test the application, you need to change the locale for your computer. The locale is controlled by the Control Panel’s Regional Settings. Select English (Canada) and notice that the welcome message has changed, but all the other strings are the same as they were for the English locale. That only the items defined for English (Canada) changed and all others stayed the same is an example of the fallback resource where we used the existing content from the default (strings.resx) resource for all resources that were not defined in the specific English-Canadian resource. Figure 15-4 shows the display using Swedish as the locale. The ResourceManager class is what makes this seamless change between locales possible. The following section will look at how the ResourceManager class works.

The Resource Manager Class The first thing we need to look at is how the resource files are compiled into one assembly. The name of the resource file is the key to how Visual Studio .NET handles the compilation—as we stated earlier, the format of the filename is .<culture>.resx.. The <culture> portion of the filename is used to build a hierarchy for languages and countries, and the file that has no <culture> in the name is the default or fallback culture. The ResourceManager class is what makes localization a convenient exercise rather than a chore. It gives us access to resources and provides the fallback when a resource does not exist. When the ResourceManager object is instantiated from the class, we provide information to it regarding the root name for the assembly created

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:55 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

9

PART III

Figure 15-4

The display using the Swedish locale

when the resource was compiled (in the example in the previous section, the root is Locale.strings) and the main assembly for the resource. In that example, we instantiated the ResourceManager using the following line: locRM = new ResourceManager("Locale.strings", typeof(WebForm1).Assembly);

Any call to the methods of the ResourceManager will now use the assembly located in the bin directory in the root of the application. The additional satellite assemblies for the different cultures are to be compiled into assemblies that use names that include the locale. To retrieve a resource from a resource assembly, you need to call methods like GetString() on the ResourceManager object. For example, to retrieve the resource stored under the name txtWelcome and assign it to a header on the page, you could use the following code: <%=locRM.GetString("txtWelcome")%>

The culture that the ResourceManager works with is the current culture of the thread that is executing. To ensure you use the culture of the client rather than the culture of the server, you need to ensure that you change to the culture according to the client. In the following example, we will use the Request object’s UserLanguages collection and select the first language in that collection by using Request

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:55 PM

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

10 .UserLanguages[0] as the parameter; this will change the culture and the UI culture (for graphical elements) of the current thread. The following two lines will do this: Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.UserLanguages[0]);

Once the culture is changed on the thread, that particular user’s session will be configured to use the culture of the user’s computer. One final note on localization: the namespaces that need to be imported are System.Globalization (which provides support for the ISO locale system), System.Resources (which provides support for resource assemblies), and System.Threads (which provides support for the threads you need to manipulate). Once imported, they will give access to all the features you need in order to support a localized application. Whenever you build applications whose users’ cultures may use different writing directions for text, you’ll need to use a special property of the Web Form. The .NET Framework exposes the dir property of the Web Form, which controls the text direction. This property is inherited by all server controls. The dir property can be set to “ltr” (left to right) or “rtl” (right to left)—“ltr” is the default. The final version of the example HTML module in this section is listed here. <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Locale.WebForm1" %> WebForm1

<%=locRM.GetString("txtWelcome")%>



The codebehind module for the localization example is as follows: using using using using using using using using using using using

System; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Web; System.Web.SessionState; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.HtmlControls; System.Resources;

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:55 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

11 using System.Globalization; using System.Threading; namespace Locale { public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Button Button1; protected ResourceManager locRM; private void Page_Load(object sender, System.EventArgs e) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); Thread.CurrentThread.CurrentUICulture = new CultureInfo(Request.UserLanguages[0]);

} override protected void OnInit(EventArgs e) { InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Load += new System.EventHandler(this.Page_Load); } private void Button1_Click(object sender, System.EventArgs e) { Label1.Text = locRM.GetString("txtHello"); } } }

EXAM TIP The UI thread must be changed to use the current culture of the client. The Resource Manager will retrieve the resource based on the thread’s current culture. Now that we have looked at how you can localize a Web Form, we will continue with the other issues of the UI, starting with page navigation.

Page Navigation When you build a form with multiple controls, you should make navigating the form as easy as possible, to the point of implementing the same shortcut-key scheme used in most Windows applications. Shortcut keys allow users to jump to a location or click a button by typing an ALT key sequence. The TAB key is used to move from control to control in a logical pattern. In this section, we will look at how to implement this type of navigation.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:56 PM

PART III

locRM = new ResourceManager("Locale.strings", typeof(WebForm1).Assembly); Button1.Text = locRM.GetString("txtClick");

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

12 Controls that receive input from the user’s keyboard have focus. Only one control at a time can have focus in a web Form. If a control can have focus, that control can also be accessed using a shortcut key by setting the AccessKey property for the control. In Figure 15-5 you can see the properties for a Button control, and the AccessKey property is set to F, indicating that the button can be clicked by the key sequence ALT-F. When you set the AccessKey property for a control, you should make sure that the user knows the shortcut-key sequence by adding a label with the information. You can either include instructions in the label, or you could underline the character that is set to the access key. The tab order of the form is set by setting the TabIndex of the controls. For example, on a form where you have 10 TextBox controls that are to be tabbed through from control 1 to 10, you would set the TabIndex of control 1 to 1, control 2 to 2, and so on to control 10, which would have its TabIndex set to 10. Designing the tab order correctly is of paramount importance for the proper functioning of the form. Set the TabIndex on all controls, and test to ensure that the resulting feel is correct for the application.

Figure 15-5 Setting the AccessKey property

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:56 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

13

Validation Revisited

ID

ToolTip

TextBox TextBox TextBox TextBox Button

txtName txtEmail txtPassword txtPasswordRepeat btnSubmit

Enter your full name. Enter your e-mail address as [email protected]. Enter your password. Re-enter your password. Click to submit information. (Note: Set the Text property to “Submit”.)

Table 15-3

The Properties for the Web Form

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:56 PM

PART III

In Chapter 12, we looked at the validation controls from the code point of view. These validation controls allow us to validate user input. Now we will build a small form using the IDE so you can see the ease with which we can build quite complicated forms. Before you validate the data in the control, however, you need to make sure the user knows what information is needed in the fields of the form. And as usual, there are two possible solutions. The first is to add labels to the form identifying the information needed, and the second is to create ToolTips that will pop up when the user hovers the mouse pointer over the field. Including labels of instructional text on the form makes the form look very cluttered and hard to understand. The ToolTip method is a very streamlined way of communicating with the user. Every control has the ability to use ToolTips, and they can be set both at design and run time. ToolTips are implemented by adding the informative text to the ToolTip property of the control. Once you have indicated in the ToolTips what you expect the user to enter, you can proceed to validate the information received (or to trap missing entries) by adding validating controls to the form. In this section, we will build an example application in which users will enter their name, e-mail address, and password into a Web Form. To start off, create a project called ValidationExample and use the localhost server. The Web Form should look like the one shown in Figure 15-6 when the fields are added—you will need to add four labels, four text boxes, and a button. The labels are there to give the basic data requirements, and they have default IDs. The text boxes should have their properties set as listed in Table 15-3. You can use the Format | Align menu to line up the controls with either the left or right edge. For the txtPassword and txtPasswordRepeat controls, set the TextMode property to Password to hide the entered characters. At this point, there is no validation on the form. To add it, you need to use the validation controls in the Toolbox. For this example, you should validate that a name is entered, that the e-mail address is correctly formed, and that the two entries for the password are equal. The validation controls should be placed to the right of the controls they validate. Add the RequiredFieldValidator control from the Toolbox, and set the properties according to Table 15-4.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

14

Figure 15-6

The finished ValidationExample form

After adding the RequiredFieldValidator controls, you can run the application by pressing the F5 key. Check that you are forced to enter data in every field. Note,

ID

ControlToValidate

Text

ErrorMessage

valName valEmail valPassword valPasswordRepeat

txtName TxtEmail TxtPassword txtPasswordRepeat

* * * *

Your name is required. The e-mail address is required. You must enter a password. Re-enter the password for verification.

Table 15-4

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:56 PM

The Properties for the Validation Controls

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

15 Value

(ID) ControlToValidate ErrorMessage Text ValidationExpression

Table 15-5

valEmail1 txtEmail E-mail address must be in the format [email protected]. * (Select Internet E-mail Address from the list. The property will be set to the regular expression that validates an Internet e-mail address.)

Properties for the RegularExpressionValidator Control

Value

(ID) ControlToCompare ControlToValidate Display ErrorMessage Operator Text Table 15-6

valPasswordRepeat1 txtPassword txtPasswordRepeat Dynamic The passwords do not match. Equal *

Properties for the CompareValidator

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:57 PM

PART III

however, that there is no validation that the e-mail address is correctly formed, nor does the application test that the password entries match. In order to validate the format of the e-mail address, you can use a RegularExpression Validator control. Start by adding a RegularExpressionValidator to the right of the valEmail control. Set the properties for the validation control as listed in Table 15-5. The validation of the two password fields will be handled by a CompareValidator control. To set this up, drag a new CompareValidator control to the right of the valPasswordRepeat control, and set the properties as in Table 15-6. You can now save and test the form (F5). As you can see, the red asterisk (*) indicates that there are errors or missing information in the fields; so while this application is very functional, you still do not see the error messages you entered into the validation controls. To display the error messages, you can use a ValidationSummary control that will take all the error outputs from the validation controls and display them in a bulleted list. To do so, simply drag a ValidationSummary control to the right of the current controls on the form. That’s all! You can change the look of the summary by changing the font and the style of the list, but the wiring is already done. Figure 15-7 shows the application with a malformed e-mail address.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

16

Figure 15-7

The validation application with a malformed e-mail address

Some of the HTML code for the validation example is listed here. We have not repeated all the controls in this sample—for the full code listing, see the Chapter 15 directory on the CD. <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="ValidationExample.WebForm1" %> WebForm1

Registrations


Name:

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:57 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

17 * *


Error Handling Have you ever written code that does not run? Code that inadvertently included optional features (a.k.a. bugs) that you did not intend to be in the application? As a developer, you know that errors are in the nature of software. In Chapter 4, we looked at exception handling; and in Chapter 9, we covered the art of debugging. In this section, we will look at how to gracefully inform the user when things happen that you did not intend, or that result from missing resources, such as a database server being offline or a network router being down. These types of runtime errors were not anticipated when the application was designed, and you must deal with them. One of the most annoying errors we have seen is when connecting to a site, and after a long period the screen displays information that we do not have permission to access: "MSOLEDBSQL.1;Data Source=Coporate1;Initial Catalog=Findata; User id=sa;Password=;". As users, we should never be given that information—if

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:57 PM

PART III



Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

18 we were less than ethical, that would be enough information to start a data-theft attempt. On the other hand, if the user is not a computer professional, the information is very confusing and doesn’t allow the user to gracefully exit from the page. The errors in an application can be classified into three broad groups: syntax errors, logical errors, and system errors. • Syntax errors These are the result of typing and spelling mistakes and of using objects in assemblies that are not referenced in the web application (no checking at design time). Syntax errors are found when the application will not compile, and they are usually trivial to repair. • Logical errors These are usually hard to find. They are rooted in the logic of the program and can be the result of bad input data that wasn’t validated, or they can be the result of the processing making an erroneous assumption, resulting in incorrect output. To solve logical errors, you need to use tracing and other general debugging techniques, as covered in Chapter 9. • System errors These are the errors that you cannot foresee. They are usually generated by ASP.NET and can be caused by missing resources or general failures in ASP.NET or even in the Common Language Runtime. We’ll focus on this type of errors in this chapter because the way we trace in a web application is different from the general debugging techniques that were covered in Chapter 9.

Custom Error Pages The default error pages displayed from a web server can be rather cryptic; in this section, we will look at techniques to customize those error pages. The first technique we will look at sends the user a custom error page with pertinent information for the error that occurred. In order to change the default error page behavior to display a customized page, you need to make an entry in the Web application’s configuration file (Web .config) in the customErrors element, as shown in the following code segment: <system.web> <customErrors defaultRedirect="TheErrorPage.aspx" mode="On"/> <system.web>

To edit the Web.config file, double-click on it in the Solution Explorer. The default Web.config file that is generated in Visual Studio .NET contains many more configuration entries than customErrors—we will look at those entries in Chapter 17. The attributes for the customErrors element are listed in Table 15-7. Now that you have the application displaying a customized error page, you need to create that error page. The page in this example is named TheErrorPage.aspx, and it is added to the project by selecting Project | Add Webform.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:57 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

19 Description

defaultRedirect mode

<error>

Attributes for the customErrors Element

EXAM TIP

The value for the mode attribute is case sensitive.

The error page should give the user the nontechnical information about the error and direct the user how to recover from or retry the operation that failed. Figure 15-8 shows one possible error page with some feedback for the user. The customErrors element gives us full control over all the error pages we might need to build for our application. For example, the “403 Forbidden,” “404 Not Found,” and “500 Internal Server Error” errors could be mapped to custom error pages using the following entry in the Web.config configuration file. <system.web> <customErrors defaultRedirect="TheErrorPage.aspx" mode="On"> <error statusCode="403" redirect="ServerSupport.aspx"/> <error statusCode="404" redirect="NotFoundError.aspx"/> <error statusCode="500" redirect="NoAccess.aspx"/> <system.web>

You can configure custom error pages for all the defined HTML error codes by adding one entry for each code. If an error occurs that does not match the error codes, the user will be redirected to the defaultRedirect page.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:57 PM

PART III

Table 15-7

Holds the URL for the page the user will be redirected to for all errors that have no <error> element inside the customErrors element. Specifies when the redirected error page should be used. The browser that is used controls how the error messages are displayed; the browser running on the local development server will by default receive the detailed error page, while any remote client will receive a short error page. The mode attribute can be set to On, Off, or RemoteOnly to change that behavior. When set to On, the custom error page is sent to both local and remote clients; Off turns off the custom redirections; RemoteOnly sends the custom page to remote clients, while the local client gets the detailed error page from ASP.NET. Identifies optional child elements that describe the redirection page for specific errors. The <error> element has two attributes: statusCode, which is the HTTP status code that the error will respond to, and redirect, which is the URL of the error page the user will be redirected to.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

20

Figure 15-8

One error page

Page_Error() When unhandled errors occur, they can be trapped on the page by implementing the Page_Error() method. The Page_Error() method is called when the Error event is raised by the Page object. An example of the use of the Page_Error() method can be seen in the following code segment: private void Page_Error(object sender, System.EventArgs e) { string str = "" + "

" + Request.Url.ToString() + "

" + "<pre>" + Server.GetLastError().ToString() + "
"; Response.Write(str); Response.Flush(); Server.ClearError(); // Clear the error to ensure it does not bubble }

The event handler must be registered in the InitializeComponent() method, as in the following code segment: private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); this.Error += new System.EventHandler(this.Page_Error); }

Event Log Windows has a very valuable feature in the Event Log. This feature can be used to save tracking information from your application that can then be viewed by the administrator of the server to find if there have been any errors that need to be resolved. The Event

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:58 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

21

… using System.Diagnostics; … protected void Application_Error(Object sender, EventArgs e) { // Create the message to be stored in the Applications Log string strMessage = "\nURL:\n http://localhost/" + Request.Path + "\nMESSAGE:\n " + Server.GetLastError().Message + "\nSTACK TRACE:\n" + Server.GetLastError().StackTrace; Server.ClearError(); //Check if the event log exists, if not create it string strLogName = "Application"; if (!EventLog.SourceExists(strLogName)) { EventLog.CreateEventSource(strLogName,strLogName); } // Create the Log object and insert the message EventLog logAppl = new EventLog(); logAppl.Source = strLogName; logAppl.WriteEntry(strMessage, EventLogEntryType.Error); }

NOTE The \n sequence used in the strings in the preceding code segment is the escape sequence for a newline character. Its use will make the message more readable.

In the code example, you need to build a message entry to be added to the Application Log, and that needs to be followed by a check to see if the log is already created on the computer—if not, you need to create it using this line: EventLog.CreateEventSource(strLogName,strLogName);

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:58 PM

PART III

Log consists of multiple physical logs that are viewed through the Event Viewer. To open the Event Viewer, select Start | Programs | Administrative Tools | Event Viewer. The Event Log has three default views: System Log, Security Log, and Application Log. Some servers might have more logs, depending on the installed products. The System.Diagnostics namespace provides the classes that write to the Event Log. You can write events into the log for every possible reason, but that would fill the log with lots of messages that might not be important. In the web application, however, there is an Application_Error() method that will execute when there are unhandled errors in any of the pages of the application, and these are the errors you should be sure to add to the log. The Application_Error() method is defined in the global configuration file for the application, global.asax. It is one of many features of the global.asax file, and you will learn more about this file in Chapter 17. In order to write information to the Event Log, start by importing the System .Diagnostics namespace into the global.asax file. The code for the Application_Error() method can be seen in the following code segment:

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

22 The final step is to write the entry to the Event Log by using the WriteEntry() method of the EventLog object. The text you include in the message should be descriptive, and use as full a description as possible. The Windows operating system adds a stock header to the Event Log entry, which can be seen in Figure 15-9.

Page-Level Tracing To debug ASP.NET applications, and in particular, debug client user interfaces, you need to make use of the tracing facility. This facility has greatly improved the debugging services compared to what was available for the ASP environment. ASP debugging was not the most developer-friendly activity to undertake—debugging was a chore, and trying to get information from the running system entailed creating code that looked like this: if (DEBUG == true) { Response.Write("x = " + pointX + ", y = " + pointy); }

The value of the global variable DEBUG determined what the output would be. Then we had to thread through the code to locate the problem spot, which was not very much Figure 15-9 The message written into the Event Log

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:58 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

23 fun. And if you forgot to set DEBUG to False, the debug information ended up on the client systems. EXAM TIP If you are given the option to use global DEBUG variables and Response.Write() calls, you know they are referring to the previous version and that these are wrong answers.

<%@ Page Trace="true" %>

EXAM TIP The Trace directive overrides the trace setting for the application in the Web.config file.

In order to look at what is returned from the trace feature, we built a Web Form. The following code is all that is needed: <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Tracer.WebForm1" trace="True"%> WebForm1





Create this application, and then save and build it. Run it by pressing F5, and after a short delay you will be presented with the information shown in Figure 15-10. The end result of turning on tracing is that the web server produces the normal content of the Web Form (the TextBox and Button) plus a large number of sections that give us information about the page and the processes on that page. The sections in the trace output are listed in Table 15-8.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:58 PM

PART III

In ASP.NET, we have a new way of debugging our applications. Tracing does away with the hard-coded DEBUG testing, and the consequent runtime errors that make it even harder to get a page working properly. The trace feature provides a large number of information points for the page, including performance data, server variables, and any messages the developer has added to the page. To use page-level tracing, you need to add one page directive at the top of the web page to inform ASP.NET that you require tracing information for that page. This is the directive:

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

24

Figure 15-10

The output from the trace

Now that you’ve seen the sections of the trace output, we need to look at how to insert messages into the trace log. There are two methods that can be used to insert custom messages into the Trace Information section. Trace.Write(); Trace.Warn();

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:59 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

25 Description

Request Details

Trace Information

Control Tree

Cookies Collection

Server Variables Table 15-8

The Sections of the Trace Output

Both methods insert information into the log, but the Trace.Warn() method inserts messages in red, while Trace.Write() inserts messages in black. Expanding on the previous example, we will implement an event handler for the click event of the Button control. The following code will write information into the Trace Information section: private void Button1_Click(object sender, System.EventArgs e) { // We will insert some information into the trace log when the Button is clicked int i = 42; Trace.Write("TestCategory","i is initialized to " + i.ToString()); if (12 < 42) { Trace.Warn("ErrorCategory", "Attempt to change the universal answer!"); } }

The resulting output from this code segment is shown in Figure 15-11, which displays the Trace Information section of the trace output. Page-level tracing is very powerful, and all you need to do is set the trace page directive to True for the trace to be generated, or to False to turn off the trace. The trace option

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 4:59:59 PM

PART III

Headers Collection

This section deals with the client’s request for the page, and includes information such as the session ID for the current session, the request type (GET or POST), the date and time of the request, and the encoding of the request and response. This is the section where trace information, as well as any messages we added to the page, will be presented. The display can be used to determine the performance of the server for this page request, as well as to see the order of the page generation. This section displays the inheritance of the controls on the page (Page is the root), as well as the control IDs, type, and size of the view state. This section contains information about the cookies collection that is attached to the web page. This section lists the different headers that the client sent to the server as part of the request for the page. This section is where the different variables available through the Server object are displayed.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

26

Figure 15-11

Output from the page-level trace

can be controlled on the application level through the Web.config configuration file for the application. By setting the enabled attribute of the element, you can turn on and off tracing. The following segment from the Web.config file illustrates the setting: <system.web>

The attributes for the element are used to control how tracing will be configured for the web site. The attributes are described in Table 15-9. EXAM TIP In order to get tracing only when testing from the web server, set the localOnly attribute to True.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

27 Attribute

Description

enabled requestLimit pageOutput

Determines whether tracing is on by default on the site Sets the total number of trace requests to keep for offline viewing Specifies whether the trace should be output on the screen as well as kept for offline viewing Determines the order of the output Determines whether only requests from http://localhost should be traced

traceMode localOnly Table 15-9

The Attributes of the Element

Figure 15-12

The application-level trace output

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

PART III

In the previous example, we used tracing at the page level: all the tracing information is presented as part of the page. There is a second option on how to present the trace output by enabling application-level tracing: you need to remove the trace page directive and add the element to the Web.config file. With the element’s attributes set to enabled="true" and pageOutput="false", the tracing is still taking place, but the output is stored on the web site and can be made available through the Trace.axd handler. In Figure 15-12 you can see the resulting Trace.axd output.

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

28

Summary In this chapter, we have looked at a number of topics that center on the user and the user interface. Although it is easy to say that localization is the most important aspect of this chapter, there are equally compelling arguments that the honor belongs to error handling, or to validation. We think they are equally important. Using validation to ensure that the data received from the user has the right format is only prudent, as is the use of error handling to communicate any problem to the user. Building a localized application will cost some extra development time up front, but the payback will easily offset that cost in the end. The topics of validation and error communication fall under the heading of human engineering. Always test your design on a target group to make sure that the layout and communications elements are clear and that the design isn’t cluttered. There is one element of localization that we have not touched on in this book, mainly because it is a topic that is not included in the exam. The use of resources increases object reuse and lowers the likelihood of problems with the application. It also lowers the overall cost of development. The resources are defined and created at the beginning of the project, and then are reused through the application. The approach to localization commonly used is to create the resources for the default locale (fallback), and use that locale for the initial application release. As the need for additional resources becomes apparent, add the locales one at a time, creating the base language resources first, and adding cultures as needed. The next chapter will deal with the features in ASP.NET and Visual Studio .NET that gives us the ability to connect to databases and work with that data. We will see the built-in components as well as hand-coded ADO.NET applications.

Test Questions 1. What property is used to control how the user can press ALT-F to set the focus to a control? A. AccessKey B. ControlOrder C. TabOrder D. TraceOrder 2. You have created a localized web application that supports English, French, German, and Spanish. After building the resource files, you code all the strings to come through the ResourceManager.GetString() method. You test the application by using the browser on your development computer, and as you switch languages in the Regional Settings, everything functions as expected. After deploying the application, you receive a message from a client saying that the application does not change when the client accesses it with a computer configured to use the French locale. You need to fix the application. What will you do?

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

29 A. Rebuild the resource assembly. B. Add code to change the current thread’s culture to the user’s culture. C. Add code to change the location of the resource assembly. D. Instruct the user to upgrade to a newer browser. 3. What is used to validate complex string patterns like an e-mail address? A. Extended expressions. B. Regular expressions. C. Irregular expressions. D. Basic expressions. A. English. B. Swedish. C. User’s setting. D. Neutral. 5. What namespace is needed for Event Log support? A. System.Event B. System.Diagnostics C. System.EventLog D. System.Diagnostics.Event 6. What property controls whether the text in a TextBox control is displayed in clear text or as a collection of * characters? A. PasswordCharacter B. Hide C. Encrypt D. TextMode 7. You need to customize the error messages from your web application. What file will you modify to customize the error messages? A. Web.config B. Error.config C. Application.config D. global.asax 8. What property is set in order to display the text in reverse flow order? A. rtl B. ltr

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

PART III

4. What is the default language for the fallback culture?

Color profile: Generic CMYK printer profile Composite Default All-In-One screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide

30 C. dir D. reverse 9. You have configured custom error pages for your application. When you test the pages from a co-worker’s computer, they display properly, but when displayed in your browser on the development computer, they display incorrectly. What will you do to correct the display of the error pages on your computer? A. Install Internet Explorer 6.0. B. Change the mode attribute to localhost in the Web.config file. C. Change the mode attribute to RemoteOnly in the Web.config file. D. Change the mode attribute to On in the Web.config file. 10. After adding messages to the trace log, you need to locate the output. What section contains the messages a developer has added to the trace log? A. Trace Information. B. Control Tree. C. Cookies. D. Headers Collection. E. Server Variables. 11. What file would you modify to implement application-wide error processing for all unhandled errors? A. Web.config B. Error.config C. Application.config D. global.asax 12. What property is used to control the order in which the controls are accessed? A. AccessKey B. ControlOrder C. TabIndex D. TraceOrder 13. How do you enable tracing? A. Set the Trace property of the Web Form to True. B. Set the Trace property of the Server object to True. C. Set the Session variable Trace to True. D. Set the Applications variable Trace to True.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

Color profile: Generic CMYK printer profile Composite Default screen All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter

15

Chapter 15: Web Forms and User Interface

31 14. What control is used to validate that two fields are equal? A. RequiredFieldValidator B. RegularExpressionValidator C. CompareValidator D. The equals() method of the field. 15. What method is used to insert a highlighted entry in the trace output? A. Trace.Write() B. Trace.HighLight() C. Trace.Error()

Test Answers 1. A. 2. B. 3. B. 4. D. 5. B. 6. D. 7. A. 8. C. 9. D. 10. A. 11. D. 12. C. 13. A. 14. C. 15. D.

P:\010Comp\All-in-1\443-6\ch15.vp Friday, August 23, 2002 5:00:00 PM

PART III

D. Trace.Warn()

Related Documents

Ch15
May 2020 7
Ch15
November 2019 21
Ch15
May 2020 7
Ch15
October 2019 21
Ch15
November 2019 15
Ch15
June 2020 7