Build Your Own ASP.NET 3.5 Website Using C# & VB (41 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
7.37Mb size Format: txt, pdf, ePub

stack
of your program. The call stack is the list of methods that are being executed.

So, if method A calls a method B, which in turn calls method C, the call stack will

be formed of these three methods, as Figure 5.45 illustrates.

Licensed to [email protected]

Building Web Applications

223

Figure 5.45. A simple call stack

In this scenario, an exception that’s raised in method C can be handled within the

same function, provided the offending code is inside a Try/Catch block. If this isn’t

the case, the exception will propagate to method B, which also has the opportunity

to handle the exception, and so on. If no method handles the exception, it will be

intercepted either by the Visual Web Developer debugger or the ASP.NET runtime.

In the Try-Catch-Finally construct, both the Finally and Catch blocks are optional.

You can use only the Try and Catch blocks if there’s no need for a Finally block;

you might use only Try and Finally blocks if you want your code always to perform

a particular action when an exception is thrown, but you want the exception to

propagate up the call stack.

In more complex scenarios, you can use more layers of error handling. In these

scenarios, you’ll want to handle the error partially in the place in which it occurred,

but you’ll still want to let it propagate so that the upper layers take note of it, and

perform further processing. Exceptions are thrown using the Throw keyword (throw

in C#), like so:

Visual Basic

Try


code block…

Catch ex As Exception


code block…

Throw ex

End Try

Licensed to [email protected]

224

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

C#

try

{


code block…

}

catch (Exception ex)

{


code block…

throw ex;

}

If an error is thrown in the Try block, we can use the Catch block to optionally execute some code and then Throw the exception again so that it’s caught higher up the stack. We could modify our array example to include Try and Catch blocks like

this:

Visual Basic

LearningASP\VB\ErrorTest_02.aspx.vb
(excerpt)

Protected Sub Page_Load(ByVal sender As Object,

➥ ByVal e As System.EventArgs) Handles Me.Load

Dim a(10) As Integer

Dim i As Integer

Try

For i = 1 To 11

a(i) = i

Next

Catch ex As Exception

messageLabel.Text = "Exception!
" & ex.Message

End Try

End Sub

C#

LearningASP\CS\ErrorTest_02.aspx.cs
(excerpt)

protected void Page_Load(object sender, EventArgs e)

{

int[] a = new int[10];

int i;

try

{

for (i = 0; i < 11; i++)

{

Licensed to [email protected]

Building Web Applications

225

a[i] = i;

}

}

catch(Exception ex)

{

messageLabel.Text = "Exception!
" + ex.Message;

}

}

Provided you have a Label control named messageLabel in your web form, you’ll

see the message shown in Figure 5.46
when you run this code.

Figure 5.46. Catching an exception

In the code above, we can see that the Catch block receives an Exception object,

ex, as a parameter. This object describes the exception that has caused the Catch

block to execute. In our code, we use one of the Exception object’s many properties—in this case, Message—to display some information about the error. In .NET, all exceptions are .NET classes derived from the Exception class. This

means that, in fact, each exception is a different class (in our case, ex is an

IndexOutOfRangeException object), but we can treat ex as the generic Exception

class to access the generic details of any error.

The Exception class contains the following properties:

Message

the error message

Source

the name of the exception’s source

Licensed to [email protected]

226

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

StackTrace

the names of the methods that were called just before the error occurred

TargetSite

an instance of the MethodBase class that represents the method that caused the

error

Specialized exception classes can contain additional members. For example, the

SqlException class, which is raised when database-related errors occur, includes

a collection of error messages (SqlError objects) in its Errors property. You could

use a For Each loop to iterate through these errors.

In complex application scenarios, you could even create your own exception classes

as specialized versions of Exception. You could then throw these exceptions as

needed, and catch them in a class or method that was situated in the upper levels

of the hierarchy, and would handle these errors properly.

Summary

In this chapter, you’ve learned just how powerful Visual Web Developer can be.

We’ve seen most of its basic features in action, and we’ve experimented with some

of the really useful features you’ll find yourself using every day, such as automatic

code generation and debugging. We also used Visual Web Developer to make a start

on our exciting new project: Dorknozzle!

We’ve taken a close look at
Web.config
, which is where your web application’s

configuration settings will be stored, and
Global.asax
, which is where applicationwide events can be handled. We’ve also discussed the Application and Cache objects, which can be used to store data that’s available to all pages within an application; the Session object, which can be used to store user-specific data across requests; and cookies, which can be sent to the user’s browser, then read on subsequent visits.

Finally, we took a look at themes and master pages, which are powerful ways of

managing your site’s look and feel.

In
Chapter 6
, we’ll discuss data validation, and learn how ASP.NET’s validation controls can help us ensure that our back-end systems are as secure as possible.

Licensed to [email protected]

Chapter6

Using the Validation Controls

Ever needed to ensure that a user typed an email address into a text box? Or wanted

to make sure that a user typed numbers only into a phone number field? Validation

involves checking that the data your application’s users have entered obeys a

number of predefined rules. To help developers with the most common data validation tasks, ASP.NET provides a set of validation controls that ease the problems that beset web developers in the past. This chapter will show you how to use them.

More specifically, in this chapter you will:

■ Learn the difference between client-side and server-side data validation.

■ Use the .NET validation controls to restrict the data your visitors can submit.

■ Create validation groups to create groups of controls that need to be validated

together.

■ Update Dorknozzle to validate the data submitted by its users.

Licensed to [email protected]

228

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Client-side Validation and

Server-side Validation

There are two kinds of form validation, and they’re differentiated by the location

in which the validation takes place. You could write client-side JavaScript code

that validates the data typed by the user directly into the browser (
client-side valid-

ation
), or you could use server-side VB or C# code to validate the user input once

the form has been submitted to the server (
server-side validation
).

Client-side validation has its benefits, chief among them the fact that it provides

instant feedback to users. If users fail to enter their names into a text box, the page

automatically displays an error message. The users know immediately that they

need to enter their names—they don’t need to wait for a response from the server

to tell them so. The process is quick and efficient, and good for the overall user experience. However, there’s one big drawback with client-side validation: users must have

JavaScript enabled in their browsers, or validation simply will not occur. Some

browsers, such as those built into PDAs and mobile telephones, don’t support

JavaScript, so client-side validation doesn’t work for users of those browsers. Thus,

although client-side validation is a great way to increase the usability of your site,

it’s not a foolproof method of ensuring that the data entered into your form passes

all your rules.

While client-side validation is optional, server-side validation is not. For this reason,

developers frequently choose to implement only server-side validation methods.

Server-side validation is necessary because it’s our last line of defense against bogus

user data. The downside to server-side validation is that the application has to make

a trip to the server before users can be alerted to any errors in their data.

Introducing the ASP.NET Validation Controls

ASP.NET includes controls that make validation a snap. The ASP.NET validation

controls, while primarily being useful for implementing client-side validation, make

it easier to implement server-side validation as well. The ASP.NET validation controls generate the JavaScript required for basic validation tasks for you (so you don’t need to deal with any JavaScript code yourself); then, once the page is submitted,

Licensed to [email protected]

Using the Validation Controls

229

you can use the controls to check on the server whether or not the client-side validation was successful. ASP.NET’s validation controls provide client-side validation capabilities while

virtually eliminating the need for developers to know JavaScript. Better still, they

don’t require complex server-side scripting. To use ASP.NET validation controls,

we just add an object to the page and configure some simple properties.

As our first step towards demonstrating the ASP.NET validation controls, we’ll

create a number of simple pages in the
LearningASP
folder we worked with in previous

chapters. Then we’ll update the Dorknozzle intranet, adding validation features to

the Help Desk page.

To start with, let’s create a simple login web form. Create a file named
Login.aspx

(with no code-behind file) in your
C:\LearningASP\VB
or
C:\LearningASP\CS
folder and modify it as shown below:

Visual Basic

LearningASP\VB\Login_01.aspx
(excerpt)

<%@ Page Language="VB" %>

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




<br/><b>Simple Login Page<br/></b>







Username:


runat="server"

Other books

The Wild Ones by M. Leighton
Oceánico by Greg Egan
The Psalmist by James Lilliefors
Cupid's Mistake by Chantilly White
Hellhound by Mark Wheaton