
C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#
.pdf
Table 6-6: Properties of the ValidationSummary control
Property
Definition
the display mode on the page for the validation summary.
|
HeaderText |
|
Indicates |
|
|
|
|
|
|
|
|
|
the text |
|
|
|
|
heading to |
|
|
|
|
display at |
|
|
|
|
the top of |
|
|
|
|
the |
|
|
|
|
validation |
|
|
|
|
summary. |
|
|
|
|
|
|
|
ShowMessageBox |
|
Indicates |
|
|
|
|
|
|
|
|
|
whether |
|
|
|
|
the |
|
|
|
|
validation |
|
|
|
|
summary |
|
|
|
|
should be |
|
|
|
|
displayed |
|
|
|
|
in a client |
|
|
|
|
side |
|
|
|
|
message |
|
|
|
|
box. |
|
|
|
|
|
|
|
ShowSummary |
|
Indicates |
|
|
|
|
|
|
|
|
|
if the |
|
|
|
|
validation |
|
|
|
|
summary |
|
|
|
|
should be |
|
|
|
|
displayed |
|
|
|
|
inline. |
|
|
|
|
|
|
|
RunAt |
|
Specifies |
|
|
|
|
|
|
|
|
|
that this |
|
|
|
|
control |
|
|
|
|
runs on |
|
|
|
|
the server. |
|
|
|
|
||
|
The ValidationSummary control gathers and displays all ErrorMessage objects of |
|
||
|
validators of the same page. At the same time, any validator can display its own error |
|
||
|
message if you put the message in the control's inner content. This control allows you to |
|
||
|
group all of your messages in a convenient spot on the page in the style of your |
|
||
|
choosing. |
|
|
|
Look at the following code for the ValidationSummary control: <!-- Validation Summary Validator --> <asp:validationsummary
id="vsAll"
headertext="<i>The following errors occurred, please correct and try again.</i><br><hr>"
displaymode="list"

runat="Server">
</asp:validationsummary><br>
Put all of this together and use all the validation controls discussed so far with the ValidationSummary control by launching your browser and navigating to Summary.aspx, shown in Figure 6-17.
Figure 6-17: Validation summary control example 1
To demonstrate the ValidationSummary control, enter invalid values for each of the controls on the page. Keep in mind the validation rules for each control, because you want to make sure validation fails. Also, keep in mind the empty values are valid. After you have entered your values, click the Validate button. A screen similar to Figure 6-18 should appear.
Figure 6-18: Validation summary control example 2
As you can see, all the validation messages are displayed at the top of the page instead of inline after each control. The ValidationSummary control provides you with a clean way to display error messages and inform the user simultaneously. Whether you use inline validation or the ValidationSummary control is a matter of preference.

