Beruflich Dokumente
Kultur Dokumente
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
15
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 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.
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
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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
Localization
In Chapter 7, we introduced localization and used manual techniques to create the de-
fault (fallback) as well as the specific language resources. The Resource Manager will lo-
cate 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.
PART III
EXAM TIP The fallback locale is the locale that will be used when there are
no resources for the user’s locale.
Let’s take a look at how you can use a resource to build a localized ASP.NET applica-
tion. 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 Eng-
lish, 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 English
fr French
de German (Deutch)
sv Swedish (Svenska)
sw 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 United Kingdom
US United States of America
CA Canada
SE Sweden
SF Finland (Suomi-Finland)
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:54 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
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” cul-
ture 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 re-
source files—the name of the resource file will contain the culture code, and the com-
piler 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:
<resource>.<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 work-
ing 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 <resource>.resx. This file defines the de-
fault 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 re-
source 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.
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:54 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
Figure 15-1 The XML Designer with the default resource strings
PART III
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
Name Value
strings.en-CA.regx TxtWelcome Welcome to the ASP.NET application eh.
strings.fr-FR.regx TxtWelcome Bienvenue à m’application localisée!
strings.fr-FR.regx TxtClick Cliquetez ici!
strings.fr-FR.regx TxtHello Allô localisé monde!
strings.sv.regx TxtWelcome Välkommen till vår ASP.NET applikation
strings.sv.regx TxtClick Var snäll ock klicka här
strings.sv.regx TxtHello Hej på dig, lokaliserade Värld
Table 15-2 The Additional Resource Files
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:54 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
using System.Resources;
using System.Globalization;
namespace Locale
Now declare a protected member variable for the ResourceManager at the be-
ginning of the class definition for the project, as shown next. (We’ll discuss the
ResourceManager class a bit later in this section.)
Finally, add the instantiation code for the ResourceManager object in the
Page_Load() method of the codebehind module, as in this code segment:
At this point, you can start using the application. Add the following lines of code in-
side the form element of the HTML document, and you will have access to the localized
strings.
Running the application results in the display shown in Figure 15-2 (assum-
ing 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 con-
tinue 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 synchro-
nize 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 con-
trols. 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
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 ob-
ject'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 con-
trol. The event handler should look like this:
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
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 us-
ing 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.
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:55 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
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:
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
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 config-
ured 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 lo-
calized application.
Whenever you build applications whose users’ cultures may use different writing di-
rections for text, you’ll need to use a special property of the Web Form. The .NET Frame-
work 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.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
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]);
PART III
Button1.Text = locRM.GetString("txtClick");
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
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 con-
trol 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
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
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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
Validation Revisited
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
PART III
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 prop-
erty 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 valida-
tion controls in the Toolbox. For this example, you should validate that a name is en-
tered, 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.
ID ToolTip
TextBox txtName Enter your full name.
TextBox txtEmail Enter your e-mail address as name@domain.xxx.
TextBox txtPassword Enter your password.
TextBox txtPasswordRepeat Re-enter your password.
Button btnSubmit 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
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
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,
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:56 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
however, that there is no validation that the e-mail address is correctly formed, nor does
the application test that the password entries match.
PART III
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 con-
trols. 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.
Value
(ID) valPasswordRepeat1
ControlToCompare txtPassword
ControlToValidate txtPasswordRepeat
Display Dynamic
ErrorMessage The passwords do not match.
Operator Equal
Text *
Table 15-6 Properties for the CompareValidator
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 All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
15
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.
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 4:59:57 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
<asp:TextBox
id="txtEmail" style="Z-INDEX: 106; LEFT: 152px; POSITION: absolute;
TOP: 136px" runat="server"
ToolTip="Enter your email address as name@domain.xxx"
tabIndex="2">
</asp:TextBox>
<asp:RegularExpressionValidator
id="valEmail1" style="Z-INDEX: 112; LEFT: 328px; POSITION: absolute;
TOP: 136px" runat="server"
ErrorMessage="Email address must be in the format name@domain.xxx"
ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*
</asp:RegularExpressionValidator>
…
<asp:ValidationSummary
id="valSummary" style="Z-INDEX: 114; LEFT: 392px; POSITION: absolute;
TOP: 136px" runat="server">
</asp:ValidationSummary>
</form>
</body>
</HTML>
Error Handling
Have you ever written code that does not run? Code that inadvertently included op-
tional features (a.k.a. bugs) that you did not intend to be in the application? As a devel-
oper, 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 an-
ticipated 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 af-
ter a long period the screen displays information that we do not have permission to ac-
cess: "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
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
• 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.
<configuration>
<system.web>
<customErrors defaultRedirect="TheErrorPage.aspx" mode="On"/>
<system.web>
</configuration>
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 configu-
ration 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
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.
Table 15-7 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.
<configuration>
<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"/>
</customErrors>
<system.web>
</configuration>
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
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
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:
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 administra-
tor 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
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 Applica-
tion_Error() method can be seen in the following code segment:
…
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();
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 Applica-
tion 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
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
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 ser-
vices 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
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.
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
PART III
page to inform ASP.NET that you require tracing information for that page. This is the
directive:
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:
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 con-
tent 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
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
Now that you’ve seen the sections of the trace output, we need to look at how to in-
sert 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
Headers Collection This section lists the different headers that the client sent to the server
as part of the request for the page.
Server Variables This section is where the different variables available through the
Server object are displayed.
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:
The resulting output from this code segment is shown in Figure 15-11, which dis-
plays 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 direc-
tive 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
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
can be controlled on the application level through the Web.config configuration file
for the application. By setting the enabled attribute of the <trace> element, you can
turn on and off tracing. The following segment from the Web.config file illustrates the
setting:
<configuration>
<system.web>
<trace enabled="true" requestLimit="10" pageOutput="false"
traceMode="SortByTime" localOnly="true"/>
</system.web>
</configuration>
The attributes for the <trace> element are used to control how tracing will be con-
figured 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
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 out-
PART III
put by enabling application-level tracing: you need to remove the trace page directive
and add the <trace> element to the Web.config file. With the <trace> 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.
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 All-In-One
screen / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
15
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 han-
dling, 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 applica-
tion 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 in-
creases 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 be-
ginning 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
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
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
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
P:\010Comp\All-in-1\443-6\ch15.vp
Friday, August 23, 2002 5:00:00 PM
Color profile: Generic CMYK printer profile
All-In-One / MCAD/MCSD Visual C# .NET Certification All-in-One Exam Guide / Rempel & Lind / 222443-6 / Chapter
Composite Default screen
15
PART III
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