- •Preface
- •Who Should Read This Book
- •Organization and Presentation
- •Contacting the Authors
- •Acknowledgments
- •Contents
- •Introduction
- •Why Microsoft .NET?
- •The Microsoft .NET Architecture
- •Internet Standards
- •The Evolution of ASP
- •The Benefits of ASP.NET
- •What Is .NET?
- •.NET Experiences
- •.NET Clients
- •.NET Services
- •.NET Servers
- •Review
- •Quiz Yourself
- •Installation Requirements
- •Installing ASP.NET and ADO.NET
- •Installing the .NET Framework SDK
- •Testing Your Installation
- •Support for .NET
- •Review
- •Quiz Yourself
- •Designing a Database
- •Normalization of Data
- •Security Considerations
- •Review
- •Quiz Yourself
- •Creating a Database
- •Creating SQL Server Tables
- •Creating a View
- •Creating a Stored Procedure
- •Creating a Trigger
- •Review
- •Quiz Yourself
- •INSERT Statements
- •DELETE Statements
- •UPDATE Statements
- •SELECT Statements
- •Review
- •Quiz Yourself
- •The XML Design Specs
- •The Structure of XML Documents
- •XML Syntax
- •XML and the .NET Framework
- •Review
- •Quiz Yourself
- •ASP.NET Events
- •Page Directives
- •Namespaces
- •Choosing a Language
- •Review
- •Quiz Yourself
- •Introducing HTML Controls
- •Using HTML controls
- •How HTML controls work
- •Intrinsic HTML controls
- •HTML Control Events
- •The Page_OnLoad event
- •Custom event handlers
- •Review
- •Quiz Yourself
- •Intrinsic Controls
- •Using intrinsic controls
- •Handling intrinsic Web control events
- •List Controls
- •Rich Controls
- •Review
- •Quiz Yourself
- •Creating a User Control
- •Adding User Control Properties
- •Writing Custom Control Methods
- •Implementing User Control Events
- •Review
- •Quiz Yourself
- •Common Aspects of Validation Controls
- •Display property
- •Type Property
- •Operator Property
- •Using Validation Controls
- •RequiredFieldValidator
- •RegularExpressionValidator
- •CompareValidator
- •RangeValidator
- •CustomValidator
- •ValidationSummaryx
- •Review
- •Quiz Yourself
- •Maintaining State Out of Process for Scalability
- •No More Cookies but Plenty of Milk!
- •Out of Process State Management
- •Review
- •Quiz Yourself
- •Introducing the Key Security Mechanisms
- •Web.config and Security
- •Special identities
- •Using request types to limit access
- •New Tricks for Forms-based Authentication
- •Using the Passport Authentication Provider
- •Review
- •Quiz Yourself
- •ASP.NET Updates to the ASP Response Model
- •Caching with ASP.NET
- •Page Output Caching
- •Absolute cache expiration
- •Sliding cache expiration
- •Fragment Caching
- •Page Data Caching
- •Expiration
- •File and Key Dependency and Scavenging
- •Review
- •Quiz Yourself
- •A Brief History of Microsoft Data Access
- •Differences between ADO and ADO.NET
- •Transmission formats
- •Connected versus disconnected datasets
- •COM marshaling versus text-based data transmission
- •Variant versus strongly typed data
- •Data schema
- •ADO.NET Managed Provider Versus SQL Managed Provider
- •Review
- •Quiz Yourself
- •Review
- •Quiz Yourself
- •Creating a Connection
- •Opening a Connection
- •Using Transactions
- •Review
- •Quiz Yourself
- •Building a Command
- •Connection property
- •CommandText property
- •CommandType property
- •CommandTimeout property
- •Appending parameters
- •Executing a Command
- •ExecuteNonQuery method
- •Prepare method
- •ExecuteReader method
- •Review
- •Quiz Yourself
- •Introducing DataReaders
- •Using DataReader Properties
- •Item property
- •FieldCount property
- •IsClosed property
- •RecordsAffected property
- •Using DataReader Methods
- •Read method
- •GetValue method
- •Get[Data Type] methods
- •GetOrdinal method
- •GetName method
- •Close method
- •Review
- •Quiz Yourself
- •Constructing a DataAdapter Object
- •SelectCommand property
- •UpdateCommand, DeleteCommand, and InsertCommand properties
- •Fill method
- •Update method
- •Dispose method
- •Using DataSet Objects
- •DataSetName property
- •CaseSensitive property
- •Review
- •Quiz Yourself
- •Constructing a DataSet
- •Tables property
- •TablesCollection Object
- •Count property
- •Item property
- •Contains method
- •CanRemove method
- •Remove method
- •Add method
- •DataTable Objects
- •CaseSensitive property
- •ChildRelations property
- •Columns property
- •Constraints property
- •DataSet property
- •DefaultView property
- •ParentRelations property
- •PrimaryKey property
- •Rows property
- •Dispose method
- •NewRow method
- •Review
- •Quiz Yourself
- •What Is Data Binding?
- •Binding to Arrays and Extended Object Types
- •Binding to Database Data
- •Binding to XML
- •TreeView Control
- •Implement the TreeView server control
- •Review
- •Quiz Yourself
- •DataGrid Control Basics
- •Binding a set of data to a DataGrid control
- •Formatting the output of a DataGrid control
- •Master/Detail Relationships with the DataGrid Control
- •Populating the Master control
- •Filtering the detail listing
- •Review
- •QUIZ YOURSELF
- •Updating Your Data
- •Handling the OnEditCommand Event
- •Handling the OnCancelCommand Event
- •Handling the OnUpdateCommand Event
- •Checking that the user input has been validated
- •Executing the update process
- •Deleting Data with the OnDeleteCommand Event
- •Sorting Columns with the DataGrid Control
- •Review
- •Quiz Yourself
- •What Is Data Shaping?
- •Why Shape Your Data?
- •DataSet Object
- •Shaping Data with the Relations Method
- •Review
- •Quiz Yourself
- •OLEDBError Object Description
- •OLEDBError Object Properties
- •OLEDBError Object Methods
- •OLEDBException Properties
- •Writing Errors to the Event Log
- •Review
- •Quiz Yourself
- •Introducing SOAP
- •Accessing Remote Data with SOAP
- •SOAP Discovery (DISCO)
- •Web Service Description Language (WSDL)
- •Using SOAP with ASP.NET
- •Review
- •Quiz Yourself
- •Developing a Web Service
- •Consuming a Web Service
- •Review
- •Quiz Yourself
- •ASP and ASP.NET Compatibility
- •Scripting language limitations
- •Rendering HTML page elements
- •Using script blocks
- •Syntax differences and language modifications
- •Running ASP Pages under Microsoft.NET
- •Using VB6 Components with ASP.NET
- •Review
- •Quiz Yourself
- •Preparing a Migration Path
- •ADO and ADO.NET Compatibility
- •Running ADO under ASP.NET
- •Early Binding ADO COM Objects in ASP.NET
- •Review
- •Quiz Yourself
- •Answers to Part Reviews
- •Friday Evening Review Answers
- •Saturday Morning Review Answers
- •Saturday Afternoon Review Answers
- •Saturday Evening Review Answers
- •Sunday Morning Review Answers
- •Sunday Afternoon Review Answers
- •What’s on the CD-ROM
- •System Requirements
- •Using the CD with Windows
- •What’s on the CD
- •The Software Directory
- •Troubleshooting
- •ADO.NET Class Descriptions
- •Coding Differences in ASP and ASP.NET
- •Retrieving a Table from a Database
- •Displaying a Table from a Database
- •Variable Declarations
- •Statements
- •Comments
- •Indexed Property Access
- •Using Arrays
- •Initializing Variables
- •If Statements
- •Case Statements
- •For Loops
- •While Loops
- •String Concatenation
- •Error Handling
- •Conversion of Variable Types
- •Index
Session 11—Validating User Input |
103 |
messages at the point on the page where the validation control is inserted. Additionally, the output can be streamed as HTML or in plain text. This is controlled by the display property of each control. The display property can be set to static, dynamic, or none.
By setting the display property to static, the validation control will allocate an appropriate amount of space on your Web page so that when the error message is displayed, the layout of the page doesn’t change.
By setting the display property to dynamic, the validation control will not reserve space on the HTML page for the error message. Therefore, when the error message is displayed, form elements may be moved around to accommodate the error message and thus disrupt the desired look of your form.
By setting the display property to none, no message will be displayed immediately next to the validated control. Why would you ever use this setting? In some situations you may choose to display all validation errors in a consolidated area of the page or in a single message box for the user. In this case you can use the ValidationSummary control to display a summarized list of all error messages rather than displaying them individually next to each control.
Type Property
When comparing values in controls, the values must be of the same type, and you typically will need to explicitly tell the validation control the types being compared. The following type property enumerators are valid: String, Integer, Double, DateTime, and Currency.
Operator Property
When comparing values, the options available for doing the comparison include:
Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.
These operator properties are relatively intuitive except for DataTypeCheck, which simply evaluates if the values being compared are of the same data type, for instance, that both are strings or integers.
Using Validation Controls
The following examples are all included in the Session 11 folder on the CD. We will look at a single example page for using each of the validation controls.
Let’s look at a page that captures basic user information such as the user’s name, e-mail address, password, age, and a subscription code that enables the user to subscribe to an online mailing list. Figure 11-1 illustrates the results of using the validation controls to validate required fields, meet regular expression conditions, and to validate field values and types.
104 |
Saturday Afternoon |
Figure 11-1 Use of validation controls
RequiredFieldValidator
The first thing that you will need to do is insure that the user has at least attempted to complete certain fields. In our example, the only required field is the Full Name field. In order to validate that a user enters information in the Full Name field, you simply insert a RequiredFieldValidator control next to the field you want to validate as shown in Listing 11-1.
Listing 11-1 Example of Using RequiredFieldValidator Control
<%@ Page Language=”vb” %> <HTML>
<HEAD>
<SCRIPT LANGUAGE=”VB” RUNAT=”server”>
Sub Page_Load(Source As Object, E as EventArgs) If Page.IsPostBack Then
lblTitle.Text = “Submit was successful”
Else
lblTitle.Text = “Leave the field blank and Submit”
End If End Sub
</SCRIPT>
</HEAD>
<BODY>
<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>
Session 11—Validating User Input |
105 |
<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>
<P>
Full Name
<ASP:TEXTBOX ID=”txtName” RUNAT=”SERVER”></ASP:TEXTBOX> </P>
<P>
<ASP:REQUIREDFIELDVALIDATOR
ID=”valReqName”
ERRORMESSAGE=”You Must Fill In The <B>Full Name</B> Field” RUNAT=”SERVER”
CONTROLTOVALIDATE=”txtName”
BACKCOLOR=”#FFFF80”
DISPLAY=”Static”>
</ASP:REQUIREDFIELDVALIDATOR>
</P>
<P>
<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>
</FORM>
</BODY>
</HTML>
The ControlToValidate property has been set to the id of the control you want to validate, in this case the txtName control. Next, set the ErrorMessage property to a string. In this case, we have added some additional html tags, <B> </B> tags, to provide some bold formatting around the error message. Finally, set the Display property to Static so that the page formatting will remain consistent, regardless if a message is displayed or not.
RegularExpressionValidator
Next, you need to validate the user’s e-mail address to make sure that it meets standard Internet e-mail naming conventions. You will do this by utilizing the
RegularExpressionValidator control.
A regular expression is a very flexible method of determining if a string value meets certain requirements in terms of its use of upperor lowercase letters, range of letters, number of characters, use of integers, mix of letters, special characters, or numbers as part of a string.
For example, in the sample registration page, we have created a regular expression to ensure that the user’s e-mail conforms to standard e-mail formats. This means that it will contain a series of numbers or letters followed by @ followed by another series of numbers or letters, followed by a period and a final series of numbers or letters.
The expression that tests if the user’s input conforms to this standard is set in the property validationexpression as shown in boldface in Listing 11-2.
Listing 11-2 Implementing RegularExpressionValidator Control
<%@ Page Language=”vb” %> <HTML>
<HEAD>
<SCRIPT LANGUAGE=”VB” RUNAT=”server”>
Sub Page_Load(Source As Object, E as EventArgs)
Continued
106 |
Saturday Afternoon |
Listing 11-2 |
Continued |
If Page.IsPostBack Then
lblTitle.Text = “Submit was successful”
Else
lblTitle.Text = “Enter an invalid email address and Hit the Submit
button”
End If End Sub </SCRIPT>
</HEAD>
<BODY>
<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>
<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>
<P>
Email Address
<ASP:TEXTBOX ID=”txtEmail” RUNAT=”SERVER”></ASP:TEXTBOX>
<ASP:REGULAREXPRESSIONVALIDATOR
ID=”valRegEmail”
ERRORMESSAGE=”Email needs to conform to <B>user@domain.com</B>” RUNAT=”SERVER”
CONTROLTOVALIDATE=”txtEmail” VALIDATIONEXPRESSION=”[\w-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+” BACKCOLOR=”#FFFF80”
DISPLAY=”Static”>
</ASP:REGULAREXPRESSIONVALIDATOR>
</P>
<P>
<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>
</FORM>
</BODY>
</HTML>
All of the remaining properties are very similar to those used for the RequiredField Validator control. The extensive flexibility of the RegularExpressionValidator enables you to quickly create custom validators for a wide range of validation routines such as:
Internet URL = http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
US Phone Number = ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
US Social Security Number = \d{3}-\d{2}-\d{4}
US Complex Zip Code = \d{5}(-\d{4})?
CompareValidator
The CompareValidator is self-explanatory. It is used to compare the value of a user control to another user control’s value or to a defined value. As illustrated in Listing 11-3, we are using the control to make sure that the second password entered by the user matches the first password entered.
Session 11—Validating User Input |
107 |
Listing 11-3 Using the CompareValidator Control
<%@ Page Language=”vb” %> <HTML>
<HEAD>
<SCRIPT LANGUAGE=”VB” RUNAT=”server”>
Sub Page_Load(Source As Object, E as EventArgs) If Page.IsPostBack Then
lblTitle.Text = “Submit was successful”
Else
lblTitle.Text = “Enter non-identical values and hit the Submit
button”
End If End Sub </SCRIPT>
</HEAD>
<BODY>
<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>
<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>
<P>
Password
<ASP:TEXTBOX ID=”txtPassword1” RUNAT=”SERVER” TEXTMODE=”Password”></ASP:TEXTBOX>
</P>
<P>
Re Enter Password
<ASP:TEXTBOX ID=”txtPassword2” RUNAT=”SERVER” TEXTMODE=”Password”></ASP:TEXTBOX>
<ASP:COMPAREVALIDATOR
ID=”valCompPassword”
ERRORMESSAGE=”The password fields must match each other” RUNAT=”SERVER”
CONTROLTOVALIDATE=”txtPassword2”
CONTROLTOCOMPARE=”txtPassword1”
BACKCOLOR=”#FFFF80”
DISPLAY=”Dynamic”>
</ASP:COMPAREVALIDATOR>
<ASP:REQUIREDFIELDVALIDATOR
ID=”valReqName”
ERRORMESSAGE=”You must complete values in both fields” RUNAT=”SERVER”
CONTROLTOVALIDATE=”txtPassword2”
BACKCOLOR=”#FFFF80”
DISPLAY=”Dynamic”>
</ASP:REQUIREDFIELDVALIDATOR>
</P>
<P>
<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>
</FORM>
</BODY>
</HTML>