Validation Events
Up to this point, you have looked at the common properties of each control, learned how to wire them up on the page, and reviewed examples of the code running in the browser. The .NET Framework also exposes some common events for these controls that give the developer more options over the controls. Take a look at Table 6-7.
Table 6-7: Public Instance Events
DataBinding |
|
The event occurs when the control binds to a data |
|
|
|
|
|
source. |
Init
The event occurs when the control is initialized; this is the first event in the page lifecycle. The control can perform any initialization steps that are required for the Web page.
Load |
|
The event occurs when the control is first loaded to the |
|
|
Page object. |
PreRender
Unload
This event occurs when the control is about to render the HTML to the page. Controls should perform any pre-rendering steps before saving the view state and before rendering content to the Page object.
This event occurs when the control is about to be unloaded from memory. The control should perform any cleanup code in this Unload event.
The developer can also wire up these events to further control what happens when the control is loaded, unloaded, and so on from the page. These events would be used when the Web developer wants to initialize values before the page is loaded and to perform any cleanup code before the page is destroyed.
Multiple Validation Controls and Code Behind
In this section we are going to take a quick look at how we can use the Validator controls in a "Code Behind" Web page. The concept of "Code Behind" is new to .NET allowing us to separate our presentation HTML from the code logic. Figure 6-19 is displayed when the "Code Behind" example is executed in the browser.
Figure 6-19: Validation with code behind example 1
When using the validation controls, keep in mind that you should use the RequiredField validator along with the other controls to perform validation. As you saw in an earlier example using the CompareValidator control, blank passwords will match. If you had also used the RequiredFieldValidator control, the Password and Confirm fields would
need a value, and then those values would be compared before determining whether validation fails. Keep in mind that you can use more than one validation control with a specified control on the page.
Also, consider the differences in using clientversus server-side validation. With clientside validation, the user gets immediate feedback as to whether the value entered is valid. Using client-side validation also prevents a round trip to the server. However, when using server-side validation, you can move the code to the server and encapsulate your logic in a code behind page. For instance, your IsCardValid function could be moved to a code behind page to separate the presentation code from the business rules for performing validation.
Using Code
To demonstrate using validation from a code behind page, take a look at the following code fragment for Codebehind.aspx:
<%@ Page Language="C#" Src="codebehind.cs" Inherits="HungryMinds.Validation"%>
...
The page directive informs the ASP.NET parser to look in the Src attribute for the code to compile and in the Inherits attribute for the code behind class to inherit. In the preceding example, the Src attribute points to the following code behind page listing:
namespace HungryMinds {
using System;
using System.Web.UI.WebControls;
//--- we could also wire up the page_load, page_init, etc. events here also //--- inherit from the page class
public class Validation : System.Web.UI.Page {
//-- we need to reference the controls on the .ASPX page protected System.Web.UI.WebControls.TextBox CardNumber; protected System.Web.UI.WebControls.Label Message;
//--- this is our validation function that we set in the onServerValidate //--- property of the Custom Validator
protected void IsCardValid(object sender, ServerValidateEventArgs e) { //--- do some type of validation and return either true or false
if (e.value != "5555555555555555" )
e.IsValid = false;
else
e.IsValid = true;
}
protected void ShowMessage(Object sender, EventArgs e) {
String Msg;
if (Page.IsValid) {
if (CardNumber.Text.Length > 0) {
Msg ="<br>and your card number is " + CardNumber.Text;
Message.Text = Msg;
}
}
}
}
}
The first line in your code listing defines the namespace for this class. Next, you import the required class libraries: System and System.Web.UI.WebControls. You next define your class, which is inherited from the ASPX page. This class must be derived from the Page class in the .NET Framework. The next lines declare references to your controls on the ASPX page, the TextBox control and the Label control, which are defined in the System.Web.UI.WebControls class. You next define the functions used by the ASPX page. By using this implementation, you are able to separate the presentation code from the business logic code.
Summary
This chapter has explored each of the validation controls and provided examples of how to use each one with its commonly used properties. In this chapter, we covered: the RequiredFieldValidator control (which requires a field on the Web page to have value); the CompareValidator control (which allows us to compare values in one control to another control on the page, or a specified minimum and maximum value); the RangeValidator control (which allows us to compare the value of a control on the Web page to a range of values); and the RegularExpression Validator control (which we can use to validate a value against regular expressions). Also, we have the CustomValidator control, so that if none of the other validation controls fit our needs, then we can write our own validation routine. Finally, we discussed the ValidationSummary control, which allows us to accumulate all of the error messages from the other controls and display them as a list on the Web page.
As you can see, the .NET Framework provides Web developers with a great set of controls for doing page validation, instead of spending time writing validation code. This chapter also looked at how to implement code behind validation in ASPX pages to separate the presentation code from the business logic.
Chapter 7: Debugging ASP.NET Pages
Overview
In the previous chapters, you saw how to design and develop an ASP.NET application by using Web Forms. After designing and developing the application, it becomes critical to check it for the desired functionality.
While you are developing the application, the code editor catches most syntax errors. However, the errors that cannot be caught during application development cause the application to display error messages at run time. The errors that occur while the application is running are called run-time errors. On the other hand, if there is a problem in the programming logic, the application would run without errors, but it will not provide the desired functionality. Such errors are called logical errors. The process of going through the code to identify the root cause of an error in an application is called debugging.
This chapter introduces you to error handling and using the different debugging tools. You'll also learn the guidelines to writing good ASP.NET code.
Error Handling
ASP.NET provides rich support for handling and tracking errors that might occur while applications are running. When you run an ASP.NET application, if an error occurs on a server, an HTML error page is generated and displayed in the browser. While displaying error messages to users, ASP.NET takes care of the security issues by default, which makes it a reliable development tool for Web applications. ASP.NET ensures that no secure information, such as the remote machine compiler messages, configuration settings, filenames, stack traces, or source code, is revealed on the client
machine. When an error occurs, a generic error message, "Application Error Occurred," is displayed to users. To see the error details, one of the following needs to be done:
§Access the page again from the local server.
§Modify the configuration settings of the computer.
§Modify the configuration settings of the application's Web.config file to enable remote access.
Following is a sample of the Web.config file that you can modify:
<configuration>
<system.web>
<customErrors mode="Off" />
</system.web>
</configuration>
In this code, the <customErrors> tag has an attribute mode whose value is set to "Off". This value indicates that the remote users always see the original error message that is generated on the server.
Using custom error pages
As mentioned earlier, an HTML error page is displayed to a user in case an error occurs on a server. These error messages are secure, because they do not leak any secret information. However, these pages are not pretty to see. You can create custom error pages that can be displayed in case errors occur. For example, you can create an error page that displays the company's brand and some error messages that you want to display. To implement the custom error pages:
1.Create a Web page that you want to display as an error message page. This can be a page with an .html or .aspx extension.
2.Modify the Web.config file of your application to point to the custom page in the event of any error. The configuration settings, shown here, point to a file called MyError.aspx:
3.<configuration>
4.<system.web>
5.<customErrors mode="RemoteOnly" defaultRedirect="MyError.aspx"/>
6.
7.</system.web>
</configuration>
The mode attribute of the <customErrors> tag can take three values:
§On: Indicates that the custom error messages are always sent to users and that the detailed ASP.NET error page is never shown.
§Off: Indicates that only original error messages are sent to users even if a custom error page is available.
§RemoteOnly: Indicates that the custom error messages are displayed only to remote users accessing the site. If no custom error page is
available, remote users simply see a message indicating that an error has occurred.
When you modify the Web.config file to set the defaultRedirect attribute, the user is directed to the same custom error message irrespective of the type of the error. The type of the error is identified by the HTTP status code. You can specify specific error messages, such as "Page not found" or "server crash" for specific status codes, as shown in the following code:
<configuration>
<system.web>
<customErrors
defaultRedirect="http://host1/MyError.aspx" mode="RemoteOnly">
<error statusCode="500"
redirect="http://host1/pages/support.html"/>
<error statusCode="403"
redirect="http://host1/pages/access_denied.html"/>
</customErrors>
</system.web>
</configuration>
In this code, the error tag takes two attributes, statusCode and redirect. The statusCode attribute represents the value of the HTTP status code. The redirect attribute points to the error message file.
Tracking errors
In an earlier section, you saw how to display custom error messages to users in case errors occur on a server. In addition to displaying error messages to users, you should ensure that the administrators and developers are also able to track errors. This would allow them to identify and solve the problems associated with the code.
You can implement error tracking by handling the Application_Error event, an application-level event that is generated when an exception occurs during the processing of a Web request. The developers can use this event handler to obtain information, such as the page URL, the query string arguments, and cookie values. With this information, developers can write the code to track the problem or notify administrators and developers about the problem. The errors can be tracked by using the Event Log, sending e-mail to administrators, or writing to a database etc.
You can write to the NT Event Log by adding code in the Application_Error event handler in the Global.asax file of your application. You can write to the NT Event Log only after you've imported the System.Diagnostics namespace.
To implement error tracking, create a Visual Basic ASP.NET Web Application project. In this project, import the System.Diagnostics namespace in the Global.asax file:
Imports System.Diagnostics
Then, write the following code in the event handler for the Application_Error event (in the Global.asax file). This code demonstrates how to write an Event Log to track errors related to page URL. The Event Log is named MyLog.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Fires when an error occurs
'Retrieving the request URL
Dim pageUrl, message, logName as String
Dim event_log1 as New EventLog
pageUrl = Request.Path
'Creating error message to write to Event Log
message = "Page URL: " & pageUrl
'Specifying the Event Log name
logName = "MyLog"
'Creating Event Log if it does not exist
If (Not EventLog.SourceExists (logName)) Then
EventLog.CreateEventSource (logName,logName)
End If
'Writing to the log
event_log1.Source = logName
event_log1.WriteEntry ("Application error occured.
" + message,EventLogEntryType.Error)
End Sub
The application project contains a default Web Form, WebForm1.aspx. Rename this file to read "MakeEvent.aspx." Open the code behind file of this page and write the following statement to import the System.IO namespace:
Imports System.IO
Finally, in the Page_Load method, write the following code:
Sub Page_Load(Sender As System.Object, e As System.EventArgs) Handles
MyBase.Load
'Cause the event log entry to be made
throw New FileNotFoundException("test exception")
End Sub
When the MakeEvent.aspx page is executed, it generates an exception called
FileNotFoundException. This exception will fire the Application_Error event in the Global.asax file, which in turn will record a log of this error in the Windows Event Log. You will be able to see the errors using the Windows Event Log Viewer. To do so:
1.Select Start → Programs → Administrative Tools → Event Viewer.
2.Click the Event Log node to open the log. In this case, the name of the log is MyLog. You need to select the log file from the \winnt\system32\config folder. The file will be named MyLog.evt.
Using Debugging Tools
A chef, while demonstrating to his students the preparation of a new dish, makes sure that all the students write down the instructions or important points in their description manual so that they can easily refer to their manual if they encounter problems while preparing the dish on their own.
In the creation process, writing or drawing an outline plays a major role, because in case of a failure, you do not need to waste your time scratching your head. Instead, you can refer to the outline to solve the problem. In any kind of development, if the developer

starts logging the steps involved, debugging or finding errors and fixing them becomes very systematic and easy.
In programming, logging of the process usually refers to the ability of an application to incorporate the use of debugging, code tracing, performance counters, and event logs. In this section, you'll learn to use the different debugging tools.
Visual Studio .NET Debugger
Visual Studio has always provided the developer with very powerful GUI debuggers, and Visual Studio .NET is no exception to this tradition. The debugger built into Visual Studio
.NET is powerful and has a lot of new features compared to the debugger that was available with Visual Studio 6.0. Features that were previously available to the developers of Visual Basic only, like the Immediate window, are now common to all the
.NET languages. So, irrespective of the language that is used to create a Web application, the debugging tools remain the same, thereby delivering a better developer experience. You can use the Visual Studio .NET debugger to debug applications in one of the following two ways:
§By using the Debug menu
§By manually attaching the debugger to a running application
The debugger provides many options that allow you to check for any errors by running through the code step by step, skipping a code routine, or placing a breakpoint. A breakpoint marks a point in the code at which the application halts and enters a mode called Break mode. The different options available in this mode help a developer to trace the source of an error in an application.
Using the Debug menu
To debug an application, select Debug → Start. This option starts the application and attaches a debugger to it. The different Debug menu options are described in Table 7-1.
Table 7-1: Debug options
Option
Start
Continue
Description
Used to start the application execution.
Used to continue the application execution after the application enters a break mode.
Restart
Step Into
Used to restart the debugging process.
Used to transfer the control to a called procedure in the application.
Step Out |
|
Used to |

Table 7-1: Debug options
Option
Step Over
Run To Cursor
New Breakpoint
Description
transfer control from the called procedure (without proceeding further) back to the calling procedure.
Used to skip a called procedure.
Used to execute the code until it reaches the line where the cursor is placed, or until a breakpoint is reached, whichever occurs first.
Used to set a breakpoint on any line of code. Using the New Breakpoint dialog box (Ctrl+B) provides a lot of options, such as to specify additional conditions that must be met for a breakpoint to be hit, and when the breakpoint will be hit.
An alternative way to set a breakpoint is to click the left