Vous êtes sur la page 1sur 348

Course Number: 2063B

Released: 09/2001
Workbook
Introduction to Microsoft
ASP.NET
Part Number: X08-50211


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Course Number: 2063B
Part Number: X08-50211
Released: 09/2001
Introduction to Microsoft ASP.NET iii


Contents
Introduction
Course Materials ......................................................................................... 2
Prerequisites ............................................................................................... 3
Course Objectives........................................................................................ 4
Course Outline ................................ ................................ ............................ 5
Setup ......................................................................................................... 7
Lab Overview............................................................................................. 8
Lab Demonstration .................................................................................... 11
Microsoft Certified Professional Program..................................................... 13
Facilities................................................................................................... 15
Module 1: Working with Microsoft ASP.NET
Overview................................ ................................ ................................ .... 1
Introducing ASP.NET .................................................................................. 2
Creating Web Forms................................ ................................ .................. 11
Adding ASP.NET Code to a Page ................................................................ 23
Handling Page Events ................................................................................ 30
Discussion: ASP vs. ASP.NET.................................................................... 35
Lab 1: Using ASP.NET to Output Text......................................................... 36
Review..................................................................................................... 42
Module 2: Using Web Controls
Overview................................ ................................ ................................ .... 1
What Are Web Controls?.............................................................................. 2
Using Intrinsic Controls................................................................................ 4
Using Input Validation Controls ................................ ................................ .. 16
Selecting Controls for Applications .............................................................. 28
Lab 2: Using Web Controls ......................................................................... 29
Review..................................................................................................... 40
Module 3: Using Microsoft ADO.NET to Access Data
Overview................................ ................................ ................................ .... 1
Overview of ADO.NET................................................................................ 2
Connecting to a Data Source....................................................................... 11
Accessing Data with DataSets..................................................................... 13
Using Stored Procedures............................................................................. 28
Lab 3: Using ADO.NET to Access Data....................................................... 37
Accessing Data with DataReaders................................................................ 46
Binding to XML Data ................................................................................ 53
Review..................................................................................................... 59
Module 4: Separating Code from Content
Overview................................ ................................ ................................ .... 1
Advantages of Partitioning an ASP.NET Page................................................. 2
Creating and Using Code-Behind Pages.......................................................... 3
Creating and Using User Controls................................................................ 12
Creating and Using Components................................ ................................ .. 19
Lab 4: Separating Code from Content........................................................... 27
Review..................................................................................................... 39
iv Introduction to Microsoft ASP.NET


Module 5: Using Trace in Microsoft ASP.NET Pages
Overview................................ ................................ ................................ .... 1
Overview of Tracing................................ ................................ .................... 2
Trace Information........................................................................................ 3
Page-Level Trace......................................................................................... 4
Application-Level Trace............................................................................. 10
Lab 5: Adding Trace to an ASP.NET Page.................................................... 16
Review..................................................................................................... 21
Module 6: Using Web Services
Overview................................ ................................ ................................ .... 1
What Is a Web Service?................................................................................ 2
Calling a Web Service from a Browser ......................................................... 12
Calling a Web Service by Using a Proxy ...................................................... 15
Creating a Simple Web Service by Using Visual Basic ................................... 22
Creating and Calling a Web Service by Using Visual Studio .NET................... 26
Lab 6: Using Web Services ......................................................................... 35
Review..................................................................................................... 47
Module 7: Creating a Microsoft ASP.NET Web Application
Overview................................ ................................ ................................ .... 1
Requirements of a Web Application............................................................... 2
What Is New in ASP.NET?........................................................................... 3
Sharing Information Between Pages............................................................. 13
Securing an ASP.NET Application .............................................................. 24
Lab 7: Creating an ASP.NET Web Application ............................................. 38
Review..................................................................................................... 53

Introduction to Microsoft ASP.NET v


About This Course
This section provides you with a brief description of the course, audience,
suggested prerequisites, and course objectives.
Description
This three-day, instructor-led course exposes students to the features of
Microsoft ASP.NET and gives them hands-on experience (practices and labs)
in using and applying these features in their own Web applications.
Audience
This course is intended for Active Server Pages (ASP) Web developers. The
course assumes that students are familiar with Hypertext Markup Language
(HTML), client-side and server-side scripting, and Microsoft ActiveX Data
Objects (ADO).
Student Prerequisites
This course requires that students be able to do the following:
n Create forms and tables in HTML
n Write Microsoft Visual Basic or Visual Basic Scripting Edition
(VBScript code)
n Create an ASP page
n Retrieve data from a relational database by using ADO

The completion of the following courses will prepare the student to attend this
course:
n 1912A, Introduction to Web Development Technologies
n 1017A, Mastering Web Application Development Using Microsoft Visual
InterDev 6

Course Objectives
After completing this course, students will be able to:
n Create a Web form with server controls.
n Separate page code from content with code-behind pages, page controls, and
components.
n Display dynamic data from a data source by using ADO.NET and data
binding.
n Debug ASP.NET pages by using trace.
n Use a Web service to enhance a Web application.
n Add configuration, authentication, and state management to an ASP.NET
Web application.

vi Introduction to Microsoft ASP.NET


Student Materials Compact Disc Contents
The Student Materials compact disc contains the following files and folders:
n Autorun.exe. When the CD is inserted into the CD-ROM drive, or when you
double-click the autorun.exe file, this file opens the CD and allows you to
browse the Student Materials CD or install Internet Explorer.
n Default.htm. This file opens the Student Materials Web page. It provides
you with resources pertaining to this course, including additional reading,
review and lab answers, lab files, multimedia presentations, and course-
related Web sites.
n Readme.txt. This file contains a description of the compact disc contents and
setup instructions in ASCII format (that is, in plain text; not as a Microsoft
Word document).
n 2063B_ms.doc. This file is the Classroom Setup Guide. It contains a
description of classroom requirements, classroom setup instructions, and the
classroom configuration.
n AddRead. This folder contains additional reading pertaining to this course.
If there are no additional reading files, this folder does not appear.
n Appendix. This folder contains appendix files for this course. If there are no
appendix files, this folder does not appear.
n Democode. This folder contains demonstration code. If there is no
demonstration code, the Democode folder does not appear.
n Flash. This folder contains the installer for the Macromedia Flash 5.0
browser plug-in. If there are no Flash animations in the course, this folder
does not appear.
n Fonts. This folder contains fonts that are required to view the Microsoft
PowerPoint presentation and Web-based materials.
n Labs. This folder contains files that are used in the hands-on labs. These
files may be used to prepare the student computers for the hands-on labs.
n Media. This folder contains files that are used in multimedia presentations
for this course. If this course does not include any multimedia presentations,
this folder does not appear.
n Menu. This folder contains elements for autorun.exe.
n Mplayer. This folder contains files that are required to install Microsoft
Windows Media Player.
n Practices. This folder contains files that are used in the hands-on practices.
If there are no practices, the Practices folder does not appear.
n Sampapps. This folder contains the sample applications associated with this
course. If there are no associated sample applications, the Sampapps folder
does not appear.
n Sampcode. This folder contains sample code that is accessible through the
Web pages on the Student Materials CD. If there is no sample code, the
Sampcode folder does not appear.
n Sampsite. This folder contains files that create the sample site associated
with this course. If there is no sample site, the Sampsite folder does not
appear.

Introduction to Microsoft ASP.NET vii


n Webfiles. This folder contains the files that are required to view the course
Web page. To open the Web page, open Windows Explorer, and in the root
directory of the compact disc, double-click Default.htm or Autorun.exe.
n Wordview. This folder contains the Word Viewer that is used to view any
Word document (.doc) files that are included on the compact disc. If no
Word documents are included, this folder does not appear.


viii Introduction to Microsoft ASP.NET


Document Conventions
The following conventions are used in course materials to distinguish elements
of the text.
Convention Use

u Indicates an introductory page. This symbol appears next to a
topic heading when additional information on the topic is covered
on the page or pages that follow it.
bold Represents commands, command options, and syntax that must be
typed exactly as shown. It also indicates commands on menus and
buttons, dialog box titles and options, and icon and menu names.
italic In syntax statements or descriptive text, indicates argument names
or placeholders for variable information. Italic is also used for
introducing new terms, for book titles, and for emphasis in the
text.
Title Capitals Indicate domain names, user names, computer names, directory
names, and folder and file names, except when specifically
referring to case-sensitive names. Unless otherwise indicated, you
can use lowercase letters when you type a directory name or file
name in a dialog box or at a command prompt.
ALL CAPITALS Indicate the names of keys, key sequences, and key combinations
for example, ALT+SPACEBAR.
monospace Represents code samples or examples of screen text.
[ ] In syntax statements, enclose optional items. For example,
[filename] in command syntax indicates that you can choose to
type a file name with the command. Type only the information
within the brackets, not the brackets themselves.
{ } In syntax statements , enclose required items. Type only the
information within the braces, not the braces themselves.
| In syntax statements, separates an either/or choice.
Indicates a procedure with sequential steps.
... In syntax statements, specifies that the preceding item may be
repeated.
.
.
.
Represents an omitted portion of a code sample.












Contents
Introduction 1
Course Materials 2
Prerequisites 3
Course Objectives 4
Course Outline 5
Setup 7
Lab Overview 8
Lab Demonstration 11
Microsoft Certified Professional Program 13
Facilities 15

Introduction


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Introduction 1


Introduction
n Name
n Company Affiliation
n Title/Function
n Job Responsibility
n HTML, Visual Basic Programming, ASP, ADO, and
Database Experience
n Expectations for the Course

*****************************illegal for non-trainer use******************************
2 Introduction


Course Materials
n Name Card
n Student Workbook
n Student Materials Compact Disc
n Visual Studio .NET Beta 2 Compact Disc
n Course Evaluation

************** ***************illegal for non-trainer use******************************
The following materials are included with your kit:
n Name card. Write your name on both sides of the name card.
n Student workbook. The student workbook contains the material covered in
class, in addition to the hands-on lab exercises.
n Student Materials compact disc. The Student Materials compact disc
contains the Web page that provides you with links to resources pertaining
to this course, including additional readings, review and lab answers, lab
files, multimedia presentations, and course-related Web sites.

To open the Web page, insert the Student Materials compact disc into
the CD-ROM drive. Then, in the root directory of the compact disc, double -
click Autorun.exe or Default.htm.

n Visual Studio .NET Beta 2 compact disc. The course is being shipped with
the Visual Studio .NET Beta 2 compact disc because the courses
executable elements are compatible only with the Beta 2 version. The labs
and demonstrations in the course will not run with the final version of
ASP.NET.
n Course evaluation. At the conclusion of this course, please complete the
course evaluation to provide feedback about the instructor, course, and
software product. Your comments will help us improve future courses.
To provide additional comments or inquire about the Microsoft Certified
Professional program, send e-mail to mcp@msprograms.com.


Note
Introduction 3


Prerequisites
n Create forms and tables in HTML
n Write Visual Basic or VBScript code
n Create an Active Server Page
n Retrieve data from a relational database using ADO

*****************************illegal for non-trainer use******************************
This course requires that you meet the following prerequisites:
n Create forms and tables in Hypertext Markup Language (HTML)
n Write Microsoft Visual Basic or Visual Basic Scripting Edition
(VBScript code)
n Create an Active Server Page (ASP)
n Retrieve data from a relational database by using Microsoft ActiveX Data
Objects (ADO)


4 Introduction


Course Objectives
n Create a Web form with server controls
n Separate page code from content with code-behind
pages, user controls, and components
n Display dynamic data from a data source using
Microsoft ADO.NET and data binding
n Debug ASP.NET pages using trace
n Use a Web service to enhance a Web application
n Add configuration, authentication, and state
management to an ASP.NET Web application

*********************** ******illegal for non-trainer use******************************
After completing this course, students will be able to:
n Create a Web form with server controls.
n Separate page code from content with code-behind pages, user controls, and
components.
n Display dynamic data from a data source by using Microsoft ADO.NET and
data binding.
n Debug ASP.NET pages using trace.
n Use a Web service to enhance a Web application.
n Add configuration, authentication, and state management to an ASP.NET
Web application.


Introduction 5


Course Outline
n Module 1: Working with Microsoft ASP.NET
n Module 2: Using Web Controls
n Module 3: Using Microsoft ADO.NET to Access Data
n Module 4: Separating Code from Content
n Module 5: Using Trace in Microsoft ASP.NET Pages
n Module 6: Using Web Services
n Module 7: Creating a Microsoft ASP.NET Web
Application

*****************************illegal for non-trainer use******************************
Module 1, Working with Microsoft ASP.NET, introduces the ASP.NET
language. It provides an overview of the features of ASP.NET and introduces
the execution model of ASP.NET. The module also shows how to add server-
side code to the controls on a page. After completing this module, you will be
able to add server controls and code to an ASP.NET page.
Module 2, Using Web Controls, introduces the Web controls that are new
with ASP.NET. You will learn what a Web control is, how to add it to an
ASP.NET page, and how to access its properties, methods, and events. You will
learn how to use input validation controls and the DataGrid control. After
completing this module, you will be able to use Web controls in an ASP.NET
page.
Module 3, Using Microsoft ADO.NET to Access Data, describes how to
access data in an ASP.NET page by using ADO.NET. This module starts with
an overview and then moves into the specifics of how to use ADO.NET. After
completing this module, you will be able to access dynamic data from a data
source by using ADO.NET.
Module 4, Separating Code from Content, describes how to partition an
ASP.NET page to separate out the code. You learn about the various methods
that can be used to separate code from content, such as code-behind pages, user
controls, and components. After completing this module, you will be able to
create a code-behind page to hold code in an ASP.NET page.
Module 5, Using Trace in Microsoft ASP.NET Pages, demonstrates how to
use the trace feature of ASP.NET to debug ASP.NET pages. Both page-level
and application- level tracing are covered in the module. After completing this
module, you will be able to debug ASP.NET pages by using the trace feature.

6 Introduction


Module 6, Using Web Services, describes Web services and explains how
they expand a Web developers toolbox. You will learn how to use a Web
service and the code to create a simple Web service. After completing this
module, you will be able to use a Web service to enhance your Web application.
Module 7, Creating a Microsoft ASP.NET Web Application, describes the
technologies in ASP.NET that are necessary for creating real-world Web
applications, such maintaining state, global files, configuration and deployment,
and security. After completing this module, you will be able to create an
ASP.NET Web application by integrating ASP.NET pages.

Introduction 7


Setup
n Microsoft Windows 2000 Server
l Internet Information Services 5.0
n Microsoft SQL Server 2000, Standard Edition
n Microsoft Internet Explorer 5.5
n Microsoft Visual Studio .NET, Beta 2
n Microsoft .NET Framework SDK, Beta 2
n Lab and Demonstration Course Files

*****************************illegal for non-trainer use******************************
The following software and resource materials will be used in the classroom:
n Microsoft Windows 2000 Server
n Internet Information Services 5.0
n Microsoft SQL Server 2000, Standard Edition
n Microsoft Internet Explorer 5.5
n Microsoft Visual Studio .NET, Beta 2
n Microsoft .NET Framework software development kit (SDK), Beta 2
n Macromedia Flash player
n Lab and Demonstration Course files

Course Files
There are starter and solution files associated with the labs in this course. The
starter files are located in the folder <install folder>\Labs\Lab0x\Starter and the
solution files for this lab are in the folder <install folder>\Labs\Lab0x\Solution,
where Lab0x corresponds with the current lab.
There are files associated with the demonstrations in this course. These files are
located in the folder <install folder>\DemoCode\Mod0x, where Mod0x
corresponds with the current module.

If you performed a default installation of the course files,
<install folder> will be c:\Program Files\Msdntrain\2063.


Note
8 Introduction


Lab Overview
n Conference registration Web site
l View pre-conference tutorials
l View the conference tracks and sessions in each track
l View the conference proceedings
l Register for the conference
l Reserve a hotel room

*****************************illegal for non -trainer use******************************
The labs for this course build upon one another to create a complete application.
The lab application is a Conference Web site. On the Web site, users can view
the pre-conference tutorials and the sessions being offered in the different
tracks of the conference. They can choose from these offerings and then register
for the conference. They can also make a reservation at a hotel for the duration
of the conference.
The lab application uses a SQL Server database named Conf. For an illustration
of the Conf database schema, see Appendix B in Course 2063B, Introduction to
Microsoft ASP.NET.
Lab Application Files
The following is a list of all the files that are used by the lab application and
their purpose.

File name

Purpose
Lab file
is used in

_header.ascx User control that contains a heading for
each page of the Web site.
Multiple
_menu.ascx User control that contains a menu for the
Web site and is placed on each page of
the Web site.
Labs 3 and 4
AddToCart.aspx Adds a product to the shopping cart, then
redirects to the shopping cart page.
Multiple
CheckOut.aspx Allows users to view the information in
the shopping cart and then select the hotel
they want to stay in.
Lab 7
Conference.css Style sheet for the user interface. Multiple
Conflogo.swf Flash animation embedded in
Default.aspx page.
Multiple

Introduction 9


(continued)

File name

Purpose
Lab file
is used in

Web.config Configuration information. Lab 7
Default.aspx Home page for the Web application. Multiple
Errorpage.aspx Redirection page in case of any error. Multiple
Hotel_reservation.aspx Allows users to reserve a hotel room by
specifying the type of room and the dates
for which the room is needed.
Labs 2 and 6
Login.aspx Allows users to sign in to the conference
system by supplying their e-mail names
and passwords.
Labs 1 and 7
ProductDetails.aspx Outputs detailed information about pre-
conference tutorial, track, or proceedings.
Multiple
ProductsList.aspx Displays the different products (tutorials,
tracks, and proceedings) available in the
conference.
Labs 3, 4, and 5
Register.aspx Allows new users to register for the
conference.
Labs 2 and 7
SearchResults.aspx Outputs products based on search criteria. Multiple
ShoppingCart.aspx All code to manage the user interface (UI)
of the shopping cart.
Multiple

Component Files
The following is a list of all the files in the conference.dll component.

File name

Purpose
Lab file
is used in

ConferenceDB.vb Programmatic access to the database
connection string.
Multiple
CustomersDB.vb Programmatic access to the Customer
table in the database.
Multiple
GetProducts.vb Programmatic access to the
GetProductsByCategory stored
procedure.
Lab 4
mk.bat Makefile to create the component. Multiple
OrdersDB.vb Programmatic access to the Orders table
in the database.
Multiple
ProductsDB.vb Programmatic access to the Products
table in the database.
Multiple


10 Introduction


Web Services
The following is a list of all the Web Service files used by the lab application.

File name

Purpose
Lab file
is used in

Hotel_empty.asmx Web service for a hotel named Empty. Multiple
Hotel_full.asmx Web service for a hotel named Full. Lab 6
mkServices.bat Makefile to create a proxy for the Web
Services.
Lab 6


Introduction 11


Lab Demonstration

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how a user would use the Conference Web
application to register for a conference and reserve a room in a hotel.
To run the demonstration
1. Start Internet Explorer and enter the Uniform Resource Locator (URL) for
the lab solution Web site, http://localhost/labsolution. This displays the
home page default.aspx, which contains the two user controls: _header.ascx
and _menu.ascx.
2. On the home page, click Pre-Conference Tutorials to view the details of
all the tutorials that are offered on the ProductsList.aspx page.
3. Click on one of the subjects to obtain further details, such as the venue and
time for the tutorials, on the ProductDetails.aspx page.
4. Click Add to Cart to purchase the tutorial that you are viewing. This goes
to the ShoppingCart.aspx page.

You can also add an item to the shopping cart from the
ProductsList.aspx page.

5. On the ShoppingCart.aspx page, change the quantity of an item or delete it
from the cart, then click Update your Shopping Cart to see the changes.
6. Repeat steps 2-5 for the Conference Tracks and Conference Proceedings
links.
7. Enter a phrase in the Search text box and click Go! This calls the
SearchResults.aspx page and displays all conference items related to the
search string. You can also add items to the shopping cart from this page.
8. Click the Shopping Cart icon to jump to the ShoppingCart.aspx page.

Note
12 Introduction



9. Click Final Checkout to buy the items in the shopping cart.
10. If you have not already logged in to the application, you will need to log in
on the login.aspx page. Because you are new to the application, click Click
here! to enter your information into the database on the Register.aspx page.

A valid user name and password that you can use on the login.aspx
page is: someone@microsoft.com, password.

11. On the Register.aspx page, enter the requested information, and then click
Submit. This returns you to the ShoppingCart.aspx page.
12. On the ShoppingCart.aspx page, click Final Checkout again. This calls the
Checkout.aspx page.
13. Review the items in your order, and then click Submit for a final checkout.
14. Select a hotel to stay at. Click either Hotel Full or Hotel Empty. This calls
the hotel_reservation.aspx page.
15. In the hotel_reservation.aspx page, select a type of room, and then select the
dates for your stay. Next, click Submit.

Hotel Full will never have a room available; Hotel Empty will always
have a room available.

16. Click the Shopping Cart icon again to show that the shopping cart is now
empty.

Note
Note
Introduction 13


Microsoft Certified Professional Program
http://www.microsoft.com/trainingandservices/

*****************************illegal for non-trainer use******************************
The Microsoft Certified Professional program includes the following
certifications:
n Microsoft Certified Systems Engineer + Internet (MCSE + Internet)
n Microsoft Certified Systems Engineer (MCSE)
n Microsoft Certified Database Administrator (MCDBA)
n Microsoft Certified Solution Developer (MCSD)
n Microsoft Certified Professional + Site Building (MCP + Site Building)
n Microsoft Certified Professional + Internet (MCP + Internet)
n Microsoft Certified Professional (MCP)
n Microsoft Certified Trainer (MCT)


See the Certification section of the Web page provided
on the compact disc or the Microsoft Training and Certification Web site at
http://www.microsoft.com/trainingandservices/
You can also send e-mail to mcp@msprograms.com if you have specific
certification questions.


For More Information
14 Introduction


Exam Preparation Guides
To help prepare for the MCP exams, you can use the preparation guides that are
available for each exam. Each Exam Preparation Guide contains exam-specific
information, such as a list of the topics on which you will be tested. These
guides are available on the Microsoft Certified Professional Web site at
http://www.microsoft.com/trainingandservices/

MSDN Training curriculum helps you to prepare for Microsoft
Certified Professional (MCP) exams. However, no one-to-one correlation exists
between MSDN Training courses and MCP exams. Passing MCP exams
requires real-world experience with the productsMSDN Training courses
help get you started.


Important
Introduction 15


Facilities
Building Hours
Parking
Rest Rooms
Meals
Phones
Messages
Smoking
Recycling
Class Hours

*****************************illegal for non-trainer use******************************







THIS PAGE INTENTIONALLY LEFT BLANK









Contents
Overview 1
Introducing ASP.NET 2
Creating Web Forms 11
Adding ASP.NET Code to a Page 23
Handling Page Events 30
Discussion: ASP vs. ASP.NET 35
Lab 1: Using ASP.NET to Output Text 36
Review 42

Module 1: Working with
Microsoft ASP.NET


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 1: Working with Microsoft ASP.NET 1


Overview
n Introducing ASP.NET
n Creating Web Forms
n Adding ASP.NET Code to a Page
n Handling Page Events
n Discussion: ASP vs. ASP.NET

*****************************illegal for non-trainer use******************************
Microsoft Active Server Pages (ASP) technology is widely used to create
dynamic Web sites and applications. However, ASP has several limitations,
such as the need for redundant and lengthy coding to accomplish simple goals.
To overcome these limitations of ASP, Microsoft has developed a new
technology called Microsoft ASP.NET, which is a part of the Microsoft .NET
strategy for Web development. ASP.NET is a unified Web development
platform that provides the services necessary for developers to build enterprise-
class Web applications.
In this module, you will learn about the main features of ASP.NET and
discover the differences between ASP and ASP.NET. You will also learn about
server controls and see how to add server -side script to an ASP.NET page.
After completing this module, you will be able to:
n Identify the main features of ASP.NET.
n Identify the differences between ASP and ASP.NET.
n Describe the working model of ASP.NET.
n Describe the architecture of server controls.
n Add a Hypertext Markup Language (HTML) server control to a page.
n Access the properties and methods of server controls in code.
n Add event handlers for page events.
n Use the IsPostback property to handle postback forms.

2 Module 1: Working with Microsoft ASP.NET


u Introducing ASP.NET
n The Microsoft .NET Framework
n ASP.NET Features
n Animation: ASP.NET Execution Model

*****************************illegal for non-trainer use**************************** **
In this section, you will read an overview of the Microsoft .NET Framework
and see how ASP.NET fits in. Next, you will learn about the various features of
ASP.NET and see a working model. You will also learn about the main
differences between ASP and ASP.NET.

Module 1: Working with Microsoft ASP.NET 3


The Microsoft .NET Framework
.NET .NET
Framework Framework
Internet Internet
COM+ COM+
Orchestration Orchestration
Windows
.NET
Enterprise
Servers
Building Building
Block Block
Services Services
Visual Studio.NET
Base Class Library Base Class Library
ADO.NET: Data & XML ADO.NET: Data & XML
User User
Interface Interface
Common Language Runtime Common Language Runtime
Web Web
Services Services

*****************************illegal for non-trainer use******************************
The Microsoft .NET Platform provides all of the tools and technologies that are
needed to build distributed Web applications. It exposes a consistent, language-
independent programming model across all tiers of an application, while
providing seamless interoperability with and easy migration from existing
technologies.
The Microsoft .NET Platform is composed of several core technologies:
n The Microsoft .NET Framework
n The Microsoft .NET Building Block Services
n The Microsoft .NET Enterprise Servers
n Microsoft Visual Studio .NET
n Microsoft Windows. NET

The Microsoft .NET Framework is a set of technologies that is integral to the
Microsoft .NET Platform. It provides the basic building blocks for developing
Web applications and services. The Microsoft .NET Framework includes the
following components:
n Common Language Runtime
n Base class library
n Data
n Web forms and Web services
n WinForms


4 Module 1: Working with Microsoft ASP.NET


Common Language Runtime
The Common Language Runtime provides the programming interface between
the Microsoft .NET Framework and the programming languages available for
the Microsoft .NET Platform. It simplifies application development, provides a
robust and secure execution environment, supports multiple languages, and
simplifies application deployment and management. The run time loads and
runs code written in any run time-aware programming language. Code that
targets the run time is called managed code. Managed code simply means that
there is a defined contract of cooperation between natively executing code and
the run time itself. Responsibility for tasks like creating objects, making method
calls, and so on is delegated to the run time, which enables the run time to
provide additional services to the executing code.
Base Classes and Libraries
The Microsoft .NET Framework includes classes that encapsulate data
structures, perform Input/Output (I/O), provide access to information about a
loaded class, and provide a way to invoke security checks. It also includes
classes that encapsulate exceptions and other helpful functionality such as data
access, server-side user interface (UI) projections, and rich graphical user
interface (GUI) generation. The Microsoft .NET Framework provides both
abstract base classes and class implementations derived from those base classes.
You can use these derived classes as is or derive your own classes from them.
The Microsoft .NET Framework classes are named using a dot-syntax naming
scheme that connotes a naming hierarchy. This technique is used to group
related classes logically together so that they can be searched and referenced
more easily. A grouping of classes is called a namespace. For example, a
program can use classes in the System.Data.SqlClient namespace to read data
from a SQL Server database.
The root namespace for the Microsoft .NET Framework is the System
namespace.
Data
Microsoft ADO.NET is the next generation of ActiveX Data Object (ADO)
technology. ADO.NET provides improved support for the disconnected
programming model and also provides rich Extensible Markup Language
(XML) support. ADO was created to provide data services to traditional client
applications that were tightly coupled to the database; consequently it was not
effective for Web applications. ADO.NET was created with the characteristics
of Web applications in mind.
Web Forms and Web Services
ASP.NET is a programming framework built on the Common Language
Runtime that can be used on a server to build powerful Web applications.
ASP.NET Web forms provide an easy and powerful way to build dynamic user
interfaces. ASP.NET Web services provide the building blocks for constructing
distributed Web-based applications. Web services are based on the Simple
Object Access Protocol (SOAP) specification.

Module 1: Working with Microsoft ASP.NET 5


Win Forms
For applications that are based on Microsoft Windows, the Microsoft .NET
Framework provides the System.Windows.Forms namespace to create the user
interface. You can use System.Windows.Forms to do rapid application design
(RAD). It provides inheritance in the same client user interface library. You can
build components by using inheritance and then aggregate them by using a form
designer such as Microsoft Visual Basic .

6 Module 1: Working with Microsoft ASP.NET


ASP.NET Features
n Multiple Language Support
n Increased Performance
l Compiled code
l Cache
n Classes and Namespaces
n Server Controls
n Web Services

*****************************illegal for non-trainer use******************************
ASP.NET is more than just the next version of ASP. It is a totally re-architected
technology for creating dynamic, Web-based applications. ASP pages use
the .asp extension and ASP.NET pages use the extension .aspx.

Both ASP and ASP.NET pages can be used on the same Web site.
Existing ASP pages will still work along with new ASP.NET pages; they do not
need to be converted into ASP.NET pages.

ASP.NET, with a host of new features, allows developers to write cleaner code
that is easy to reuse and share. ASP.NET boosts performance and scalability by
offering access to compiled languages. Some of the main features of ASP.NET
are described below.
Multiple Language Support
ASP.NET provides a true language-neutral execution framework for Web
applications.
You can currently use over 20 languages to build .NET applications. Microsoft
has compilers for Visual Basic, Microsoft Visual C#

, Microsoft Visual C++,


and Microsoft JScript. Third-party vendors are writing .NET compilers for
Cobol, Pascal, Perl, and Smalltalk, among others.
The labs and the sample code in this course will use Visual Basic.
Increased Performance
In ASP.NET, code is compiled. When you request a page for the first time, the
run time compiles the code and the page itself, and keeps a cached copy of the
compiled result. When you request the page the second time, the cached copy is
used. This results in greatly increased performance because, after this first
request, the code can run from the much faster compiled version and the content
on the page does not need to be parsed again.

Note
Module 1: Working with Microsoft ASP.NET 7


Classes and Namespaces
ASP.NET includes a range of useful classes and namespaces. Namespaces are
used as an organizational systema way to present program components that
are exposed to other programs and applications. Namespaces contains classes.
Namespaces are like class libraries and can make writing Web applications
easier. Some of the classes included with ASP.NET are HtmlAnchor,
HtmlControl, and HtmlForm, which are included within the
System.Web.UI.HtmlControls namespace.

Namespaces may change between the Beta 2 and the final release
versions of ASP.NET.

Server Controls
ASP.NET provides several server controls that simplify the task of creating
pages. These server controls encapsulate common tasks that range from
displaying calendars and tables to validating user input. They automatically
maintain their selection states and expose properties, methods, and events for
server-side code, thereby providing a clean programming model.
For more information about using server controls, see Module 2, Using Web
Controls, in Course 2063B, Introduction to Microsoft ASP.NET.
Web Services
A Web service is an application delivered as a service that can be integrated
with other Web services by using Internet standards. ASP.NET allows you to
use and create Web services.
For example, a company can assemble an online store by using the Microsoft
Passport service to authenticate users, a third-party personalization service to
adapt Web pages to each users preferences, a credit-card processing service, a
sales tax service, package-tracking services from each shipping company, and
an in-house catalog service that connects to the companys internal inventory
management applications.
Web services provide the building blocks for constructing distributed Web-
based applications. ASP.NET files have an .aspx extension and Web services
have an .asmx extension. The technologies are similar; however, instead of
outputting HTML, a Web service outputs a computer-readable answer to the
input it receives.
For more information about Web services, see Module 6, Using Web
Services, in Course 2063B, Introduction to Microsoft ASP.NET.

Note
8 Module 1: Working with Microsoft ASP.NET


ASP.NET Features (continued)
n Improved Security
n Greater Scalability
n Cookie-less Sessions
n Easy Configuration and Deployment

*****************************illegal for non-trainer use******************************
Improved Security
In ASP, the only type of authentication that you can use is the Windows
authentication, whereas ASP.NET allows different types of logon and user
authentication: Windows, Passport, and Cookies.
ASP.NET also enables you to get real account impersonation and have the
server execute code as if the user were present. You can also programmatically
check to see if the user is in a given role and conditionally let him or her
perform certain tasks when given permission.
In addition, creating forms-based authentication, in whic h you can create your
own custom logon screen and credential checking, is much easier if you are
using ASP.NET.
For more information about authentication and creating login forms, see
Module 7, Creating a Microsoft ASP.NET Web Application, in Course
2063B, Introduction to Microsoft ASP.NET.
Greater Scalability
In ASP.NET, session state can now be maintained in a separate process on a
separate machine or database, allowing for cross-server sessions. This allows
you to add more Web servers as your traffic grows.

Module 1: Working with Microsoft ASP.NET 9



Cookie-less Sessions
ASP.NET enables you to use session state even with browsers that have cookie
support disabled. Cookie-less sessions use Uniform Resource Locators (URLs),
as opposed to cookies, to pass the SessionID to an ASP.NET page. A cookie-
less session involves encoding data into a URL, which is done automatically by
the browser.
For more information about maintaining state, see Module 7, Creating a
Microsoft ASP.NET Web Application, in Course 2063B, Introduction to
Microsoft ASP.NET.
Easy Configuration and Deployment
Configuration and deployment are now easier with the use of human-readable
configuration files and DLLs that do not need to be registered.
In ASP.NET, all the configuration details for all Web applications are kept in
human-readable files named web.config. The standard format for the
configuration files is XML, and each application inherits the settings in the
default web.config file.
With .NET, all files that a Web site needs are located under the sites root
folder. DLLs are in the /bin folder, and the web.config file is in the root folder.
To deploy a Web site, all you need to do is copy the sites root folder by using
file copy commands, the Microsoft FrontPage server extensions, or File
Transfer Protocol (FTP).
For more information about configuration options, see Module 7, Creating a
Microsoft ASP.NET Web Application, in Course 2063B, Introduction to
Microsoft ASP.NET.
10 Module 1: Working with Microsoft ASP.NET


Animation: ASP.NET Execution Model

*****************************illegal for non-trainer use******************************
In this animation, you will see how ASP.NET pages are processed on the server.
To view the animation, open the 2063B_01A001.swf file from the Media
folder.
The following table describes the elements that are depicted in the animation.
Element Description

Parser The parser checks and interprets the contents of the aspx page and
passes the page to a compiler.
Compiler The run-time compiler is responsible for compiling the contents of
the page into an intermediate language.
Assembly Cache Each machine on which the Microsoft .NET Framework is installed
has a machine-wide code cache called the assembly cache. One of
the functions of the assembly cache is to hold the native code
versions of pages that have been pre-compiled.
Memory Some items that are expensive to construct can be built once and
used for a period of time before they are considered invalid. These
items are stored in memory where they can be efficiently retrieved
without incurring the cost of being reconstructed.
Output Cache The output cache is a cache for entire pages, including their objects
and data. After a page is built, it can be placed in the output cache.
If a user makes another request for the page, the request is returned
from the output cache.



Module 1: Working with Microsoft ASP.NET 11


u Creating Web Forms
n What Are Web Forms?
n What Are Server Controls?
n Types of Server Controls
n How Do Server Controls Work?
n Demonstration:
Adding Server Controls to an ASP.NET Page

*****************************illegal for non-trainer use* *****************************
ASP.NET introduces the concept of server controls that encapsulate common
tasks and provide a clean programming model. In this section, you will learn
about types of server controls and see how they work. You will also learn how
to use server controls on ASP.NET pages.

12 Module 1: Working with Microsoft ASP.NET


What Are Web Forms?
n .aspx extension
n @Page Directive
n Framework Is an Object Model
n Denoted by the runat="server" Attribute
n Contain Client-side and Server-side Code
n Contain HTML and Server Controls
<Form runat="server">
</Form>
<Form runat="server">
</Form>
<%@ Page Language="vb" %>
<%@ Page Language="vb" %>

*****************************illegal for non-trainer use******************************
Web Forms divide Web applications into two pieces: the visual component and
the user interface logic.
n Web Forms have an .aspx extension
Web forms are commonly referred to as ASP.NET pages or ASPX pages.
They have an .aspx extension and work as the containers for the text and
controls that you want to display.
n @Page directive
The @Page directive defines page-specific attributes that are used by the
ASP.NET page parser and compiler. You can set the language attribute to
the language that will be used throughout all code on the page.
You can include only one @ Page directive per .aspx file.
n The Web Forms framework is an object model
Although you create Web forms from separate components, they form a unit.
When the Web form is compiled, ASP.NET parses the page and its code,
generates a new class dynamically, and then compiles the new class. The
dynamically generated class is derived from the ASP.NET Page class, but is
extended with controls, your code, and the static HTML text in the .aspx file.
This is different from ASP. In ASP, the page consists of static HTML
interspersed with executable code. The ASP processor reads the page,
extracts and runs the code, and then inserts the results back into the static
HTML before sending the results to the browser.
Unlike controls in an ASP form, all intrinsic controls in an ASP.NET form
are objects. Therefore, all the controls on a form have properties, methods,
and events.

Module 1: Working with Microsoft ASP.NET 13


n A Web form is denoted by the runat="server" attribute
The runat="server" attribute ensures that the form is executed at the server.
<For m r unat ="ser ver ">

</ For m>

n Contain client-side and server-side code
In the previous versions of ASP, controls on forms could invoke only client-
side functions. This has been changed in ASP.NET by the introduction of
server controls and server-side events.
Like ASP pages, Web forms can contain client-side and server-side code.
n Contain HTML and server controls
Server controls are new in ASP.NET. Web forms can contain HTML and
server controls.


ASP.NET and ASP pages can coexist on the same machine. The file
extension determines only whether ASP or ASP.NET processes it.


Note
14 Module 1: Working with Microsoft ASP.NET


What Are Server Controls?
n Server-programmable Objects
n Denoted by Tag with the runat = "server" Attribute
n Encapsulate Both Behavior and Rendering
n Fully Declarative
n Render Different HTML to Support Multiple Browsers or
Other Web Clients

*****************************illegal for non -trainer use******************************
ASP allowed developers to execute components on the server. ASP.NET
extends this concept with the introduction of server controls.
Server controls are controls that have built-in behavior. They have properties,
methods, and events that can be accessed at run time from code running on the
server.
They provide client-specific HTML that is displayed on the client. This means
that you do not need to create separate pages for each browser type, nor query
what type of browser is being used, because the control does that for you. For
example, server controls can determine whether a presentation task, such as
making a Web page text dynamically appear or disappear, should be performed
by the browser or server code. If Microsoft Internet Explorer, version 4.0 or
above, was the destination, the code is on the client side because
Internet Explorer 4.0 can handle dynamic text operations. If an older version of
Internet Explorer (for example, Internet Explorer 3.0) is the destination, the
code is on the server side, resulting in an extra transaction with the server to
change the text. From the user point of view, the text would change, but
depending on the browser type, changes would occur either on the client or
server. All this can be accomplished by a server control, which determines the
browser type and generates the appropriate code.
Server controls also provide a consistent object model for the controls,
providing standard properties, methods, and events.

Module 1: Working with Microsoft ASP.NET 15


Users can easily create server controls from existing HTML controls. To create
a server control, simply add the runat attribute to the controls tag. For
example, the following is an HTML input box, turned into a server control:
<I NPUT TYPE=" TEXT" r unat =" ser ver " >

Without the runat="server" attribute, this line of HTML would be parsed
into a standard HTML text box.

After you create a server control, you can access its properties, methods, and
events through server-side code, making it easy to obtain user input and provide
user feedback.

Note
16 Module 1: Working with Microsoft ASP.NET


Types of Server Controls
n HTML Controls
l Exist within the System.Web.UI.HtmlControls
namespace
n Web Controls
l Exist within theSystem.Web.UI.WebControls
namespace
<input type="text" id="txtName" runat="server">
<span id="spnStarter" runat="server">
starter</span>
<input type="text" id="txtName" runat="server">
<span id="spnStarter" runat="server">
starter</span>
<asp:TextBox id="txtName" runat="server"
Text="[Entry Keywords]"/>
<asp:TextBox id="txtName" runat="server"
Text="[Entry Keywords]"/>

*****************************illegal for non-trainer use******************************
Server controls are us ed to create the user interface for your Web application.
They can generate any output that is suitable for the device or browser they are
targeting and can maintain state between trips to the server. There are two sets
of server controls in the ASP.NET Framework: HTML controls and Web
controls. Both render HTML that is displayed by Web browsers.
HTML Controls
HTML controls offer Web developers the power of the Web Forms page
framework while retaining the familiarity and ease of use of HTML elements.
These controls look exactly like HTML, except that they have a
runat="server" attribute/value pair in the opening tag of the HTML element.
For example, the following HTML not only creates a text box on a Web page,
but also creates an instance of the text box server control:
<i nput t ype=" t ext " r unat =" ser ver " i d=" t xt Name" val ue=" some
t ext ">

To enable programmatic referencing of the control, include a unique id attribute.
In the preceding example, the id="txtName" defines this programmatic id,
allowing developers to manipulate the contents of this text box with server-side
events and other code.
ASP.NET offers direct object model support for the most commonly used
HTML elements. For object models that are not directly supported, there is the
HtmlGenericControl object, which supports the <span>, <div>, <body>, and
<font> elements, among others.

Module 1: Working with Microsoft ASP.NET 17


For example, you can use the following code to create a SPAN server element.
<span i d=" spnSt ar t er " r unat =" ser ver " >st ar t er t ext </ span>

The HTML controls exist in the System.Web.UI.HtmlControls namespace.

All HTML controls must be well-formed and must not overlap. Unless
otherwise noted, elements must be closed, either with an ending slash within the
tag or with a closing tag, like the XML syntax.

Web Controls
Web controls include traditional form controls such as the TextBox and Button
controls, as well as other higher-level abstractions such as the Calendar and
DataGrid controls. Web controls can be further classified into Intrinsic, Rich,
Validation, and List controls.
Web controls appear in the HTML markup as namespaced tagsthat is, tags
with a prefix. The prefix is used to map the tag to the namespace of the run-
time component. The remainder of the tag is the name of the run-time class
itself. Like HTML controls, these tags must also contain a runat="server"
attribute. An example declaration is as follows:
<asp: Text Box i d=" t xt Name" r unat =" ser ver " Text =" [ Ent r y
Keywor ds] " ></ asp: Text Box>

In the preceding example, "asp" is the namespace tag prefix and it maps to the
System.Web.UI.WebControls namespace. This namespace is automatically
included in an ASP.NET page; you do not need to import it.

Note
18 Module 1: Working with Microsoft ASP.NET


How Do Server Controls Work?
n Declared with runat="server" Attribute
n When the ASP.NET Page Is Executed:
l Creates action and method attributes of form
l Adds unique id and name attributes to controls
l Adds value attribute to controls
l Adds a hidden control to the form to save view state
information
<input type="text" id="text2" runat="server">
<input type="text" id="text2" runat="server">

*****************************illegal for non -trainer use******************************
The key to the working of server controls is the runat="server" attribute.
When you set the runat attribute, you enable the server -side events and view
state maintenance for controls. If you do not set the runat attribute, the control
works as a plain HTML control. The state for the controls is not maintained and
no server-side events are available. You can have both server and plain HTML
controls on a form.
Web controls usually reside on a form. Forms also have the runat="server"
attribute. The runat attribute enables forms to maintain the view state of their
controls in an ASP.NET page. When an ASP.NET page is submitted to the
server, ASP.NET automatically adds a hidden control named _VIEWSTATE
to the form. If the state of a control has been modified, the _VIEWSTATE
control is used to remember the values. This way, changes made to a page can
be saved across multiple requests.

Module 1: Working with Microsoft ASP.NET 19


To understand how server controls work, consider an example.
The following example is a simple form that allows you to type your name and
select your job title from a list box.

<FORM r unat ="ser ver ">
Name: <I NPUT t ype=" t ext " r unat =" ser ver " >
<p>Pr of essi on: <SELECT r unat =" ser ver " >
<OPTI ON> Sof t war e Engi neer </ OPTI ON>
<OPTI ON> Sof t war e Test er </ OPTI ON>
<OPTI ON> Pr ogr amManager </ OPTI ON>
</ SELECT>
<p><I NPUT t ype=" Submi t " Val ue=" Save" r unat =" ser ver " >
</ FORM>

Assume that a software engineer named Jane fills in and submits this form.
When your ASP.NET code is executed, it does the following:
1. Creates the action and method attributes of the form so that the values of
the controls in the form are posted back to the same page.
2. Adds a unique id and name attribute to the form. However, if you specify
these on the form tag, the values that you specify will be used.
3. For each control, adds the value attribute with the text value that was in the
control when the form was submitted. This maintains the state of the server
controls.
4. Adds a hidden control named __VIEWSTATE to the form that stores state
changes of a page.


Example
20 Module 1: Working with Microsoft ASP.NET


This is the HTML that is returned to the browser:
<FORM name=" ct r l 1" met hod=" post " act i on=" ser ver _cont r ol s. aspx"
i d=" ct r l 1" >
<I NPUT t ype=" hi dden" name=" __VI EWSTATE"
val ue="a0z- 1466413384__x">

Name: <I NPUT val ue=" J ane" name=" ct r l 3" t ype=" t ext " >
<p>
Pr of essi on: <SELECT name="ct r l 5">
<OPTI ON val ue=" Sof t war e Engi neer " >
Sof t war e Engi neer </ OPTI ON>
<OPTI ON val ue=" Sof t war e Test er " >
Sof t war e Test er </ OPTI ON>
<OPTI ON sel ect ed val ue=" Pr ogr amManager " >
Pr ogr amManager </ OPTI ON>
</ SELECT>
<p>
<i nput t ype=" submi t " val ue=" Save" >
</ FORM>


Module 1: Working with Microsoft ASP.NET 21


Demonstration: Adding Server Controls to an ASP.NET Page

*****************************illegal for non -trainer use******************************
In this demonstration, you will see how to add HTML server controls to an
ASP.NET page.
To run this demonstration
1. Open the file <install folder>\Democode\Mod01\server_controls.aspx with
Microsoft Notepad.
This file has a form with an input box, a list box, and a Submit button.
2. View the page in Internet Explorer.
3. Enter information in the controls and click Save.
When the page is re-displayed, the information in the controls is lost.
4. Edit the page and add a runat="server" attribute to the three controls.
5. View the page in the browser again. View the source of the page to show
the changes that were made.
Among other changes made, a name attribute was added to each control.
6. Enter information in the controls and click Save. The controls still lose their
values.
7. Edit the page and add a runat="server" attribute to the form.
8. View the page in the browser again. View the source of the page to show
the changes that were made.
Among other changes made, action and method attributes were added to
the form and a hidden control was created.
9. Enter information in the controls and click Save. The controls now save
their values.

22 Module 1: Working with Microsoft ASP.NET


10. Edit the page and add an intrinsic label Web control to the page:
<asp: l abel i d=" l abel 1" r unat =" ser ver " / >

11. View the page in the browser and show the source of the page.
The intrinsic control generates a <span> element.

To demonstrate how to use Microsoft Visual Studio .NET
1. Open Visual Studio .NET and create a new Visual Basic ASP.NET Web
Application project.
A number of files are added to the project by default. For most of the course,
we will be working only with ASPX files.
An ASPX file, WebForm1.aspx, is created by default and opened in Design
view.
2. In the Solution Explorer window, click the Show All Files button.
3. By default, a number of windows are opened in Visual Studio .NET.
Windows can be pinned to the work area, or open only when you want to
see them. Click the Auto Hide button in the upper right corner of the
Solution Explorer window. Now the window will open only when you
hover over or click its tab on the side of the workspace.
4. Click the Toolbox tab to display the toolbox window.
5. Add a text box and a button to the default Web form by dragging and
dropping the controls from the toolbox onto the page.
The Properties window is a great way to learn about the properties of the
Web controls.
6. A code-behind page is created by default for the ASPX page named
WebForm1.aspx.vb. Double-click the button to create an OnClick event
procedure in the code-behind page.

You will not be using this feature of Visual Studio .NET in this
course. You will create event procedures manually.

7. Go back to the WebForm1.aspx page and click the HTML tab to go into
HTML view.
By default, ASPX pages are created with code-behind pages. To remove this
feature, delete all the attributes in the @Page directive except the Language
attribute.
8. Add an HTML text box to the default form. Microsoft IntelliSense is built
into Visual Studio .NET and supplies many of the attributes of the control.
<i nput t ype=" t ext " r unat =" ser ver " >

9. Add a <script> section to the page by right-clicking on the page, clicking
Insert Script Block, and then clicking Server.
10. To view the page, right-click and click View in Brows er.


Note
Module 1: Working with Microsoft ASP.NET 23


u Adding ASP.NET Code to a Page
n Creating an ASP.NET <SCRIPT> Section
n Visual Basic 6.0 vs. Visual Basic. NET Version 7.0
n Creating Event Procedures
n Demonstration: Adding Code to Controls

*****************************illegal for non-trainer use******************************
ASP.NET introduces a new way of coding that is very similar to coding in
event-driven languages, such as Visual Basic and dynamic HTML (DHTML)
scripting. In this section, you will learn how to create a basic ASP.NET page.
You will learn about the major differences between Visual Basic version 6.0
and Visual Basic .NET version 7.0. Finally, you will also learn how to add
functionality to the controls on an ASP.NET page.

24 Module 1: Working with Microsoft ASP.NET


Creating an ASP.NET <SCRIPT> Section
n Declaring the Language
n Declaring Functions and Subroutines
<script language="VB" runat="server">
<script language="C#" runat="server">
<script language="VB" runat="server">
<script language="C#" runat="server">
<SCRIPT LANGUAGE="VB" runat="server">
Sub login ()
'contents of routine
End Sub
</SCRIPT>
<SCRIPT LANGUAGE="VB" runat="server">
Sub login ()
'contents of routine
End Sub
</SCRIPT>

*****************************illegal for non-trainer use******************************
Most code in an ASP.NET page is placed in <SCRIPT> sections. You can use
the ASP <% and %> syntax, but it is not the preferred method. Although
<% %> code blocks provide a powerful way to custom-manipulate the text
output returned from an ASP.NET page, they do not provide much help in
providing a clean HTML programming model. Developers using only <% %>
code blocks must custom-manage page state between round trips and custom
interpret posted values.
When you create a <SCRIPT> section for server-side code, you need to declare
the language being used for the code and set the runat attribute to "server". The
default language is Visual Basic, which is a superset of Microsoft Visual Basic
Scripting Edition (VBScript). For example, the following code example
declares Visual Basic as the language.
<SCRI PT LANGUAGE=" VB" r unat =" ser ver " >

In ASP.NET, you declare functions and sub-procedures within the <SCRIPT>
tags.
<SCRI PT LANGUAGE=" VB" r unat =" ser ver " >
Sub l ogi n( )
' cont ent s of r out i ne
End Sub
</ SCRI PT>


Module 1: Working with Microsoft ASP.NET 25


Visual Basic 6.0 vs. Visual Basic .NET Version 7.0
n No More Set and Let
n Need to Use Parentheses When Calling Functions and
Sub-Procedures
n Parameters Are Passed by Value
n You Can Specify the Data Type of a Variable; Variants
Are Not Supported
n Variables Can Be Initialized When They Are Declared
n Improved Type Safety
n Structured Error Handling with Try/Catch/Finally
n New Conversion Methods

******************** *********illegal for non-trainer use******************************
Visual Basic .NET version 7.0 is very different from earlier versions. Following
are some of the major differences between Visual Basic .NET version 7.0 and
earlier versions of Visual Basic .
n No more Set and Let
You assign values to object variables; you no longer use the Set syntax.
This is because the concept of default properties and methods does not exist
any more. Furthermore, when comparing objects, you must use the is
operator, not the = operator:
obj Thi s i s obj That

n Use parentheses when calling functions and sub-procedures
All methods, functions, and sub-procedures must now use parentheses to
enclose the parameter list.
Response. Wr i t e ( Hel l o)

n Parameters are passed by value
Previously, parameters were passed by reference in Visual Basic. Now they
are passed by value. You can add the ByRef keyword to the parameter list if
you want to pass a parameter by reference.

26 Module 1: Working with Microsoft ASP.NET


n Declaring variables
As in Visual Basic 6.0, you can specify the data type of a variable when you
declare it. However, the Variant data type is no longer supported in Visual
Basic .NET.
Di mst r Name as St r i ng
Di mst r Ti t l e, st r Addr ess as St r i ng

You can turn on Option Explicit by setting the Explicit attribute of the
@Page directive to true.
<%@Page Language=" vb" Expl i ci t =" t r ue" %>

n Initializers
Visual Basic .NET version 7.0 supports initialization of variables on the line
in which they are declared. Initializers can be used anywhere, including
inside a control structure. The semantics of a procedure-level declaration,
which include an initalizer, are the same as those for a declaration statement
immediately followed by an assignment statement. In other words, the
following statement:
Di mX As I nt eger = 1

is equivalent to these statements:
Di mX As I nt eger
X = 1

n Type Safety
Visual Basic .NET version 7.0 offers improved type safety by generating
errors when a conversion that could fail at run time or is unexpected by the
user is required.
n Structured Error Handling
In the past, developers needed to provide error-handling code in every
function and subroutine. Developers have found that a consistent error-
handling scheme means writing a great deal of duplicated code.
With Try...Catch...Finally, these problems are eliminated. Developers can
nest their exception handling, and there is a control structure for writing
cleanup code that executes in both normal and exception conditions.
Sub SEH( )
Tr y
Open " TESTFI LE" For Out put As #1
Wr i t e #1, Cust omer I nf or mat i on
Cat ch
Ki l l "TESTFI LE"
Fi nal l y
Cl ose #1
End t r y
End Sub

n New Conversion Methods
Visual Basic .NET supports new conversion methods such as ToString for
converting data types. You can still use conversion functions such as CStr,
but ToString is the recommended method.


Module 1: Working with Microsoft ASP.NET 27


Creating Event Procedures
n Assign a Method Name to the Event Attribute
n Create an Event Procedure in Your Page Code
n Access Properties of Controls in the Event Procedure
<input type="submit" value="Submit!"
onServerClick="GreetMe" runat="server">
<input type="submit" value="Submit!"
onServerClick="GreetMe" runat="server">
Sub GreetMe(s As Object, e As EventArgs)
Sub GreetMe(s As Object, e As EventArgs)
Sub GreetMe(s As Object, e As EventArgs)
spnGreeting.InnerHTML = "Hello " & _
txtName.Value
End Sub
Sub GreetMe(s As Object, e As EventArgs)
spnGreeting.InnerHTML = "Hello " & _
txtName.Value
End Sub

*****************************illegal for non-trainer use******************************
You can create event handlers for server controls by using the ASP.NET syntax.
In the event handlers, you can access the properties of a control.
To create event handlers by using the ASP.NET syntax
1. In the tag for the control, assign a method name to the name of the event.
For example:
<i nput t ype=" submi t " val ue=" Submi t ! "
onSer ver Cl i ck=" Gr eet Me" r unat =" ser ver " >

OnClick is a client-side event, whereas OnServerClick is a server-
side event for an HTML button.

2. Create an event-handling sub-procedure in your page code and access the
properties of a control. The event handler takes two parameters as shown in
the following sample code:
Sub Gr eet Me( s As Obj ect , e As Event Ar gs)
spnGr eet i ng. I nner HTML = " Hel l o " & t xt Name. Val ue
End Sub



Note
28 Module 1: Working with Microsoft ASP.NET


Event arguments
All events pass two arguments to the event procedure: the sender of the event,
and an instance of the class that holds data for the event, if any. The second
argument is usually of type EventArgs and often does not contain any
additional information but, for some controls, it is of a type specific to that
control.
For example, for an ImageButton Web control, the second argument is of the
type ImageClickEventArgs, which includes information about the coordinates
where the user clicked. The following event procedure outputs the coordinates
of the click in a label control:
Sub i mg_OnCl i ck( s As Obj ect , e As I mageCl i ckEvent Ar gs)
l abel 1. Text = e. x & ", " & e. y
End Sub


Module 1: Working with Microsoft ASP.NET 29


Demonstration: Adding Code to Controls

*****************************illegal for non -trainer use******************************
In this demonstration, you will see how to add event procedures to an ASP.NET
page.
The file <install folder>\Democode\Mod01\eventproc.aspx has the completed
code for this demonstration.
To run this demonstration
1. Open the file <install folder>\democode\Mod01\server_controls.aspx.
2. Add id attributes to the text box and the list box: txtName and lstTitle.
3. Add an onServerClick attribute to the button that will call the GreetMe
procedure.
<i nput t ype=" submi t " onser ver cl i ck=" Gr eet Me"
val ue=" Save" r unat =" ser ver " >

4. Create a SCRIPT section for server -side code.
<SCRI PT l anguage=" VB" r unat =" ser ver " >

5. Create the GreetMe sub-procedure.
Sub Gr eet Me( s As Obj ect , e As Event Ar gs)
l abel 1. Text = "Hel l o " & t xt Name. Val ue & _
" . I see your occupat i on i s " & l st Ti t l e. Val ue
End Sub

6. View the page in Internet Explorer. When you click the button, the values of
the controls are displayed in the <span> element.
7. View the source of the page. The code is server-side code so it is not
included in the page.


30 Module 1: Working with Microsoft ASP.NET


u Handling Page Events
n Page Event Life Cycle
n Handling Postback Forms
n Demonstration: Using Postback Forms

*****************************illegal for non-trainer use******************************
In this section, you will learn about the event life cycle of an ASP.NET page.
You will learn about using the Load and Unload events of the Page object.
Finally, you will learn how to use the IsPostBack property to handle postback
forms.

Module 1: Working with Microsoft ASP.NET 31


Page Event Life Cycle
Page_Load
Page_Load
Page_Unload
Page_Unload
Textbox1_Changed
Textbox1_Changed
Button1_Click
Button1_Click
Page i s di sposed
Page_Init Page_Init

*****************************illegal for non-trainer use******************************
In ASP.NET, a structured set of events occurs every time a page is viewed. The
event order is:
1. Page_Init
After this event, a page is initialized. This event is responsible for all the
initialization activities. If you want to initialize certain variables and so on,
before a page loads, you declare it in the Page_Init event.
2. Page_Load
The Page_Load event automatically fires every time a page is loaded. It
fires at the beginning of a request after controls are initialized. Because
server controls can be accessed on the server, you can load their data in the
Page_Load event.
Sub Page_Load( s As Obj ect , e As Event Ar gs)
t xt Name. Text = ' val ue f r omdat abase
End Sub

3. Change events
After the Page_Load event, control-specific events are fired. An example of
a control-specific event is a Change event or a Click event.
By default, only Click events submit a form to the server. Change events
are stored in a queue and handled in a random order on the server after the
form is posted.
For example, if a user enters text into a number of controls on a form and
then clicks a submit button, the Change events for the text controls will not
be processed until the form is sent to the server by the Click event.

32 Module 1: Working with Microsoft ASP.NET


4. Click event
Whatever event caused the posting of the form fires after all Change events
have completed.
5. Page_Unload
The Page_Unload event is the last event fired before the page is discarded.
This event is fired when the user goes to another page. You cannot read the
values of controls in the Page_Unload event because by the time the event
fires, the controls no longer exist. Page_Unload events are useful for
cleanup activities such as logging, closing files, closing databases, and
discarding objects.
Sub Page_Unl oad( s As Obj ect , e As Event Ar gs)
MyApp. LogPageCompl et e( )
End Sub



Module 1: Working with Microsoft ASP.NET 33


Handling Postback Forms
n ViewState Control Maintains the State of a Page During
Postback
n Page_Load Fires on Every Request
l Use Page.IsPostBack to execute conditional logic
Sub Page_Load(s As Object, e As EventArgs)
If Not Page.IsPostBack Then
'executes only on initial page load
End If
'Rest of procedure executes on every request
End Sub
Sub Page_Load(s As Object, e As EventArgs)
If Not Page.IsPostBack Then
'executes only on initial page load
End If
'Rest of procedure executes on every request
End Sub

*****************************illegal for non-trainer use******************************
If you do not specify an action attribute on a form, ASP.NET pages post back to
themselves. The __VIEWSTATE hidden control on a form maintains the state
on the form so that the values previously entered do not disappear. This is very
useful for form validation and building dynamic pages.
However, code in the Page_Load event runs each time the page is loaded. This
code could re-execute data lookup to fill a list box, which is unnecessary, or
override previous selections made by the user and maintained by the
__VIEWSTATE control.
The IsPostBack property of the Page object is a Boolean value that is set to
True whenever the page is posted back. This property can be used in the
Page_Load event to specify which code in the Page_Load event run should
run on every page load, and which should run only the first time the page is
loaded.
For example, in the following code sample, the IsPostBack property is used to
ensure that the text box is filled in only the first time.
Sub Page_Load( s As Obj ect , e As Event Ar gs)
I f Not Page. I sPost Back Then
' execut es onl y on i ni t i al page l oad
t xt Comment . Val ue = " i ni t i al val ue"
End I f
' Rest of pr ocedur e execut es on ever y r equest
End Sub


34 Module 1: Working with Microsoft ASP.NET


Demonstration: Using Postback Forms

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to use the IsPostBack property of an
ASP.NET page.
The file <install folder>\Democode\Mod01\postback.aspx has the completed
code for this demonstration.
To run this demonstration
1. Open the file <install folder>\Democode\Mod01\server_controls.aspx.
2. Add a Page_Load event procedure that initializes the text box.
Sub Page_Load( s As Obj ect , e As Event Ar gs)
t xt Name. Val ue = " Ent er your name"
End Sub

3. View the page in Internet Explorer. Enter text in the text box and click Save.
The text box is loaded with default text.
4. In the Page_Load event procedure, check for IsPostBack and initialize the
text box only the first time the page is loaded.
I f Not Page. I sPost Back Then
t xt Name. Val ue = " Ent er your name"
End I f

5. View the page again. Enter text in the text box and click Save.
Now the initial text is displayed only the first time the page is displayed.


Module 1: Working with Microsoft ASP.NET 35


Discussion: ASP vs. ASP.NET

*****************************illegal for non-trainer use******************************


36 Module 1: Working with Microsoft ASP.NET


Lab 1: Using ASP.NET to Output Text

*****************************illegal for non -trainer use******************************
Objectives
After completing this lab, you will be able to:
n Integrate HTML server controls in an ASP.NET page
n Write page event procedures and event procedure for server controls in an
ASP.NET page

Prerequisite
Before working on this lab, you must know how to create an HTML page.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab01\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab01\Solution.
Scenario
A user must type an e-mail name and password in order to sign into the
conference system. This is done on the login.aspx page. In this lab, you will
first create an ASP.NET page with HTML server controls and then create event
procedures for the button.
Estimated time to complete this lab: 60 minutes

Module 1: Working with Microsoft ASP.NET 37


Exercise 1
Creating an ASP.NET Page
In this exercise, you will create a simple ASP.NET page with a form, two
HTML text boxes, an HTML button, and an HTML <span> element. You will
then create an event procedure for the button.
To create the Web application
1. Using Microsoft Visual Studio .NET, create a new Web project named
ASPNET.
a. On the File menu, click New, and then click Project.
b. In the New Project dialog box, click ASP .NET Web Application, set
the Name to ASPNET, and then click OK.
Visual Studio .NET creates a virtual root named ASPNET, and the
following files:
aspnet.vbproj
aspnet.vbproj.webinfo
aspnet.vsdisco
AssemblyInfo.vb
Global.asax
Global.asax.resx
Global.asax.vb
Styles.css
Web.config
WebForm1.aspx
WebForm1.aspx.resx
WebForm1.aspx.vb
2. Add the starter lab files to the project.
a. On the Project menu, click Add Existing Item.
b. In the Add Existing Item dialog box, navigate to the
<install folder>\Labs\Lab01\Starter folder.
c. Select All Files (*.*) in the Files of type list box.
d. Select all 19 files, and then click Open.

When copying the files, you will be asked if you want to replace the
existing Web.config file. Click Yes. You will also be asked multiple times if
you want to create a new class file. Click No for each new class file that you
are asked to create.


Note
38 Module 1: Working with Microsoft ASP.NET


e. Start Windows Explorer and navigate to the
<install folder>\Labs\Lab01\Starter folder.
f. Select the bin, Components, and images folders and drag them to the
root of the ASPNET Web site in the Visual Studio .NET Solution
Explorer window.

When copying the folders, you will be asked if you want to replace
the bin directory. Click Yes.


To create a blank .aspx page
1. Open the WebForm1.aspx file.
2. Click the HTML tab (at the bottom of the page) to view the contents of the
page.
3. Delete all attributes except the Language attribute from the @Page
directive at the top of the page.
The @Page directive should look like the following:
<@Page Language=" vb" %>

4. Save the page as login.aspx.

To add a SCRIPT section
1. Add a SCRIPT section to the beginning of the login.aspx page (just before
the <HTML> tag).
2. Set the Language attribute to Visual Basic.
Your script section should look the following:
<scr i pt l anguage=" VB" r unat =" ser ver " >

</ scr i pt >


To create the logon form
1. Add text and HTML server controls to the default form section of the file
to make it look like the following illustration. Be sure to add a <span> tag
after the Sign In Now button.


Note
Module 1: Working with Microsoft ASP.NET 39


Use the following table to create the controls:
Control Attributes

E-mail type = "text "
id = "txtEmail"
Listbox (select) id = "selMailClient"
Password type = "password"
id = "txtPassword"
Button type = "submit"
value = "Sign In Now"
Span id = "spnInfo"

Your form should look like the following:
<f or mi d=" WebFor m1" met hod=" post " r unat =" ser ver " >
Emai l : <br >
<i nput t ype=" t ext " i d=" t xt Emai l " r unat =" ser ver " >
<br ><br >
What ki nd of mai l cl i ent do you use: <br >
<sel ect i d=" sel Mai l Cl i ent " r unat =" ser ver " >
</ sel ect >
<br ><br >
Passwor d: <br ><i nput t ype=" passwor d" i d=" t xt Passwor d"
r unat =" ser ver " ><br ><br >
<i nput t ype=" submi t " val ue=" Si gn I n Now"
r unat =" ser ver " >
<span i d=" spnI nf o" r unat =" ser ver " > </ span>
</ f or m>

2. Fill the listbox server-control with the following options:
Microsoft Outlook
Microsoft Outlook Express
Web-based
3. Make the first option the default selection.
Your HTML for the list box should look the following:
<sel ect i d=" sel Mai l Cl i ent " r unat =" ser ver " >
<opt i on sel ect ed>Mi cr osof t Out l ook</ opt i on>
<opt i on>Mi cr osof t Out l ook Expr ess</ opt i on>
<opt i on>Web- based</ opt i on>
</ sel ect >



40 Module 1: Working with Microsoft ASP.NET


To add an event procedure for the button
1. Set the onServerClick attribute of the button to cmdLogin_Click.
2. In the <script> section, create the cmdLogin_Click event procedure.
3. Display the contents of the controls in the spnInfo SPAN element.
To see all the comments written to the spnInfo SPAN element, concatenate
the spnInfo.innerHTML content with the values from the other controls.
Your event procedure should look like the following:
Sub cmdLogi n_Cl i ck( s As Obj ect , e As Event Ar gs)
spnI nf o. i nner HTML = spnI nf o. i nner HTML & _
"Your emai l : " & _
t xt Emai l . Val ue & _
"<br >Your mai l cl i ent i s: " & _
sel Mai l Cl i ent . Val ue & _
"<br ><br >"
End Sub


To save and test your work
1. Save your changes.
2. Using Microsoft Internet Explorer, go to the login page of the ASPNET
Web site by viewing http://localhost/ASPNET/login.aspx.
3. Fill the Email field with your e-mail address and click Sign In Now.
You should see your e-mail address at the bottom of the page.


Module 1: Working with Microsoft ASP.NET 41


Exercise 2
Creating Page Event Procedures
In this exercise, you will add page event procedures to the page.
To add a Page Load event procedure
1. In the script section, add a Page_Load event procedure that displays the
value of Page.IsPostBack.
Concatenate the value of the IsPostBack property with the current text in
the spnInfo element.
Your event procedure should look like the following:
Sub Page_Load( s As Obj ect , e As Event Ar gs)
spnI nf o. i nner HTML = spnI nf o. i nner HTML & _
" One mor e Page_Load event ! <br >" & _
"Page. I sPost Back=" & _
Page. I sPost Back. ToSt r i ng( ) & _
"<br ><br >"
End Sub

2. Save your changes.
3. Using Internet Explorer, go to the logon page of the ASPNET Web site by
viewing http://localhost/ASPNET/login.aspx.
Notice the message on the page.
4. Click Sign In Now.
Notice the postback message.


42 Module 1: Working with Microsoft ASP.NET


Review
n Introducing ASP.NET
n Creating Web Forms
n Adding ASP.NET Code to a Page
n Handling Page Events
n Discussion: ASP vs. ASP.NET

*****************************illegal for non-trainer use******************************
1. List some of the differences between ASP and ASP.NET.


2. What are the main features of ASP.NET?


3. What attribute is used to denote server controls?


4. How is the view state of controls maintained?



Module 1: Working with Microsoft ASP.NET 43


5. How do you create an event procedure for the click event of an HTML
button control?


6. What is the order of events that occur when a page is displayed?






THIS PAGE INTENTIONALLY LEFT BLANK









Contents
Overview 1
What Are Web Controls? 2
Using Intrinsic Controls 4
Using Input Validation Controls 16
Selecting Controls for Applications 28
Lab 2: Using Web Controls 29
Review 40

Module 2: Using
Web Controls


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 2: Using Web Controls 1


Overview
n What Are Web Controls?
n Using Intrinsic Controls
n Using Input Validation Controls
n Selecting Controls for Applications

*****************************illegal for non-trainer use******************************
Web controls are designed to provide a simple way to add functionality, such as
displaying data or selecting dates, to a Web page. Web controls include
traditional form controls, such as buttons and text boxes, and complex controls,
such as tables and the calendar control.
After completing this module, you will be able to:
n Add Web controls to a Microsoft ASP.NET page.
n Use properties, methods, and events of Web controls.
n Validate user input on an ASP.NET page by using input validation controls.
n Bind two controls together.

2 Module 2: Using Web Controls


What Are Web Controls?
n HTML Controls
n Web Controls
l Intrinsic controls
asp:list, asp:button, asp:checkbox, asp:table
l Input Validation controls
asp:RangeValidator, asp:RegularExpressionValidator
l Rich controls
asp:calendar, asp:adrotator
l List-bound controls
asp: datagrid, asp:repeater, asp:datalist

*****************************illegal for non-trainer use******************************
ASP.NET uses server controls extensively to simplify the task of programming
Web pages. You can change many Hypertext Markup Language (HTML)
elements into server controls by adding the runat=server attribute to the
element tag. However, ASP.NET includes new controls, called Web controls,
which have built-in functionality and are the preferred controls to use in an
ASP.NET page.
Web controls include traditional form controls, such as buttons and text boxes,
and complex controls, such as tables. They also include controls that provide
commonly used form functionality such as displaying data in a grid, choosing
dates, and so on.
There are four sets of Web controls in ASP.NET:
n Intrinsic controls map to simple HTML elements.
n Validation controls provide a variety of data validation.
n Rich controls provide rich user interface and functionality. Currently
ASP.NET ships with two rich controls, the Calendar and the AdRotator
controls.
n List-bound controls provide data flow across a page.
The DataGrid, DataList, and Repeater controls constitute an interrelated
set of Web controls. These controls render HTML to display the contents of
a list or data source to which they are bound. Hence, they are collectively
referred to as list-bound controls.


For more information about displaying data from databases, see
Module 3, Using Microsoft ADO.NET to Access Data, in Course 2063B,
Introduction to Microsoft ASP.NET.


Note
Module 2: Using Web Controls 3


Web controls exist within the System.Web.UI.WebControls namespace. You
create them by using the asp: namespace. You do not need to import this
namespace into your .aspx page to use these controls. For example, the
following sample code creates a button Web control:
<asp: But t on r unat =" ser ver " / >

All controls must be well-formed and must not overlap. Unless otherwise
noted, elements must be closed, either with an ending slash within the tag or
with a closing tag. For example, <asp:Button runat="server" /> or < asp:Button
runat="server" > </asp:Button>.

For more information about the Web controls available with ASP.NET, see
ASP.NET Syntax for Web Controls in the .NET Framework SDK
documentation.

Note
4 Module 2: Using Web Controls


u Using Intrinsic Controls
n What Are Intrinsic Controls?
n List of Intrinsic Controls
n Handling Intrinsic Control Events
n Demonstration: Adding Intrinsic Controls to a Page
n Linking Two Controls Together
n Demonstration: Linking Two Controls Together

*****************************illegal for non-trainer use******************************
Intrinsic controls are designed to replace the standard set of HTML controls.
This section describes intrinsic controls and explains how to use them in an
ASP.NET page.

Module 2: Using Web Controls 5


What Are Intrinsic Controls?
<asp:CheckBox Checked="True" ... />
<asp:CheckBox Checked="True" ... />
n Provide Standard Naming Convention, with
Standard Properties for Controls
n Include Properties Specific to the Control
n Create Browser-Specific HTML
<asp:RadioButton BackColor="red" Text=" "... />
<asp:CheckBox BackColor="red" Text=" "... />
<asp:RadioButton BackColor="red" Text=" "... />
<asp:CheckBox BackColor="red" Text=" "... />
<span>
<input type="checkbox" id="ctrl1"
checked="true" name="ctrl1">
<label for="ctrl1">Standard</label>
</span>
<span>
<input type="checkbox" id="ctrl1"
checked="true" name="ctrl1">
<label for="ctrl1">Standard</label>
</span>

*****************************illegal for non-trainer use******************************
Intrinsic controls are used as an alternative to HTML controls. You use Web
controls in the same way that you use HTML controls. The most important
difference is the prefix tag asp: that is added before every Web control. For
example, you can add a Label control to a form by using the following line of
code:
<asp: Label r unat =" ser ver " Text =" Label 1" ></ asp: Label >

Intrinsic Web controls provide the following benefits:
n Provide a standard naming convention for similar controls
n Provide common properties for all controls
n Include strongly typed properties that are specific to the control
n Create browser-specific HTML

Standard Naming Convention
One of the problems with HTML controls has been the lack of a consistent
naming convention for similar controls. Intrinsic controls eliminate this
problem, as shown in the following examples.
Example 1
The following lines of code declare a radio button, a check box, and a button.
<i nput t ype =" r adi o" >
<i nput t ype =" checkbox" >
<i nput t ype =" submi t " >

All of these controls are input controls; however, they all behave in different
ways.

6 Module 2: Using Web Controls


Intrinsic controls provide an alternative way to declare different controls. The
following lines of code use intrinsic Web controls to declare a radio button, a
check box, and a button:
<asp: Radi oBut t on>
<asp: CheckBox>
<asp: But t on>

Include Common Properties for Controls
In ASP.NET, common properties for intrinsic controls have the same name. For
example, when you want to set the background color for a control, you always
use the same attribute irrespective of the control. For example, all controls have
a Text property that sets the text corresponding to the control. Controls also
have BackColor and ForeColor properties. Setting the BackColor="red"
property sets the background color to red for any control.
<asp: t ext box i d=" t xt Name" Text =" J ane" BackCol or =" r ed"
r unat ="ser ver " / >

<asp: But t on i d=" bt nSubmi t " Text =" Submi t " BackCol or =" cyan"
r unat ="ser ver " / >

Control-Specific Properties
Intrinsic Web controls also have a set of properties that relate specifically to the
control.
Check Box
For example, a check box has a Checked property that indicates whether the
check box is checked or not.
The following sample code creates a check box labeled Standard that is initially
checked.
<asp: CheckBox Checked=" Tr ue" Text =" St andar d" r unat =" ser ver " / >

List Box
Some properties of Web controls are available only at run time. For example,
the list box and drop-down list boxes have the SelectedItem property that
returns either the value or text of the item selected in the list box.


Module 2: Using Web Controls 7


Create Browser-Specific HTML
Although Web controls are easily added to a page, they are powerful controls.
When a page is rendered for a browser, the Web controls determine which
browser is requesting the page and then deliver the appropriate HTML.
For example, if the requesting browser supports client-side scripting, such as
Microsoft Internet Explorer version 4.0 or later, the controls create client-side
script to implement their functionality. But, if the requesting browser does not
support client-side script, the controls create server-side code and require more
round trips to the server to obtain the same functionality.
For example, the HTML generated for the above check box in Internet Explorer
5.5 is:
<span>
<i nput t ype=" checkbox" i d=" ct r l 1" checked=" t r ue" name=" ct r l 1" >
<l abel f or =" ct r l 1" >St andar d</ l abel >
</ span>


8 Module 2: Using Web Controls


List of Intrinsic Controls
n List of Intrinsic Controls
<asp:textbox> <asp:button> <asp:checkbox>
<asp:hyperlink> <asp:linkbutton> <asp:imagebutton>
<asp:image> <asp:label> <asp:radiobutton>
<asp:panel> <asp:table>
<asp:dropdownlist id="favColor" runat="server">
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Red</asp:listitem>
<asp:listitem>Green</asp:listitem>
</asp:dropdownlist>
<asp:dropdownlist id="favColor" runat="server">
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Red</asp:listitem>
<asp:listitem>Green</asp:listitem>
</asp:dropdownlist>

*****************************illegal for non-trainer use******************************
ASP.NET intrinsic controls include traditional form controls, such as buttons
and text boxes, and complex controls, such as tables.
Examples of Intrinsic Controls
The following table lists some of the intrinsic Web controls and their
corresponding HTML controls.
Web control HTML control

<asp: t ext box> <i nput t ype=t ext >
<asp: but t on> <i nput t ype=submi t >
<asp: i magebut t on> <i nput t ype=i mage>
<asp: checkbox> <i nput t ype=checkbox>
<asp: r adi obut t on> <i nput t ype=r adi obut t on>
<asp: l i st box> <sel ect si ze=" 5" > </ sel ect >
<asp: dr opdownl i st > <sel ect > </ sel ect >
<asp: hyper l i nk> <a hr ef =""> </ a>
<asp: i mage> <i mg sr c=" " >
<asp: l abel > <span> </ span>
<asp: panel > <di v> </ di v>
<asp: t abl e> <t abl e> </ t abl e>


Module 2: Using Web Controls 9


Adding Intrinsic Controls
Drop-Down List Box
The DropDownList control is used to allow a single selection from a number
of choices displayed as a drop-down list:
You can add a list box to a form by using the following code:
<asp: dr opdownl i st i d=" f avCol or " r unat =" ser ver " >
<asp: l i st i t em>Bl ue</ asp: l i st i t em>
<asp: l i st i t em>Red</ asp: l i st i t em>
<asp: l i st i t em>Gr een</ asp: l i st i t em>
</ asp: dr opdownl i st >

Label
You can add a label control to a form as follows:
<asp: Label r unat =" ser ver " Text =" Label 1" Font -
I t al i c="t r ue"></ asp: Label >

Check box
The CheckBox control is used to generate a check box that can be toggled
between selected and cleared states:
<asp: CheckBox r unat =" ser ver " Text =" CheckBox1"
Checked=" Tr ue" ></ asp: CheckBox>

For more information about the properties and events associated with the
intrinsic controls, see the .NET Framework SDK documentation.

10 Module 2: Using Web Controls


Handling Intrinsic Control Events
n Web Controls Support Only Server-Side Events
n Web Controls Have a Limited Number of Events
n Only Click Events Cause the Form to Be Posted Back to
the Server
n Set the AutoPostBack Property to TRUE to Force
Postbacks
<asp:button id="btn" runat="server"
onclick="btn_Click" />
<asp:button id="btn" runat="server"
onclick="btn_Click" />
Sub btn_Click(s As Object, e As EventArgs)
Sub btn_Click(s As Object, e As EventArgs)

*****************************illegal for non-trainer use******************************
Events in Web forms work differently than events in traditional client forms or
in client-based Web applications. In client-based applications, events are raised
and handled on the client. In Web forms, all events are raised on the client but
handled on the Web server.
Web controls support server-side events only. Web controls have a limited
number of events because all events are server-side events and cause a round
trip to the server. They support click-type events. Some server controls also
support a special version of an onChange event, such as SelectionChanged,
which is raised when the control's value changes. However, mouse-key events
are not supported.
Using Event Procedures
As with HTML control events, writing event handlers for Web controls is a
two-step procedure. You need to set up the event handler in the controls tag,
and then write the event procedure itself.
For example, you set up a click event for a button control as follows:
<asp: but t on i d=" bt n" r unat =" ser ver " oncl i ck=" bt n_Cl i ck" / >

The button Web control has only an OnClick event, not an
OnServerClick event.

You then write the event procedure as follows:
Sub bt n_Cl i ck( s As Obj ect , e As Event Ar gs)

End Sub


Note
Module 2: Using Web Controls 11


For more information on the events available for intrinsic controls, see the
Microsoft .NET Framework SDK documentation.

Web controls do not support client-side events. HTML controls have
both server-side and client-side events.

Using AutoPostBack
In Web controls, by default, only click events cause the form to be posted to the
server. Change events are captured, but do not immediately cause a postback.
Instead, they are cached by the control until the next time a post occurs. Once
the form is posted to the server, the associated event procedures will run.
During server page processing, all change events are processed first, in no
particular order. When all change events have been processed, the click event
that caused the form to be posted is processed.
You can specify a change event to cause a form postback, and thus run the
event procedure immediately, by setting the AutoPostBack property to True.
For example, you can set up a change event for a list box with the following tag:
<asp: dr opdownl i st i d=" l st Ti t l e" r unat =" ser ver "
onSel ect edI ndexChanged=" l st _change" >

However, until you set the autoPostBack property to True, the lst_change
event procedure will run only when the form is posted to the server in response
to a click event of a button.

Note
12 Module 2: Using Web Controls


Demonstration: Adding Intrinsic Controls to a Page

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to add intrinsic Web controls to an
ASP.NET page. You will see the HTML generated by this page for Internet
Explorer and understand what happens when you add intrinsic controls to a
form. Next, you will learn how to add event procedures for the controls.
The file <install folder>\Democode\Mod02\demo1.aspx has the completed
code for this demonstration.
To run the demonstration
1. Open intrinsic.aspx from the <install folder>\Democode\Mod02 folder.
There are three intrinsic controls in this file: a text box, a list box, and a
button, plus two <span> elements. There are also event procedures created
for the button and the list box.
2. View the page in Internet Explorer. Enter text in the text box and click Save.
Nothing happens when you click the button or select an item in the list box.
Events are fired only for controls on forms.
3. Edit the page and add a form with the runat="server" attribute to the page
to hold the controls.
4. View the page in Internet Explorer again. Enter text in the text box and click
Save.
View state is now preserved for the text box and the list box. The button
procedure runs when you click the button, but the list box event procedure
does not fire until the button is clicked.
5. Edit the page and set the AutoPostBack attribute of the list box to True.
6. View the page in Internet Explorer again. Enter text in the text box and click
Save.
The list box event procedure fires immediately when you select an item.


Module 2: Using Web Controls 13


Linking Two Controls Together
n Binding One Control to Another Is Useful for Taking
Values from List Boxes or Drop-Down Lists
n Data Binding
<asp:DropDownList id="lstLocation"
autoPostBack="True" runat="server" >
You selected: <asp:Label id="SelectedValue"
Text="<%# lstLocation.SelectedItem.Text %>"
runat="server" />
<asp:DropDownList id="lstLocation"
autoPostBack="True" runat="server" >
You selected: <asp:Label id="SelectedValue"
Text="<%# lstLocation.SelectedItem.Text %>"
runat="server" />
Sub Page_Load (s As Object, e As EventArgs)
SelectedValue.DataBind()
End Sub
Sub Page_Load (s As Object, e As EventArgs)
SelectedValue.DataBind()
End Sub

*****************************illegal for non-trainer use******************************
You can bind one control to the contents of another. This is particularly useful
for taking values from list boxes or drop-down lists.
The following example demonstrates how to bind a Label control to the
contents of a drop-down list. You set the Text attribute of the Label control to
the Selected Item of the lstLocation list by using the binding tags <%# and
%>:
<asp: Label i d=" Sel ect edVal ue" r unat =" ser ver "
Text =" <%# l st Locat i on. Sel ect edI t em. Text %>" / >


14 Module 2: Using Web Controls


In the following code, notice that the autoPostBack property of the drop-down
list is set to True, which causes automatic post back whenever the value of the
list box changes.
<scr i pt l anguage=" VB" r unat =" ser ver " >
Sub Page_Load ( Sender As Obj ect , E As Event Ar gs)
Sel ect edVal ue. Dat aBi nd( )
End Sub
</ scr i pt >

<f or m r unat ="ser ver ">
<asp: Dr opDownLi st i d="l st Locat i on"
aut oPost Back=" t r ue" r unat =" ser ver " >
<asp: l i st i t em>Bost on</ asp: l i st i t em>
<asp: l i st i t em>New Yor k</ asp: l i st i t em>
<asp: l i st i t em>London</ asp: l i st i t em>
<asp: l i st i t em>Amst er dam</ asp: l i st i t em>
</ asp: dr opdownl i st >
<p>You sel ect ed: <asp: Label i d=" Sel ect edVal ue"
Text ="<%# l st Locat i on. Sel ect edI t em. Text %>"
r unat =" ser ver " / >
</ p>
</ f or m>

You can use Page.DataBind() if you want the page to data bind all elements on
the page. The preceding example binds only the label control to data, and
therefore uses the SelectedValue.DataBind() syntax, where SelectedValue is
the id attribute of the label control.
While this lesson describes using the binding tags <%# and %>, it is often a
better practice to assign values from one control directly to another, rather than
using data binding. The following line of code demonstrates assigning values
from one control to another:
Sel ect edVal ue. Text =l st Locat i on. Sel ect edI t em. Text

For more information about data binding, see Module 3, Using Microsoft
ADO.NET to Access Data, in Course 2063B, Introduction to Microsoft
ASP.NET.

Module 2: Using Web Controls 15


Demonstration: Linking Two Controls Together

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to bind a label control to a list box.
The completed code for this demonstration is in the
<install folder>\Democode\Mod02\binding.aspx page.
To run the demonstration
1. Edit the page you created in the last demo,
<install folder>\Democode\Mod02\intrinsic.aspx
2. Add a label control to the page.
<asp: l abel i d=" l bl Li st box" r unat =" ser ver " / >

3. Bind the label control to the list box by setting its Text attribute.
<asp: l abel i d=" l bl Li st box"
Text =" <%# l st Ti t l e. Sel ect edI t em. Text %> " r unat =" ser ver " / >

4. Create a Page_Load event and call lblListbox.DataBind()
Sub Page_Load( s As Obj ect , e As Event Ar gs)
l bl Li st box. Dat aBi nd( )
End Sub

5. View the page in Internet Explorer.
When you select an item in the list box, the value is reflected in the label
control.


16 Module 2: Using Web Controls


u Using Input Validation Controls
n Input Validation Controls
n Adding Input Validation Controls to a Form
n Validating an Entire Page
n Demonstration: Adding Input Validation Controls
n Advantages of Using Input Validation Controls

*****************************illegal for non -trainer use******************************
In HTML 3.2, validating data is a difficult process. You can run validation code
on the client, on the server, or both. Each time you receive a request, you not
only need to write code that checks the input, you need to write error messages
to help the user to correctly fill in the form. This is a taxing process for users,
developers, and servers.
The introduction of input validation controls in ASP.NET makes the task of
validating input easier than it has been in the past.
In this section, you will learn about the advantages of using input validation
controls. You will also learn how to add these controls to an ASP.NET page.

Module 2: Using Web Controls 17


Input Validation Controls
n RequiredFieldValidator
n CompareValidator
n RangeValidator
n RegularExpressionValidator
n CustomValidator
n ValidationSummary

*****************************illegal for non-trainer use******************************
Validation controls are added to an ASP.NET page like other server controls.
There are controls for specific types of validation, such as range checking or
pattern matching, plus a RequiredFieldValidator control that ensures that a
user does not skip an entry field. Validation controls work with all server
controls.
The validation controls have both uplevel and downlevel client support.
Uplevel browsers perform validation on the client (using JavaScript and
dynamic HTML [DHTML]). Client-side validation enhances the validation
scheme by checking user input as the user enters data. This allows errors to be
detected on the client before the form is submitted, preventing the round trip
necessary for server-side validation. In uplevel checking, if there is an error in
user input, a trip is not made to the server; instead, the associated error
messages are shown on the client.
Downlevel browsers perform validation on the server. Both scenarios use the
same programming model.

More than one input validation control can be associated with a Web
control. For example, there can be required and compare validators for the same
text box Web control.


Note
18 Module 2: Using Web Controls


The following table lists the validation controls included in the ASP.NET
Framework.
Validation control Function

RequiredFieldValidator Checks whether value has been entered into a control.
CompareValidator Compares an input control to a fixed value or another
input control. It can be used for password verification
fields, for example. It is also possible to do typed date
and number comparisons.
RangeValidator Much like CompareValidator, but can check that the
input is between two values or the values of other
input controls.
RegularExpressionValidator Checks that the entry matches a pattern defined by a
regular expression. This type of validation allows you
to check for predictable sequences of characters, such
as those in social security numbers, e-mail addresses,
telephone numbers, postal codes, and so on.
CustomValidator Allows you to write your own code to take part in the
validation framework.
ValidationSummary Displays a summary of all of the validation errors for
all of the validation controls on the page.

For more information about using the input validation controls, see Validation
Server Controls Overview in the .NET Framework SDK documentation.

Module 2: Using Web Controls 19


Adding Input Validation Controls to a Form
n Properties:
l ControlToValidate
l ErrorMessage
l Display
<asp:RequiredFieldValidator id="txtNameValidator"
runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
<asp:RequiredFieldValidator id="txtNameValidator"
runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
<asp:textbox id="txtName" runat="server" />
<asp:textbox id="txtName" runat="server" />

*****************************illegal for non-trainer use******************************
The standard code used to add input validation controls to a form is as follows:
<asp: t ype_of _val i dat or i d=" val i dat or _i d" r unat =" ser ver "
cont r ol ToVal i dat e="cont r ol _i d"
er r or Message=" er r or _message_f or _summar y"
di spl ay="st at i c| dynami c| none" >
</ asp: t ype_of _val i dat or>

In the preceding code, controlToValidate is the ID of the control whose input
is being validated (a text box, in most cases). The errorMessage property is the
error message that is displayed if the input is not valid, and the display property
indicates how the validation control will be rendered in the page. Setting the
display property to static implies that each validation control occupies space
even when no error message text is visible, thereby allowing you to define a
fixed layout for the page. Setting the display property to dynamic means that
the layout of the page changes, sometimes causing controls to move as error
messages are displayed. Validation controls cannot occupy the same space on
the page, so you must give each control a separate location on the page.
In addition to the above-mentioned required properties, each validation control
has more spec ific properties that define how the control should behave. The
following examples show how to add validation controls.

20 Module 2: Using Web Controls


RequiredFieldValidator Control
Use the RequiredFieldValidator control to require input in a field.
The following code shows how to use the RequiredFieldValidator control.
<asp: t ext box i d=" t xt Name" val ue=" Ent er your name"
r unat ="ser ver " / >
<asp: Requi r edFi el dVal i dat or i d=" t xt NameVal i dat or "
r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Name"
er r or Message=" You must ent er your name"
di spl ay="dynami c" >
</ asp: Requi r edFi el dVal i dat or >

RangeValidator Control
To test whether an input value falls within a given range, use the
RangeValidator control.
The RangeValidator control uses three additional properties to perform its
validationMinimumValue, MaximumValue, and type. MinimumValue
and MaximumValue properties define the minimum and maximum values of
the valid range. The type property specifies the data type that that is used in
comparing values.
In the following example, the txtAge field must have a value between 18 and
50. If the value does not fall within the range, an error message is displayed and
no trip to the server occurs.
<asp: t ext box i d=" t xt Age" val ue=" Ent er your age" r unat =" ser ver "
/ >

<asp: RangeVal i dat or i d=" t xt AgeVal i dat or " r unat =" ser ver "
cont r ol ToVal i dat e=" t xt Age"
t ype="I nt eger "
mi ni mumVal ue="18"
maxi mumVal ue="50"
er r or Message=" Appl i cant s must be bet ween 18 and 50"
di spl ay="dynami c">
</ asp: RangeVal i dat or >


Module 2: Using Web Controls 21


CompareValidator Control
To use one control to test the validity of a second control, or to test input
against a specific value, use the CompareValidator control.
The CompareValidator control uses the following additional properties to
perform its validation:
n ValueToCompare or ControlToCompare
Set ValueToCompare to compare to a constant value. Set
ControlToCompare to the ID of another control to compare against. If you
set both ValueToCompare and ControlToCompare, ControlToCompare
takes precedence.
n Type
The data type of the two values to be compared.
n Operator
The comparison operator to use. Operators are specified with the name of
the comparison operators, such as Equal, NotEqual, GreaterThan,
GreaterThanEqual, and so on.

The following code shows an example in the .aspx file of a Web form Textbox
control with required field validation. A table is used to control layout. In the
following example, the txtAge field must have a value greater than or equal to
zero.
<asp: t ext box i d=" t xt Age" r unat =" ser ver " / >
<asp: Compar eVal i dat or i d=" t xt AgeCompar eVal i dat or "
r unat ="ser ver "
Cont r ol ToVal i dat e="t xt Age"
Val ueToCompar e="0"
Type="I nt eger "
Oper at or =" Gr eat er ThanEqual "
Er r or Message="Pl ease ent er a whol e number zer o or gr eat er . ">
</ asp: Compar eVal i dat or >


22 Module 2: Using Web Controls


RegularExpressionValidator Control
You can check whether a user s entry matches a pre-defined pattern, such as a
phone number, postal code, e-mail address, and so on, with the
RegularExpressionValidator control.
Set the ValidationExpression property of the RegularExpressionValidator
control to a regular expression.
The following example shows how you can use a
RegularExpressionValidator control to check whether users enter valid social
security numbers. The control checks for the pattern: three digits, a hyphen, two
digits, a hyphen, and four more digits.
<asp: t ext box i d=" t xt SSN" r unat =" SERVER" / >
<asp: Regul ar Expr essi onVal i dat or i d=" t xt ZI P_val i dat i on"
r unat ="ser ver "
Cont r ol ToVal i dat e=" t xt SSN"
Er r or Message=" Use t he f or mat 123- 12- 1234. "
Val i dat i onExpr essi on="[ 0- 9] {3}- [ 0- 9] {2}- [ 0- 9] {4}" >
</ asp: Regul ar Expr essi onVal i dat or >


Module 2: Using Web Controls 23


Validating an Entire Page
n Page.IsValid Property
n ValidationSummary Control
Sub Submit_click (s A Object, e As EventArgs)
If Page.IsValid Then
Message.Text = "Page is valid!"
End If
End Sub
Sub Submit_click (s A Object, e As EventArgs)
If Page.IsValid Then
Message.Text = "Page is valid!"
End If
End Sub
<asp:ValidationSummary id="valSummary"
runat="server"
headerText= "These errors were found:"
showSummary="True"
displayMode="List" />
<asp:ValidationSummary id="valSummary"
runat="server"
headerText= "These errors were found:"
showSummary="True"
displayMode="List" />

*****************************illegal for non-trainer use******************************
Sometimes you need to know if all the controls on a page are valid before
performing some other action. In fact, in client-side validation, values are sent
across to the server only when all controls are valid.
Page.IsValid Property
ASP.NET developers can check the Page.IsValid property at run time to
determine whether all validation server controls on a page are currently valid.
This provides a short and simple way to determine whether to proceed with
business logic.
Sub Submi t _cl i ck ( s A Obj ect , e As Event Ar gs)
I f Page. I sVal i d Then
Message. Text = " Page i s val i d! "
End I f
End Sub

The validation can be either client-side or server-side, depending on the
browser.


Note
24 Module 2: Using Web Controls


Validation Summary Control
If a validation control is in error, an error message may be displayed in the page
by the validation control or in the ValidationSummary control elsewhere on
the page. The ValidationSummary control is displayed when the IsValid
property of the page is false. Each of the validation controls on the page is
polled and the text messages exposed are aggregated by the
ValidationSummary control.
n The ValidationSummary updates itself without posting back if it detects
errors.
n The ValidationSummary can optionally display a message box to the user
if there are errors.

<asp: Val i dat i onSummar y i d=" val Summar y" r unat =" ser ver "
header Text ="These er r or s wer e f ound: "
showSummar y="Tr ue"
di spl ayMode="Li st " / >

There are two places where you can display error messages to the user: in the
input validation control or in the ValidationSummary control. If there is a
ValidationSummary control on the form, it gathers and displays all
ErrorMessage properties of input validation controls on the form, and the
validation controls themselves display any error text that is contained between
their start and end tags.
If there is no ValidationSummary control, the input validation controls display
the text in the ErrorMessage property.

Module 2: Using Web Controls 25


Demonstration: Adding Input Validation Controls

*****************************illegal for non-trainer use******* ***********************
In this demonstration, you will see how to add input validation controls to text
controls on a form.
The completed code for this demonstration is in the
<install folder>\Democode\Mod02\validation.aspx and
<install folder>\Democode\Mod02\validate_all.aspx pages.
To run the demonstration
1. Edit the page you created in the last demonstration
<install folder>\Democode\Mod02\intrinsic.aspx.
2. Add a RequiredField validator to the txtName text box.
<asp: Requi r edFi el dVal i dat or i d=" t xt NameVal i dat or "
r unat =" ser ver "
cont r ol ToVal i dat e=" t xt Name"
er r or Message="You must ent er your name"
di spl ay="dynami c">
</ asp: Requi r edFi el dVal i dat or >

3. View the page in Internet Explorer. Leave the text box blank and click Save.
The error message from the errorMessage attribute appears.
4. View the source of the page. The input validation control generated client-
side script to do the validation.

26 Module 2: Using Web Controls


5. Add a RangeValidator control to limit the entries to names that start with
"A".
<asp: RangeVal i dat or i d=" t xt NameRngVal i dat or " r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Name"
er r or Message=" Pl ease ent er a name t hat begi ns wi t h ' A' "
t ype="St r i ng"
mi ni mumVal ue="A"
maxi mumVal ue="B"
di spl ay="dynami c">
</ asp: RangeVal i dat or >

6. Set the display attribute of the RequiredFieldValidator to static.
7. View the page in Internet Explorer. Enter invalid text in the text box and
click Save.
The error message from the errorMessage attribute of the RangeValidator
control appears, but it is offset by the area required by the
RequiredFieldValidator.
8. Open the page validate_all.aspx.
There are a number of input validation controls used on this page, and a
validation summary control.
9. View the page validate_all.aspx in Internet Explorer.
When you click the Validate button, the ValidationSummary control
displays all the errorMessage attributes of controls that are not valid.


Module 2: Using Web Controls 27


Advantages of Using Input Validation Controls
n Provide Immediate Feedback to the User
n Create Client-Side and Server-Side Validation
n Uses DHTML and JScript Library to Write Client Logic
n Allow Enhancement of Client-Side Validation and
Behavior

*****************************illegal for non-trainer use******************************
Most Web sites perform their validation checks on the server. However, most
applications also need client-side validation checks. Writing two versions of
validation code for these validation checks can be time-consuming for
developers.
Validation controls eliminate this problem because almost all the duplicated
logic is encapsulated in the controls. Validation controls check controls for a
specific type of error condition and display a description of that problem. In
addition, the controls create browser-specific code, so that, if a client with
Internet Explorer 4.0 or later uses the page, it can perform the same input
validation that takes place on the server without client script.
Using validation controls has the following advantages:
n Provides immediate feedback to the user.
The user gets immediate feedback on whether the data entered is valid or
not. The error messages appear and disappear immediately after the bad
input is entered or corrected.
n Creates client-side and server-side validation.
If the browser supports client-side script, the controls do error checking
before posting the data to the server. This saves the user time and reduces
hits on the server.
n Uses DHTML and a Microsoft JScript library to write client logic.
The client logic is contained in a JScript library, so no Microsoft ActiveX
components or Java applets are used.
n Allows enhancement of client-side validation and behavior.
An object model is exposed on the client to allow enhancement of client-
side validation and behavior.


28 Module 2: Using Web Controls


Selecting Controls for Applications
Use Web Controls When:
l You prefer a Visual
Basic-like programming
model
l You are writing a page
that might be used by a
variety of browsers
l You need specific
functionality such as a
calendar or ad rotator
Use HTML Controls When:
l You prefer an HTML-
like object model
l You are working with
existing HTML pages
and want to quickly add
Web Forms functionality
l The control will interact
with client and server
script

*****************************illegal for non-trainer use******************************
When creating ASP.NET pages, you can use different classes of controls.
You can mix control types on the same page. For example, your ASP.NET page
might include a form made up of Web controls plus an HTML control
converted from an HTML <span> element.
The following table summarizes some of the situations in which you might
decide to use a particular control.
Type of control Use it when

Web control You prefer a Microsoft Visual Basic-like programming model.
You are writing a Web Forms page that might be viewed by a
variety of browsers.
You need specific functionality, such as a calendar or ad rotator,
that is available only as a Web Forms control.
You are creating applications with nested controls and want to be
able to catch events at the container level.
HTML control You prefer an HTML-like object model.
You are working with existing HTML pages and want to quickly
add Web Forms functionality. Because HTML controls map
exactly to HTML elements, any HTML design environment can
support them.
The control will also interact with client and server script.

As a general rule, Web controls are more capable and have a richer object
model than HTML controls. If you want all the processing of an ASP.NET page
to occur on the server, Web controls are a good choice.

Module 2: Using Web Controls 29


Lab 2: Using Web Controls

*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Use Web controls in an ASP.NET page.
n Use input validation controls in an ASP.NET page.
n Display the summary of validation controls in a form.
n Test if a page is valid or not.
n Add a Calendar control to an ASP.NET page.

Prerequisite
Before working on this lab, you must know how to create ASP.NET event
procedures.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab02\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab02\Solution.

30 Module 2: Using Web Controls


Scenario
When users want to reserve a room in a hotel for a conference, they need to
select the type of room and specify the check-in and check-out dates. This is
done on the hotel_reservation.aspx page. In exercises 1 and 2 of this lab, you
will add Web controls to this page.
Before registering for a conference on the Conference Web site, a user needs to
register as an individual. This is done on the register.aspx page. In exercises 3
and 4 of this lab, you will add input validation controls to the register.aspx page
to validate the input for the controls on this page.
Estimated time to complete this lab: 60 minutes

Module 2: Using Web Controls 31


Exercise 1
Adding Web Controls to a Page
In this exercise, you will add three different controls to the ASP.NET page
hotel_reservation.aspx: a button control, a label control, and a drop-down list
control.
To add a button
1. Open the file hotel_reservation.aspx in the folder
InetPub\wwwRoot\ASPNET.
2. Locate the following comment:
<! - - TO DO: add a r eser vat i on but t on - - >

3. Create a button Web control.
a. Set the ID, Text and Runat attributes.
b. Set the OnClick event to call the cmdSubmit_Click procedure.
Your code should look like the following:
<asp: but t on
i d="cmdOK"
Text ="Reser ve"
OnCl i ck="cmdSubmi t _Cl i ck"
r unat ="ser ver "
/ >


To add a label
1. Locate the following comment:
<! - - TO DO: add a conf i r mat i on l abel - - >

2. Create a label Web control.
Set the ID and Runat attributes.
Your code should look like the following:
<asp: Label
i d=" l bl Reser vat i onConf i r mat i on"
r unat ="ser ver "
/ >



32 Module 2: Using Web Controls


To add a drop down list
1. Locate the following comment:
<! - - TO DO: add a second Dr opDownLi st - - >

2. Create a second drop-down list control to contain the available room types.
a. Set the ID attribute to lstRoomType2.
b. Create two drop-down list items: NoSmoking and Smoking. Set the No
Smoking item to be the default selection.
Your code should look like the following:
<asp: Dr opDownLi st
i d="l st RoomType2"
r unat =" ser ver " >
<asp: Li st I t emsel ect ed=" t r ue" >No Smoki ng</ asp: Li st I t em>
<asp: Li st I t em>Smoki ng</ asp: Li st I t em>
</ asp: Dr opDownLi st >

3. Save your work.


Module 2: Using Web Controls 33


Exercise 2
Adding a Calendar Control to a Page
In this exercise, you will add a calendar control to the ASP.NET page
hotel_reservation.aspx.
To add a calendar control
1. In the file hotel_reservation.aspx, locate the following comment:
<! - - TO DO: add a cal endar cont r ol f or t he endi ng dat e - - >

2. Create a second calendar control, named calEndingDate, with the same
attributes as the calStartingDate calendar control.
Your code should look like the following:
<asp: Cal endar i d=" cal Endi ngDat e" r unat =" ser ver "
BackCol or =" #9FC89F" For eCol or =" #313179"
Bor der Wi dt h=" 3"
Bor der St yl e=" Sol i d" Bor der Col or =" #313179"
Cel l Spaci ng=" 2" Cel l Paddi ng=" 2"
ShowGr i dLi nes=" t r ue"
Ti t l eSt yl e- BackCol or =" whi t e"
Ti t l eSt yl e- For eCol or =" bl ack"
/ >


To validate start and end date selections
1. Locate the following comment:
' TO DO: val i dat e st ar t and end dat e sel ect i ons

2. Write an event procedure named cmdSubmit_Click for the Reserve button
that validates the selections in the two calendar controls.
a. If the end date is greater than the start date, display a confirmation
message in the lblReservationConfirmation label.
b. If the end date is less than the start date, display an error message in the
lblReservationConfirmation label.

You use the SelectedDate method to obtain the selected date of a
calendar control and you use the SelectedItem.Text method to obtain the
selected item of a drop-down list.


Note
34 Module 2: Using Web Controls


Your code should look like the following:
' Test i f t he dat e r ange i s val i d
I f cal Endi ngDat e. Sel ect edDat e <= _
cal St ar t i ngDat e. Sel ect edDat e Then
l bl Reser vat i onConf i r mat i on. Text = _
"The end dat e cannot be bef or e t he st ar t dat e. "
El se
l bl Reser vat i onConf i r mat i on. Text = _
" Congr at ul at i ons. Ther e i s an avai l abl e r oom" & _
"f or you. <br >" & _
"Roomt ype: " & _
l st RoomType1. Sel ect edI t em. Text & " , " & _
l st RoomType2. Sel ect edI t em. Text & " <br >" & _
" f r om: " & _
cal St ar t i ngDat e. Sel ect edDat e. ToShor t Dat eSt r i ng( ) & _
" t o " & _
cal Endi ngDat e. Sel ect edDat e. ToShor t Dat eSt r i ng( )
End I f


To save and test your work
1. Save your changes to the file hotel_reservation.aspx.
2. Using Internet Explorer, go to the hotel reservation page of the Conference
Web site by viewing http://localhost/ASPNET/hotel_reservation.aspx.
3. Select a room type, a start date and an end date, and then click Reserve.
You should see a confirmation message.
4. Select a start date that is later than the end date, and then click Reserve.
You should see the following message: The end date cannot be before the
start date.


Module 2: Using Web Controls 35


Exercise 3
Validating User Input
In this exercise, you will add four different input validation controls to the
ASP.NET page register.aspx: a RequiredValidator control, a RangeValidator
control, a RegularExpressionValidator control, and a CompareValidator
control.
To validate the Full Name text box
1. Open the file register.aspx in the folder InetPub\wwwRoot\ASPNET.
2. Locate the following comment:
<! - - TO DO: val i dat e t xt Ful l Name cont r ol - - >

3. Create a RequiredFieldValidator input validation control to validate the
txtFullName control.
a. Set the ID and Runat attributes.
b. Set the remaining attributes as shown in the following table.
Property Value

ErrorMessage Full Name is a required field.
InitialValue
Display Static

c. Set the default text of the control to *.
Your code should look like the following:
<asp: Requi r edFi el dVal i dat or
i d="val Ful l Name"
r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Ful l Name"
er r or Message=" Ful l Name i s a r equi r ed f i el d. "
i ni t i al Val ue=" "
di spl ay="st at i c">
*
</ asp: Requi r edFi el dVal i dat or >



36 Module 2: Using Web Controls


To validate the e-mail text box
1. Locate the following comment:
<! - - TO DO: val i dat e t xt Emai l cont r ol - - >

2. Create a RegularExpressionValidator input validation control to validate
the txtEmail control. Set the ID, ControlToValidate, Runat,
ErrorMessage, and Display attributes.
3. Set the validationExpression attribute of the RegularExpressionValidator
control to a regular expression for the syntax of an e-mail address.
Use the characters in the following table to create the regular expression.
Character Meaning

. Any character
+ One or more occurrences of the preceding expression
@ Character @
\. Character .

An e-mail address must meet the following requirements:
One or more characters representing the account name preceding the
at (@) separator between the account name and the domain name
address.
The at (@) separator.
One or more characters representing the domain name following the at
(@) separator.
One period following the conclusion of the domain name.
One or more characters following the period, representing the top-level
domain.
Your code should look like the following:
<asp: Regul ar Expr essi onVal i dat or
i d="val Emai l Expr "
r unat ="ser ver "
val i dat i onExpr essi on=" . +@. +\ . . +"
cont r ol ToVal i dat e=" t xt Emai l "
er r or Message=" E- mai l synt ax i s i ncor r ect . "
di spl ay="dynami c">
*
</ asp: Regul ar Expr essi onVal i dat or >



Module 2: Using Web Controls 37


To compare the values in the txtPassword and txtConfirmPassword
text boxes
1. Locate the following comment
<! - - TO DO: passwor d compar i son - - >

2. Create a CompareValidator input validation control to compare the
txtConfirmPassword control with the txtPassword control.
3. Set the ID, Runat, ControlToValidate, ControlToCompare,
ErrorMessage, and Display properties.
Your code should look like the following:
<asp: Compar eVal i dat or
i d=" val Compar ePasswor d"
r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Conf i r mPasswor d"
cont r ol ToCompar e=" t xt Passwor d"
er r or Message=" Passwor d f i el ds do not mat ch. "
Di spl ay="dynami c">
*
</ asp: Compar eVal i dat or >


To save and test your work
1. Save your changes to the file register.aspx.
2. Using Internet Explorer, go to the registration page of the Conference Web
site by viewing http://localhost/ASPNET/register.aspx.
3. Enter invalid information in the Name, E-mail, Password, and Confirm
Password text boxes, and then click Submit. The following table gives
examples of invalid information.
Field Value

Full Name
E-mail Email
Password abc
Confirm Password def

The page should display an asterisk next to each invalid field.
4. Enter valid information in the Name, E-mail, Password, and Confirm
Password text boxes, and then click Submit.


38 Module 2: Using Web Controls


Exercise 4
Summarizing Validation Errors
In this exercise, you will add a ValidationSummary control to the
register.aspx page. You will also programmatically test the validity of the
controls on the form in the OnClick event procedure of the Submit button.
To add a validation summary control
1. In the register.aspx file, locate the following comment:
<! - - TO DO: val i dat i on summar y - - >

2. Create a ValidationSummary control to summarize the validity of all
validation controls on the form.
Your code should look like the following:
<asp: val i dat i onsummar y
i d=" val Summar y"
r unat =" ser ver " / >


To save and test your work
1. Save your changes to the register.aspx file.
2. Open the page in Internet Explorer and enter invalid values in some of the
fields, and then click Submit.
You will see an error message for each incorrect field in a summarization at
the bottom of the page.

To display another page if all the fields are valid
1. In the cmdValidation_Click event procedure, go to the comment:
' TO DO: t est i f t he page i s val i d

2. Add code to test if the page is valid.
a. If the page is valid, redirect to the validOK.aspx page using the Redirect
method of the Response object.
b. If the page is invalid, do nothing.
Your code should look like the following:
I f Page. I sVal i d Then
Response. Redi r ect ( " val i dOK. aspx" )
End I f



Module 2: Using Web Controls 39


To save and test your work
1. Save your changes to the file register.aspx.
2. Open the page in Internet Explorer.
3. Enter invalid values in the fields, and then click Submit.
You should see error messages.
4. Enter valid values in the fields, and then click Submit.
You should receive the confirmation page.


40 Module 2: Using Web Controls


Review
n What Are Web Controls?
n Using Intrinsic Controls
n Using Input Validation Controls
n Selecting Controls for Applications

*****************************illegal for non-trainer use**************************** **
1. What is the prefix tag that you must use to create Web controls?


2. How do you create an event procedure for a button?


3. List the input validation controls included with ASP.NET.


4. What property of the input validation controls determines the error text
displayed to the user?



Module 2: Using Web Controls 41


5. What validation control would you use to validate a phone number?


6. Why would you use the ValidationSummary control?






THIS PAGE INTENTIONALLY LEFT BLANK









Contents
Overview 1
Overview of ADO.NET 2
Connecting to a Data Source 11
Accessing Data with DataSets 13
Using Stored Procedures 28
Lab 3: Using ADO.NET to Access Data 37
Accessing Data with DataReaders 46
Binding to XML Data 53
Review 59

Module 3: Using
Microsoft ADO.NET to
Access Data


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 3: Using Microsoft ADO.NET to Access Data 1


Overview
n Overview of ADO.NET
n Connecting to a Data Source
n Accessing Data with DataSets
n Using Stored Procedures
n Accessing Data with DataReaders
n Binding to XML Data

*****************************illegal for non-trainer use******************************
One of the reasons for the widespread use of Microsoft Active Server Pages
(ASP) is that it facilitates access to data stores. ASP.NET expands on this
capability with the introduction of ADO.NET, which offers a rich suite of data
handling and data binding functions for manipulating all types of data.
After completing this module, you will be able to:
n Describe the Microsoft ADO.NET object model.
n Connect to a data source by using ADO.NET.
n Retrieve data from a database by using DataReaders and DataSets.
n Display the data from a database on the client by using list-bound controls.
n Customize the look of Repeater controls with templates.
n Use stored procedures to return Recordsets.
n Read data from an Extensible Markup Language (XML) file into DataSets .

There were many changes between the Beta 1 and Beta 2 versions of
ASP.NET with respect to data binding. For a detailed list of changes, see
Appendix A, in Course 2063B, Introduction to Microsoft ASP.NET.

Note
2 Module 3: Using Microsoft ADO.NET to Access Data


u Overview of ADO.NET
n The ADO.NET Object Model
n Animation: Using ADO.NET to Access Data
n RecordSets vs. DataSets
n Using Namespaces

*****************************illegal for non -trainer use******************************
ADO.NET is not a revision of Microsoft ActiveX Data Objects (ADO), but a
new way to manipulate data that is based on disconnected data and XML.
Although ADO is an important data access tool within ASP, it does not provide
all of the necessary features for developing robust and scalable Web
applications. In spite of ADOs rich object model and relative ease of use, it is
connected by default, relies on an OLE DB provider to access data, and it is
entirely Component Object Model (COM)-based.
ADO.NET has been designed to work with disconnected datasets. Disconnected
datasets reduce network traffic.
ADO.NET uses XML as the universal transmission format. This guarantees
interoperability as long as the receiving component runs on a platform where an
XML parser is available. When the transmission occurs through XML, it is no
longer necessary that the receiver be a COM object. The receiving component
has no architectural restrictions whatsoever. Any software component can share
ADO.NET data, as long as it uses the same XML schema for the format of the
transmitted data.
In this section, you will learn about ADO.NET. You will learn about the new
and modified objects in ADO.NET. You will also learn about some of the new
namespaces that are included in ASP.NET.

Module 3: Using Microsoft ADO.NET to Access Data 3


The ADO.NET Object Model
DataAdapter
Connection
Database Database
Command
.ASPX Page
List-Bound
Control
List-Bound
Control
DataReader
Company:
Northwind Traders
Company:
Northwind Traders
.ASPX Page
DataView DataView
DataSet

*****************************illegal for non-trainer use******************************
ADO.NET evolved from the ADO data access model. By using ADO.NET, you
can develop applications that are robust and scalable, and that can use XML.
ADO.NET has some of the same objects as ADO (like the Connection and
Command objects), and introduces new objects, such as the Dataset,
DataReader, and DataAdapter.
Connection Objects
Connection objects are used to talk to databases. They have properties, such as
DataSource, UserID, and Password, which are needed to access a particular
DataSource. Commands travel over connections, and result sets are returned in
the form of streams that can be read by DataReaders or pushed into DataSet
objects.
There are two kinds of connection objects in ADO.NET: SqlConnection and
OleDbConnection.
Command Objects
Command objects contain the information that is submitted to a database. A
command can be a stored procedure call, an update statement, or a statement
that returns results. You can also use input and output parameters and return
values. In ADO.NET, you can use two kinds of command objects:
SqlCommand and OleDbCommand.

4 Module 3: Using Microsoft ADO.NET to Access Data


DataReader Objects
A DataReader is a read-only/forward-only view on the data. It provides a
simple and lightweight way of traversing through recordsets. For example, if
you wanted to simply show the results of a search list in a Web page, using a
DataReader is an ideal way to accomplish this.
A DataReader is returned after executing a command. It works similarly to a
recordset in ADO, allowing you to simply loop through the records.
ADO.NET includes two types of DataReader objects: the SqlDataReader for
Microsoft SQL Server

version 7.0 (or later) data, and the OleDbDataReader


for ADO data. The DataReader object is database-specific. The behavior for
the SqlDataReader may differ from the behavior for the OleDbDataReader
and additional DataReader objects that are introduced in the future.
You use the OleDbCommand and SqlCommand objects and the
ExecuteReader method to transfer data into a DataReader.
DataSet Objects
The DataSet is designed to handle the actual data from a data store. The
DataSet provides a rich object model to work with when passing data between
various components of an enterprise solution. The DataSet object is generic.
The behavior of a DataSet is completely consistent regardless of the underlying
database, SQL or OLE DB.
The DataSet object represents a cache of data, with database-like behavior. It
contains tables, columns, relationships, constraints, and data. Data coming from
a database, an XML file, code, or user input can be entered into DataSet
objects and converted into files, forms, or databases. As changes are made to
the DataSet, they are tracked in a way similar to the way changes are tracked in
a word processing document.
The DataSet object has a collection of DataTable objects. A DataTable
represents one table of in-memory data. It contains a collection of columns that
represents the table's schema. A DataTable also contains a collection of rows,
representing the data contained in the table.
You use the OleDbDataAdapter and SqlDataAdapter objects and the Fill
method to get data into a DataSet.
DataView Objects
A DataView provides a custom view of a data table. You can think of the
DataView as the equivalent of the ADO disconnected recordset, because it
contains a single view on top of the table data. You can use a DataViewto
specify criteria for filtering and sorting a DataSet.

A DataSet is not a recordset. A DataViewis more analogous to a
recordset.


Note
Module 3: Using Microsoft ADO.NET to Access Data 5


DataAdapter Object
While the DataSet object provides a tool for in-memory data storage, you need
another tool to create and initialize the various tables. This tool is the
DataAdapter object. It represents a centralized console that hides the details of
working with connections and commands. The DataAdapter object allows for
the retrieval and saving of data between a DataSet object and the source data
store. It is responsible for pulling out data from the physical store and pushing it
into data tables and relations. The DataAdapter object is also responsible for
transmitting any update, insertion, or deletion to the physical database. You can
use four command objects to make any updates: UpdateCommand,
InsertCommand, DeleteCommand, and SelectCommand.
The DataAdapter object exists in two forms: SqlDataAdapter objects and
OleDbDataAdapter objects. The data source is SQL Server for
SqlDataAdapter objects and any other OLE DB provider for
OleDbDataAdapter objects.

6 Module 3: Using Microsoft ADO.NET to Access Data


Animation: Using ADO.NET to Access Data

******************** *********illegal for non-trainer use******************************
In this animation, you will learn how to access data by using ADO.NET and
how you can display that data in an ASP.NET page. To view the animation,
open the file 2063B_03A001.swf from the folder Media.


Module 3: Using Microsoft ADO.NET to Access Data 7


Recordsets vs. DataSets
Transmit XML file COM marshalling Transmitting data
Disconnected Connected or
disconnected
Data connections
Navigate via
relationships
Move row-by-row Moving through data
Includes relationships Based on join Relationships
Multiple tables One table Number of tables
DataSet Recordset Feature

*****************************illegal for non-trainer use******************************
In ADO, the in-memory representation of database data is the recordset. In
ADO.NET, it is the DataSet. The DataSet contains a collection of tables and
knowledge of relationships between those tables. Each table contains a
collection of columns. These objects represent the schema of the DataSet. Each
table can then have multiple rows, representing the data held by the DataSet.
These rows track their original state along with their current state, so that the
DataSet tracks what kinds of changes have occurred. Additionally, the DataSet
provides persistence and de-persistence through XML.
There are important differences between recordsets and DataSets, which are
highlighted in the following table and detailed in the text that follows.
Feature Recordset DataSet

Number of tables One table Multiple tables
Relationships Based on join Includes relationships
Moving through data Move row-by-row Navigate via relationships
Data connections Connected or disconnected Disconnected
Transmitting data COM marshalling Transmit XML file

Number of Tables
An ADO recordset looks like a single table. If a recordset is to contain data
from multiple database tables, it must use a JOINquery, which assembles the
data from the various database tables into a single result table.
In contrast, an ADO.NET DataSet is a collection of one or more tables. The
tables within a data set are called data tables; specifically, they are DataTable
objects.

8 Module 3: Using Microsoft ADO.NET to Access Data


Relationships
Typically, a DataSet also contains relationships. A relationship within a
DataSet is analogous to a foreign-key relationship in a database. In ADO.NET,
a DataRelation represents the relationship.
Moving Through Data
In ADO.NET, the methods you use to read or modify data differ from the
programming methods you use in ADO in the following ways:
n In ADO, you scan sequentially through the rows of the recordset.
n In ADO.NET, you employ a navigation paradigm, moving from a row of
one data table to the corresponding row or rows of another data table by
following the relationship.

Data Connections
In ADO.NET, the DataSet provides disconnected access to database data. In
ADO, the recordset can provide disconnected access, but is typically used to
provide connected access.
Transmitting Data
To transmit an ADO disconnected recordset from one component to another,
you use COM marshalling. To transmit an ADO.NET data set, you simply
transmit an XML file.

Module 3: Using Microsoft ADO.NET to Access Data 9


Using Namespaces
n Use the Import Construct to Declare Namespaces
n Namespaces Used with ADO.NET Include:
l System.Data
l System.Data.OleDb
l System.Data.SqlClient
l System.Data.XML
l System.Data.SqlTypes
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

*****************************illegal for non-trainer use******************************
The Microsoft .NET Framework is an object-oriented system. When using
specific parts of the framework, you need to include references to the
appropriate namespace in your ASP.NET page.
When using ADO.NET from either Microsoft Visual Basic 7.0 or Microsoft
VisualC#

, you must reference the System.Data namespace, plus either the


System.Data.OleDb or System.Data.SqlClient namespace, depending on the
data source you choose to use. System.Data provides the code facilities, while
System.Data.OleDb and System.Data.SqlClient are the namespaces for the
two managed providers.
In the C# programming language, you use the keyword Using to import a
namespace. In Visual Basic, you declare namespaces at the top of an ASP.NET
page, using the Import construct.
<%@I mpor t Namespace=" Syst em. Dat a" %>
<%@I mpor t Namespace=" Syst em. Dat a. Sql Cl i ent " %>


10 Module 3: Using Microsoft ADO.NET to Access Data


The following table summarizes the list of available namespaces with
ADO.NET.
Namespace Contains

System.Data Base objects and types for ADO.NET
System.Data.OleDb Managed OLE DB data store objects
System.Data.SqlClient SQL Server specific implementations of ADO.NET
objects
System.Data.XML XML objects
System.Data.SqlTypes SQL data types


Module 3: Using Microsoft ADO.NET to Access Data 11


Connecting to a Data Source
n Using SqlConnection
n Using OleDbConnection
Dim strConn As String = _
"server=localhost; uid=sa;pwd=; database=northwind"
Dim conn As SqlConnection = New SqlConnection(strConn)
Dim strConn As String = _
"server=localhost; uid=sa;pwd=; database=northwind"
Dim conn As SqlConnection = New SqlConnection(strConn)
Dim strConn As String = "Provider= SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"InitialCatalog=northwind;"
Dim conn As OleDbConnection = _
New OleDbConnection(strConn)
Dim strConn As String = "Provider= SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"InitialCatalog=northwind;"
Dim conn As OleDbConnection = _
New OleDbConnection(strConn)

*****************************illegal for non-trainer use******************************
When you connect to a database through an ASP.NET page, there are two
routes that you can take: use OLE DB or use the native SQL provider. The
native SQL provider is faster, but you must be using Microsoft SQL Server as
your database. If you are using Microsoft Access, Microsoft Excel, a comma-
delimited file, or some other data source, you must use the OLE DB provider.
You can use the OLE DB provider with a Microsoft SQL Server database;
however, it is not as fast as using the native SQL provider.
The Connection object defines how to connect to a specific data store.
The .NET framework provides two Connection objects: SqlConnection and
OleDbConnection. The SqlConnection object defines how to connect to
SQL Server databases and the OleDbConnection object allows you to establish
a connection to a database through an OLE DB provider.
Using SqlConnection
The following code illustrates how to create and open a connection to a
Microsoft SQL Server database by using the SqlConnection object.
Di mst r Conn As St r i ng = _
" ser ver =l ocal host ; ui d=sa; pwd=; dat abase=nor t hwi nd"
Di mconn As Sql Connect i on = New Sql Connect i on( st rConn)


12 Module 3: Using Microsoft ADO.NET to Access Data


Using OleDbConnection
For the OLE DB Managed Provider, the connection string format is quite
similar to the connection string format used in OLE DB.
The following code illustrates how to create and open a connection to a
Microsoft SQL Server database by using OleDbConnection.
Di mst r Conn As St r i ng = "Pr ovi der =SQLOLEDB. 1; " & _
" Dat a Sour ce=l ocal host ; ui d=sa; pwd=; " & _
" I ni t i al Cat al og=nor t hwi nd; "
Di mconn As Ol eDbConnect i on = New Ol eDbConnect i on( st r Conn)

We will be using SqlConnection objects for the examples in this module.
Implementation is slightly different for using OleDbConnection objects. For
more information about using OleDbConnection objects, search for
OleDbConnection in the Microsoft .NET Framework SDK documentation.

Module 3: Using Microsoft ADO.NET to Access Data 13


u Accessing Data with DataSets
n Using DataSets to Read Data
n Storing Multiple Tables in a DataSet
n Using DataViews
n Displaying Data in the DataGrid Control
n Demonstration: Displaying Data in a DataGrid
n Using Templates
n Using the Repeater Control
n Demonstration: Displaying Data in a Repeater Control

*****************************illegal for non-trainer use******************************
ADO.NET provides two ways to access data, DataSets and DataReaders.
In this section, you will learn how to access data by using DataSets. You will
also learn about DataViews and displaying data in list-bound controls. At the
end of the section, you will learn how to customize a list-bound control by
using templates.

14 Module 3: Using Microsoft ADO.NET to Access Data


Using DataSets to Read Data
Dim cmdAuthors As SqlDataAdapter
cmdAuthors = New SqlDataAdapter _
("select * from Authors", conn)
Dim cmdAuthors As SqlDataAdapter
cmdAuthors = New SqlDataAdapter _
("select * from Authors", conn)
n Create the Database Connection
n Store the Query in a SqlDataAdapter
n Create and Populate the DataSet with DataTables
Dim ds As DataSet
ds = New DataSet()
cmdAuthors.Fill(ds, "Authors")
Dim ds As DataSet
ds = New DataSet()
cmdAuthors.Fill(ds, "Authors")

*****************************illegal for non-trainer use******************************
After you establish a connection to a database, you can access its data.
ADO.NET provides multiple ways to access data.
Using DataSets
The DataSet object is the centerpiece of ADO.NET. It represents a complete
set of data, including multiple, related tables, and constraints.
Although a DataSet stores data, you need DataAdapter objects to create and
initialize the various tables. You also need the Fill method to populate a
DataSet with the results from a query.
The Fill method takes two parameters: a DataSet instance and a string. The
DataSet instance represents the DataSet to be filled, and the string identifies
the DataTable that will be created inside the DataSet. A DataSet can contain
many DataTables. You use the string supplied to the Fill method to reference
the DataTable after it is created.

Module 3: Using Microsoft ADO.NET to Access Data 15


The following code example illustrates how to create a SqlDataAdapter object
that contains the query statement. The Fill method then populates the DataSet
with the results from the query.
' Cr eat e a connect i on
Di mconn As Sql Connect i on = New Sql Connect i on _
( " ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs" )
' Cr eat e t he Dat aAdapt er
Di mcmdAut hor s As Sql Dat aAdapt er = New Sql Dat aAdapt er _
( " sel ect * f r omAut hor s" , conn)
' Cr eat e and popul at e t he Dat aSet
Di mds As Dat aSet
ds= New Dat aSet ( )
cmdAut hor s. Fi l l ( ds, " Aut hor s" )


16 Module 3: Using Microsoft ADO.NET to Access Data


Storing Multiple Tables in a DataSet
n Add the First Table
n Add the Subsequent Table(s)
command = New SqlDataAdapter _
("select * from Authors", conn)
command.Fill(ds, "Authors")
command = New SqlDataAdapter _
("select * from Authors", conn)
command.Fill(ds, "Authors")
command.SelectCommand = New SQLCommand _
("select * from Titles", conn)
command.Fill(ds, "Titles")
command.SelectCommand = New SQLCommand _
("select * from Titles", conn)
command.Fill(ds, "Titles")
Authors
Books
DataSet
Data Tables

*****************************illegal for non-trainer use******************************
A DataSet can contain multiple tables. You can retrieve multiple tables from a
database and store them in a DataSet.

You can store tables from different databases in the same DataSet.

To retrieve and store multiple tables in a DataSet
1. Create and populate the first DataSet.
ds = New Dat aSet ( )
SQL = "Sel ect * f r omAut hor s"
command = New Sql Dat aAdapt er ( SQL, conn)
command. Fi l l ( ds, " Aut hor s" )

2. Reset the SelectCommand, InsertCommand, or DeleteCommand
property of the DataAdapter object to a new Command object with a new
SQL statement.
command. Sel ect Command = New Sql Command _
( " sel ect * f r omTi t l es ", conn)

3. Call Fill again.
command. Fi l l ( ds, " Ti t l es" )



Note
Module 3: Using Microsoft ADO.NET to Access Data 17


The following code shows how you can add two tables from two different
queries, one for authors and the other for titles, to the same DataSet.
Di mst r Conn As St r i ng
Di mconn As Sql Connect i on
Di mSQL As St r i ng
Di mcommand As Sql Dat aAdapt er
Di mds As Dat aSet

' cr eat e connect i on t o dat abase
st r Conn = " ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs"
conn = New Sql Connect i on( st r Conn)

' f i l l Dat aSet wi t h f i r st set of dat a
SQL = " Sel ect * f r omAut hor s"
command = New Sql Dat aAdapt er ( SQL, conn)
ds = New Dat aSet ( )
command. Fi l l ( ds, " Aut hor s" )

' f i l l Dat aSet wi t h second set of dat a
SQL = "sel ect * f r omTi t l es "
command. Sel ect Command = New Sql Command( SQL, conn)
command. Fi l l ( ds, " Ti t l es")


18 Module 3: Using Microsoft ADO.NET to Access Data


Using DataViews
n DataViews Can be Customized to Present a Subset of
Data from a DataTable
n The DefaultView Property Returns the Default DataView
for the Table
n Setting Up a Different View of a DataSet
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"
Dim dv as DataView
dv = ds.Tables("Authors").DefaultView
Dim dv as DataView
dv = ds.Tables("Authors").DefaultView

*****************************illegal for non-trainer use******************************
To display the data held in a DataSet, you need to use a DataView.
DataViews can be customized to present a subset of data from the DataTable.
This capability allows you to have two controls bound to the same DataTable,
but showing different versions of the data. For example, one control may be
bound to a DataViewthat shows all the rows in the table, and a second may be
configured to display only the rows that have been deleted from the DataTable.
Each DataTable in a DataSet has a DefaultViewproperty, which returns the
default view for the table. You can access the default DataView on a DataSet
as follows:
Di mdv As Dat aVi ew
dv = ds. Tabl es( " Aut hor s" ) . Def aul t Vi ew

The DataSet object contains a Tables collection. You reference the
DataTable you are interested in by name.

You can also create a view of a subset of the data in a DataTable. For example,
you can set the RowFilter property on a DataView to retrieve only authors
from California.
Di mdv as Dat aVi ew
dv = New Dat aVi ew ( ds. Tabl es( " Aut hor s" ) )
dv. RowFi l t er = " st at e = ' CA' "

For more information on the properties of the DataView object, see the
Microsoft .NET Framework SDK documentation.

Note
Module 3: Using Microsoft ADO.NET to Access Data 19


Displaying Data in the DataGrid Control
n Create the Control
n Bind to a DataSet
dgAuthors.DataSource=ds
dgAuthors.DataMember="Authors"
dgAuthors.DataBind()
dgAuthors.DataSource=ds
dgAuthors.DataMember="Authors"
dgAuthors.DataBind()
<asp:DataGrid id="dgAuthors" runat="server" />
<asp:DataGrid id="dgAuthors" runat="server" />

*****************************illegal for non-trainer use******************************
Displaying data from a data source is extremely simple and flexible in
ASP.NET. ASP.NET includes a set of controls that perform the function of
displaying data. The developers only need to bind these controls to a data
source.
To display data on the client, you can use any list-bound control, such as
DataGrid, DataList, or DataRepeater.
Using the DataGrid Control
The DataGrid control is designed to produce Hypertext Markup Language
(HTML) output that resembles a spreadsheet.
<asp: Dat aGr i d i d=" dgAut hor s" r unat =" ser ver " / >

To bind a DataSet to a DataGrid control, you first need to set the DataSource
property of the DataGrid to a DataSet, DataTable, or DataVieweither the
DefaultView property of a DataSet or a custom DataView objectand then
call the DataBind method.
If you set the DataSource property of the DataGrid directly to a DataSet, the
DataTable with index 0 is used by default. To specify a different DataTable,
set the DataMember property of the DataGrid to the name of the DataTable.
Example Binding to a DataSet
dgAut hor s. Dat aSour ce = ds
dgAut hor s. Dat aMember = " Aut hor s"
dgAut hor s. Dat aBi nd( )


20 Module 3: Using Microsoft ADO.NET to Access Data


Alternatively, you can use the Tables collection of the DataSet to assign the
DataTable directly to the DataSource of the DataGrid, as in the following
example:
dgAut hor s. Dat aSour ce = ds. Tabl es( " Aut hor s" )
dgAut hor s. Dat aBi nd( )

If you want to display a different view of data in the DataGrid control, create a
new DataViewobject from the DataSet and bind that to the control. For
example, the following code will display only those authors living in California.
Example Using a Custom View
Di mdv as Dat aVi ew
dv = New Dat aVi ew ( ds. Tabl es( " Aut hor s" ) )
dv. RowFi l t er = " st at e = ' CA' "
dgAut hor s. Dat aSour ce = dv
dgAut hor s. Dat aBi nd( )

The following illustration shows the default format of the DataGrid control
displaying data for authors living in California.


Module 3: Using Microsoft ADO.NET to Access Data 21


Demonstration: Displaying Data in a DataGrid

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to read data from a database into a
DataSet and then display it in a DataGrid control.
To run the demonstration
1. Edit the file <install folder>\DemoCode\ Mod03\grid.aspx.
a. There are two DataGrid controls. The first of these sets the formatting
attributes to make the DataGrid control more aesthetically pleasing to
the viewer.
Select one of the DataGrid controls and view the Properties window in
Microsoft Visual Studio .NET to learn about the properties of the
DataGrid control. Look specifically at the Style properties.
b. The Page_Load event procedure makes a connection to the database and
creates a DataSet.
c. The first DataGrid is bound to the DefaultViewof the DataSet.
d. The second DataGrid is bound to a new DataView that is a filtered
version of the data.
2. View the page in Microsoft Internet Explorer.


22 Module 3: Using Microsoft ADO.NET to Access Data


Using Templates
FooterTemplate
FooterTemplate
HeaderTemplate
HeaderTemplate
SeparatorTemplate SeparatorTemplate
AlternatingItem
Template
AlternatingItem
Template
ItemTemplate
ItemTemplate

*****************************illegal for non-trainer use******************************
Most ASP.NET controls have a standard appearance, but the user may require
something different. ASP.NET allows users to customize the appearance of
some controls by using templates. When a control supports a template, you add
the ASP.NET template elements. Then, within the template, you insert the
elements and controls that you want to be displayed.
List-bound controls support five types of templates. The Repeater and
DataList controls can use these templates directly. The DataGrid control can
use these templates only if they are bound to a column.
Template Use

HeaderTemplate Elements to render once before any data-bound rows have
been rendered. A typical use is to begin a container
element, such as a table.
ItemTemplate Elements that are rendered once for each row in the data
source. To display data in the ItemTemplate, declare one
or more Web controls and set their data-binding
expressions to evaluate to a field in the Repeater control's
(that is, in the container control's) DataSource:
<asp: Label r unat =" ser ver "
Text =" <%#Cont ai ner . Dat aI t em. Lst Name %>"
/ >

AlternatingItemTemplate Elements that are rendered for every other row in the
Repeater control.
SeparatorTemplate Elements to render between each row, typically line breaks
(<BR> tags), lines (<HR> tags), and so on.
FooterTemplate Elements to render once when all data-bound rows have
been rendered. A typical use is to close an element opened
in the HeaderTemplate item (with a tag such as
</TABLE>).


Module 3: Using Microsoft ADO.NET to Access Data 23


For more information about using templates with the DataGrid control, refer to
the DataGrid Web Control topic in the Microsoft .NET Framework SDK
documentation.

24 Module 3: Using Microsoft ADO.NET to Access Data


Using the Repeater Control
n Create the Control and Bind to a DataView
n Display Data in TemplatedElements
<asp:Repeater id="repList" runat="server">
<ItemTemplate>
<%# Container.DataItem("au_lname") %>
</ItemTemplate>
</asp:Repeater>
<asp:Repeater id="repList" runat="server">
<ItemTemplate>
<%# Container.DataItem("au_lname") %>
</ItemTemplate>
</asp:Repeater>

*****************************illegal for non-trainer use******************************
DataList and Repeater controls give a developer greater flexibility over the
rendering of list-like data. You might call these controls appearance-less,
because they have no standard appearance; that is, they have no default layout
or styles. The way data is displayed is completely determined by the HTML in
the control's templates, which describe how to present data items.
An advantage of the DataList control is that it allows you to display items in
multiple columns. As a result, elements can flow horizontally or vertically. For
more information about using templates with the DataList control, refer to the
DataList Web Control topic in the Microsoft .NET Framework SDK
documentation.
To use the DataList or Repeater controls, you first bind the controls to a
DataTable in a DataSet as shown in the following example code:
r epl i st . Dat aSour ce= ds
Repl i st . Dat aMember = " Aut hor s"
r epl i st . Dat aBi nd( )

Next, you bind data held in the Repeater control to templates that describe how
to display the data. For example, to display a list of authors last names, use the
following binding syntax in an ItemTemplate template:
<asp: Repeat er i d="r epLi st " r unat ="ser ver ">
<I t emTempl at e>
<%# Cont ai ner . Dat aI t em( " au_l name" ) %><BR>
</ I t emTempl at e>
</ asp: Repeat er >


Module 3: Using Microsoft ADO.NET to Access Data 25


The <% %> is the syntax for inline server-side code, the # is the binding
expression, the Container object refers to the current record of the Repeater
control, and the DataItem method refers to a field in the record. You are
binding to a field in the current record.
Example of a Repeater Control
The following sample code creates a very simple table to display information
about the set of authors retrieved from the database.
<asp: Repeat er i d="r epLi st " r unat ="ser ver ">
<Header Templ at e>
<t abl e>
<t r >
<t d>Last name</ t d>
<t d>Fi r st name</ t d>
<t d>St at e</ t d>
</ t r >
</ Header Templ at e>

<I t emTempl at e>
<t r >
<t d><%# Cont ai ner . Dat aI t em( " au_l name" ) %></ t d>
<t d><%# Cont ai ner . Dat aI t em( " au_f name" ) %></ t d>
<t d><%# Cont ai ner . Dat aI t em( " st at e" ) %></ t d>
</ t r >
</ I t emTempl at e>

<Foot er Templ at e>
</ t abl e>
</ Foot er Templ at e>
</ asp: Repeat er >

The following illustration shows the table created by the above sample code:


26 Module 3: Using Microsoft ADO.NET to Access Data


Using the AlternatingItemTemplate with the Repeater
Control
As mentioned previously, DataList and Repeater controls can use the
templates directly. The following is an example of using the
AlternatingItemTemplate with the Repeater control. The use of
AlternatingItemTemplate highlights every alternate line.
<Al t er nat i ngI t emTempl at e>
<t r >
<t d st yl e="backgr ound- col or : gr een" >
<%# Cont ai ner . Dat aI t em( " au_l name" ) %></ t d>
<t d st yl e="backgr ound- col or : gr een" >
<%# Cont ai ner . Dat aI t em( " au_f name" ) %></ t d>
<t d st yl e="backgr ound- col or : gr een" >
<%# Cont ai ner . Dat aI t em( "st at e") %></ t d>
</ t r >
</ Al t er nat i ngI t emTempl at e>

The following illustration shows the table with the AlternatingItemTemplate :


Module 3: Using Microsoft ADO.NET to Access Data 27


Demonstration: Displaying Data in a Repeater Control

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to display data in a Repeater control.
To run the demonstration
1. Edit the file <install folder>\DemoCode\ Mod03\repeater.aspx.
a. The Page_Load event procedure makes a connection to the database,
creates a DataSet, and binds it to the two Repeater controls.
b. The first Repeatercontrol, repList, simply outputs the data from the
DataSet in a list.
c. The second Repeater control, repTable, uses HeaderTemplate,
ItemTemplate, AlternatingItemTemplate, and FooterTemplate
templates to display data in a table.
2. View the page in Microsoft Internet Explorer.


28 Module 3: Using Microsoft ADO.NET to Access Data


u Using Stored Procedures
n Calling Stored Procedures
n Passing Parameters
n Calling Action Stored Procedures
n Demonstration: Calling Stored Procedures

*****************************illegal for non-trainer use******************************
In the past, data processing has been primarily connection-based. Now, in an
effort to make multi-tiered applications more efficient, data processing is
turning to a message-based approach that revolves around chunks of
information. In ADO.NET, this is accomplished by the DataAdapter object,
which provides a bridge to retrieve and save data between a DataSet object and
its source data store. The DataAdapter object accomplishes this by invoking
the appropriate SQL commands against the data store.
Both the SqlDataAdapter and the OleDbDataAdapter classes feature four
command objects, InsertCommand, UpdateCommand, DeleteCommand,
and SelectCommand. These objects provide the create, update, delete, and
read functions for a specific DataTable in the DataSet.
These command objects are used when you want to perform a number of
updates at the same time. Instead of having one stored procedure to do it all,
you can put SQL Statements in each object and call the Update method.
For more information about these command objects, see the .NET Framework
SDK documentation.
However, the easier and more commonly used method of updating data in a
database is to use stored procedures. You can use stored procedures to read and
modify data from a database. You can call stored procedures both from
DataAdapter and Command objects.

Module 3: Using Microsoft ADO.NET to Access Data 29


Calling Stored Procedures
n Stored Procedures Provide Security for Database
n Set Up the DataAdapter
n Run the Stored Procedure and Store Returned Records
Dim cmd as SqlDataAdapter
cmd = New SqlDataAdapter()
cmd.SelectCommand = New SqlCommand()
With cmd.SelectCommand
.Connection = conn
.CommandText = "ProductCategoryList"
.CommandType = CommandType.StoredProcedure
End With
Dim cmd as SqlDataAdapter
cmd = New SqlDataAdapter()
cmd.SelectCommand = New SqlCommand()
With cmd.SelectCommand
.Connection = conn
.CommandText = "ProductCategoryList"
.CommandType = CommandType.StoredProcedure
End With
cmd.Fill (ds, "Categories")
cmd.Fill (ds, "Categories")

*****************************illegal for non-trainer use******************************
A stored procedure is a sequence of Transact-SQL (T-SQL) statements stored
on the database server. Stored procedures provide a level of security to a
database. The database designer can create stored procedures to retrieve and
modify data, and not allow developers access to the actual tables of the database.
In this way, the database designer can then change the structure of the database
without breaking applications that use it.
Stored procedures are able to return a set of records. This will not always be the
case. Stored procedures can encapsulate repetitive tasks and execute them
efficiently. When you call a stored procedure that returns a set of records, use a
DataAdapter and the Fill method. When you call a stored procedure that
performs some function on the database but does not return a set of records, use
a Command object and the ExecuteNonQuery method.
Calling a Select Stored Procedure
Using stored procedures in ADO.NET is similar to ADO. You create a
command object and point it to the database connection. Next, you set the
CommandText property to the name of the stored procedure and the
CommandType property to CommandType.StoredProcedure.
The following is the ProductCategoryList stored procedure. It returns a list of
Categories.
Pr ocedur e Pr oduct Cat egor yLi st
As
SELECT Cat egor yI D, Cat egor yName
FROM Cat egor i es


30 Module 3: Using Microsoft ADO.NET to Access Data


The following example code uses a Connection object and a DataAdapter
object to call the ProductCategoryList stored procedure:
Di mcmd as Sql Dat aAdapt er
cmd = New Sql Dat aAdapt er ( )
cmd. Sel ect Command = New Sql Command( )
Wi t h cmd. Sel ect Command
. Connect i on = conn
. CommandText = " Pr oduct Cat egor yLi st "
. CommandType = CommandType. St or edPr ocedur e
End Wi t h

You can directly set the connection and command text when creating the
SqlDataAdapter object:
cmd = New Sql Dat aAdapt er ( "Pr oduct Cat egor yLi st ", conn)

You then simply need to set the CommandType property before you call the
Fill method.

To execute the stored procedure, call the Fill method of the SqlDataAdapter
object. This fills a DataTable object with the returned records of the stored
procedure.
cmd. Fi l l ( ds, "Cat egor i es")

After you have filled a DataTable with the results of a Select stored procedure,
you can bind it to a list-bound control to display the data.

Note
Module 3: Using Microsoft ADO.NET to Access Data 31


Passing Parameters
n Create Parameter, Set Direction and Value, Add to the
Parameters Collection
n Run Stored Procedure
workParam = New SqlParameter("@CategoryID", _
SQLDbType.Int)
workParam.Direction = ParameterDirection.Input
workParam.Value = CInt(txtCatID.Text)
cmd.SelectCommand.Parameters.Add(workParam)
workParam = New SqlParameter("@CategoryID", _
SQLDbType.Int)
workParam.Direction = ParameterDirection.Input
workParam.Value = CInt(txtCatID.Text)
cmd.SelectCommand.Parameters.Add(workParam)
ds = new DataSet()
cmd.Fill(ds, "Products")
ds = new DataSet()
cmd.Fill(ds, "Products")

*****************************illegal for non-trainer use******************************
When using Microsoft SQL Server, or other procedure-based databases,
parameters can be used to pass and retrieve information from the database.
Using parameters in ADO.NET works just as it does in ADO. You can pass the
string in the command or use the parameters collection.
When using parameters, the names of the parameters added to the parameters
collection of the command must match the names of the parameter markers in
the stored procedure.
Parameters
Your application can pass specific data to a stored procedure by using
parameters. The following table describes the types of parameters available to
you.
Direction Use

Input Used by your application to send specific data values to a stored
procedure.
Output Used by a stored procedure to send specific values back to the calling
application.
InputOutput Used by a stored procedure to both retrieve information sent by your
application and to send specific values back to the application.
ReturnValue Used by a stored procedure to send a return value back to the calling
application.


32 Module 3: Using Microsoft ADO.NET to Access Data


Creating a Parameter
To create a parameter for the SqlDataAdapter object, create a new
SqlParameter object with the name and data type of the parameter. Next, set
the Direction property of the new parameter to indicate how the parameter is
used by the stored procedure. If the stored procedure returns a return value,
create a parameter named returnValue. If the parameter is an input parameter,
set the Value property to specify the data that should be sent to the server.
For example, the ProductsByCategory stored procedure takes one input
parameter:
Pr ocedur e Pr oduct sByCat egor y (
@Cat egor yI D i nt )
As
SELECT Pr oduct I D, Model Name, Uni t Cost , Pr oduct I mage,
Chai r man
FROM Pr oduct s
WHERE Cat egor yI D=@Cat egor yI D

To call the ProductsByCategory stored procedure, create an input parameter
named @CategoryID and set its value to the value of a text box.
Di mcmd as Sql Dat aAdapt er
cmd = New Sql Dat aAdapt er ( )
cmd. Sel ect Command = New Sql Command( )
Wi t h cmd. Sel ect Command
. Connect i on = conn
. CommandText = " Pr oduct Cat egor yLi st "
. CommandType = CommandType. St or edPr ocedur e
End Wi t h
Di mwor kPar amas Sql Par amet er
wor kPar am= New Sql Par amet er ( " @Cat egor yI D" , Sql DbType. I nt )
wor kPar am. Di r ect i on = Par amet er Di rect i on. I nput
wor kPar am. Val ue = CI nt ( t xt Cat I D. Text )

After you have created the parameter, use the Add method of the Parameters
collection of the SelectCommand object. The Add method takes a
SqlParameter as an argument. If a stored procedure has more than one
parameter, it does not matter what order you add them in because you create
them by name.
cmd. Sel ect Command. Par amet er s. Add( wor kPar am)

Use the Fill method to run the stored procedure and retrieve the records.
ds = new Dat aSet ( )
cmd. Fi l l ( ds, " Pr oduct s" )


Module 3: Using Microsoft ADO.NET to Access Data 33


Calling Action Stored Procedures
n Use SQLCommand Object
n Call the ExecuteNonQuery Method
n Retrieve Output Parameters
curSales = myCmd.Parameters("@ItemCount").Value
curSales = myCmd.Parameters("@ItemCount").Value
conn.Open()
myCmd.ExecuteNonQuery()
conn.Close()
conn.Open()
myCmd.ExecuteNonQuery()
conn.Close()
Dim myCmd As SqlCommand = New SqlCommand _
("OrdersCount", conn)
Dim myCmd As SqlCommand = New SqlCommand _
("OrdersCount", conn)

*****************************illegal for non-trainer use******************************
When calling an update, insert, or delete stored procedure, you use the
SqlCommand directly and call the ExecuteNonQuery method to run it.
The OrdersCount stored procedure takes a customers ID and returns the
number of outstanding orders that customer has:
Pr ocedur e Or der sCount (
@Cust omer I D i nt ,
@I t emCount i nt OUTPUT )
As
SELECT @I t emCount =COUNT( Or der I D)
FROM Or der s
WHERE Cust omer I D=@Cust omer I D

Because this stored procedure does not return a set of records, you do not need
to use a DataAdapter object. Instead, you can use a Command object directly,
and call the ExecuteNonQuery method to run the stored procedure.

34 Module 3: Using Microsoft ADO.NET to Access Data


To call this stored procedure, create an input parameter named @CustomerID,
an output parameter named @ItemCount, add them to the Parameters
collection of a Command object, and then call ExecuteNonQuery to run the
stored procedure:
Di mmyCmd As Sql Command = New Sql Command( " Or der sCount " , conn)
myCmd. CommandType = CommandType. St or edPr ocedur e

' add an i nput par amet er
wor kPar am= New Sql Par amet er ( " @Cust omer I D" , Sql DbType. I nt )
wor kPar am. Di r ect i on = Par amet er Di r ect i on. I nput
wor kPar am. Val ue = CI nt ( t xt Cust I D. Text )
myCmd. Par amet er s. Add ( wor kPar am)

' add an out put par amet er
wor kPar am= New Sql Par amet er ( " @I t emCount " , Sql DbType. I nt )
wor kPar am. Di r ect i on = Par amet er Di r ect i on. Out put
myCmd. Par amet er s. Add ( wor kPar am)

' execut e t he st or ed pr ocedur e
conn. Open( )
myCmd. Execut eNonQuer y( )
conn. Cl ose( )

Retrieving an Output Parameter
If you need to retrieve a value from a stored procedure that returns a value or
sets an output parameter, use the Parameters collection to find the value of the
output parameter. You can reference the value of the output parameter by name
or index. The following example code retrieves the value of the @ItemCount
output parameter by name:
cur Sal es = myCmd. Par amet er s( " @I t emCount " ) . Val ue


Module 3: Using Microsoft ADO.NET to Access Data 35


Demonstration: Calling Stored Procedures

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to call stored procedures from DataSets,
both with and without parameters.
To run the demonstration
1. Edit the file <install folder>/DemoCode/2063/mod03/storedprocedure.aspx
There are three sub-procedures called from the Page_Load event procedure
that call stored procedures in different ways.
a. The displayCategories procedure calls a stored procedure that has no
parameters.
b. The displayProducts procedure calls a stored procedure that has one
input parameter.
c. The displayOrderCount procedure calls a stored procedure that has
input and output parameters.
2. View the page in Internet Explorer.
The first DataGrid is filled from the displayCategories procedure.
3. Enter a category number in the text box and click Get Products.
The second DataGrid is filled from the displayProducts procedure.
4. Enter a customer number in the textbox (such as 31 or 33) and click Get
Order Count.
The <span> element is filled from the displayOrderCount procedure.

36 Module 3: Using Microsoft ADO.NET to Access Data


5. View the source code of the page.
The Hidden field in the form contains the DataSet.
6. In Visual Studio .NET, you can view the objects in the Conf SQL Server
database.
a. Open the Server Explorer window.
b. Expand Servers , then <Computer Name>, then SQL Servers , then
<Computer Name>, then Conf.
You can view the tables and other objects in the SQL Server database.


Module 3: Using Microsoft ADO.NET to Access Data 37


Lab 3: Using ADO.NET to Access Data

*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Connect to a database.
n Create and fill a DataSet with data from a database.
n Display data using the Repeater control.

Prerequisite
Before working on this lab, you must know how to use Web controls in an
ASP.NET page.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab03\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab03\Solution.
Scenario
There are five tracks in the ASP.NET conference. To view these tracks, a user
goes to the ProductsList.aspx page. In Exercise 1, you will connect to the
database, create a DataSet , fill it, and display it in a Repeater control. In
Exercise 2, you will display the alternating line differently. In Exercise 3
(optional), you will use a DataList control to display a menu of items available
in the ASP.NET conference.
Estimated time to complete this lab: 60 minutes

38 Module 3: Using Microsoft ADO.NET to Access Data


Exercise 1
Accessing a SQL Database by Using ADO.NET
In this exercise, you connect to the Conf SQL Server database and call a stored
procedure. You then display the data in a Repeater control.
To connect to the database
1. Open the file ProductsList.aspx in the folder InetPub\wwwRoot\ASPNET.
2. Locate the comment:
' TO DO: r ead dat a f r omdat abase

3. Create a new connection to the Conf database.
a. Declare a string variable named strConn.
b. Set the variable to:
"server=localhost;uid=sa;pwd=1Aspnet;database=Conf"
c. Declare a SqlConnection variable named conn.
d. Create a new SqlConnection object from the strConn variable and save
it in the conn variable.
Your code should look like the following:
Di mst r Conn As St r i ng
Di mconn As Sql Connect i on

st r Conn = _
" ser ver =l ocal host ; ui d=sa; pwd=1Aspnet ; dat abase=Conf "
conn = New Sql Connect i on( st r Conn)



Module 3: Using Microsoft ADO.NET to Access Data 39


To call the ProductsByCategory stored procedure
1. Create a new SqlDataAdapter variable to call the ProductsByCategory
stored procedure.
Your code should look like the following:
Di mcmdPr oduct s As Sql Dat aAdapt er
cmdPr oduct s = _
New Sql Dat aAdapt er ( " Pr oduct sByCat egor y", conn)
cmdPr oduct s. Sel ect Command. CommandType = _
CommandType. St or edPr ocedur e

2. Create an input parameter for the stored procedure with the following
properties.
Property Value

Name @CategoryID
Type SqlDbType.Int
Value categoryID

3. Add the parameter to the Parameters collection of the SQLDataAdapter
variable.
Your code should look like the following:
Di mpar amCat egor yI D As Sql Par amet er
par amCat egor yI D = _
new Sql Par amet er ( " @Cat egor yI D" , Sql DbType. I nt , 4)
par amCat egor yI D. Val ue = cat egor yI D
cmdPr oduct s. Sel ect Command. Par amet er s. Add( par amCat egor yI D)


To create and fill the DataSet
1. Create a new DataSet object.
2. Fill the DataSet by calling the Fill method of the SqlDataAdapter variable.
Save the data in a table named Products.
Your code should look like the following:
Di mdsPr oduct s As New Dat aSet
cmdPr oduct s. Fi l l ( dsPr oduct s, " Pr oduct s" )


To display the data in a Repeater control
At the end of the Page_Load event procedure, display the default view of
the Products table in the DataSet by binding it to the repList Repeater
control.
Your code should look like the following:
r epLi st . Dat aSour ce = _
dsPr oduct s. Tabl es( "Pr oduct s ") . Def aul t Vi ew
r epLi st . Dat aBi nd( )



40 Module 3: Using Microsoft ADO.NET to Access Data


To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer , view the ProductsList.aspx page by viewing
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15

The ProductsList.aspx page can display any of the categories of
information in the Conf database. CategoryID 15 will display the conference
tracks.

You should see the tracks of the conference, as shown in the following
illustration.

3. Change the CategoryID to 14 and reload the page.
You should see the Pre-Conference Tutorials of the conference, as shown in
the following illustration.



Note
Module 3: Using Microsoft ADO.NET to Access Data 41


Exercise 2
Displaying Data Using ASP.NET Controls
In this exercise, you will modify the look of the data displayed in the Repeater
control on the ProductsList.aspx page by adding an AlternatingItemTemplate.
To add an AlternatingItemTemplate
1. Open the file ProductsList.aspx in the folder InetPub\wwwRoot\ASPNET.
2. Copy the HTML tags for the ItemTemplate template, from
<ItemTemplate> to </ItemTemplate>.
3. Paste the copied tags following the ItemTemplate template.
4. Change the start and end tags of the new template to
AlternatingItemTemplate, as shown in the following sample code.
<Al t er nat i ngI t emTempl at e>
</ Al t er nat i ngI t emTempl at e>


42 Module 3: Using Microsoft ADO.NET to Access Data


5. Set the background color of the alternating rows to BackgroundColor6,
BackgroundColor5, BackgroundColor6, BackgroundColor5.
These styles are defined in the conference.css style sheet.
To change the appearance of the columns, set the class attribute of the <td>
tags to the name of the style as follows:
<t d cl ass=" Backgr oundCol or 6" >

The AlternatingItemTemplate template should look like the following:
<Al t er nat i ngI t emTempl at e>
<t r >
<t d cl ass=" Backgr oundCol or 6" >
<%# Cont ai ner . Dat aI t em( " Chai r man" ) %>
</ t d>

<t d cl ass=" Backgr oundCol or 5" >
<a hr ef =' Pr oduct Det ai l s. aspx?pr oduct I D=
<%# Cont ai ner . Dat aI t em( " Pr oduct I D" ) %>' >
<%# Cont ai ner . Dat aI t em( " Model Name" ) %><br >
</ a>
</ t d>

<t d cl ass=" Backgr oundCol or 6" >
<b>Pr i ce: </ b>
<%# Syst em. St r i ng. For mat ( " {0: c}" , _
Cont ai ner . Dat aI t em( " Uni t Cost " ) ) %>
<br >
</ t d>

<t d cl ass=" Backgr oundCol or 5" >
<a hr ef =' AddToCar t . aspx?pr oduct I D=
<%# Cont ai ner . Dat aI t em( " Pr oduct I D" ) %>' >
<b>Add To Car t </ b>
</ a>
</ t d>
</ t r >
</ Al t er nat i ngI t emTempl at e>



Module 3: Using Microsoft ADO.NET to Access Data 43


To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer, view the ProductsList.aspx page by viewing
http://localhost/ASPNET/ProductsList.aspx?CategoryID=14
Your page should now look like the following illustration.

3. Click on a subject link.
4. Click on an Add to Cart link.


44 Module 3: Using Microsoft ADO.NET to Access Data


Exercise 3 (Optional)
Creating a Menu Page
In this exercise, you will create a menu for the Web site. The menu.aspx page
reads categories of data from the database and displays them in a DataList Web
control.
To create a new page
1. Create a new ASP.NET page named Menu.aspx in the ASPNET Web site.

There is a Menu.aspx file in the <install folder>\Labs\Lab03\Starter
folder that you can add to your project and edit.

2. Create a DataList control named lstMenu.
<asp: Dat aLi st i d=" l st Menu" wi dt h=" 145" r unat =" ser ver " >

</ asp: Dat aLi st >

3. Between the <asp:DataList> and </asp:DataList> tags, create an
ItemTemplate template that displays data in an asp:HyperLink control.
<I t emTempl at e>
<asp: Hyper Li nk i d=" Hyper Li nk1" CssCl ass=" MenuUnsel ect ed"
Text =' <%# Cont ai ner . Dat aI t em( "Cat egor yName") %>'
Navi gat eUr l =' <%# " pr oduct sl i st . aspx?Cat egor yI D=" & _
Cont ai ner . Dat aI t em( " Cat egor yI D" ) %>'
r unat ="ser ver " / >
</ I t emTempl at e>

The Text attribute of the asp:HyperLink control displays the
CategoryName field from the DataSet bound to the DataList. The
NavigateUrl attribute of the asp:HyperLink control links to the
ProductsList.aspx page, passing the ID of the selected category.

To fill the DataList control in the Page_Load event procedure
1. Add an Import statement to import the System.Data namespace.
2. Create a Page_Load event procedure in a <script> section.
3. Add the following code to read categories from the Conf database using a
method in the Conference component, and bind them to the lstMenu
DataList control:
Di mdvMenuI t ems As Dat aVi ew
Di mpr oduct s As New Conf er ence. Pr oduct sDB
dvMenuI t ems = pr oduct s. Get Pr oduct Cat egor i es( ) . _
Tabl es( 0) . Def aul t Vi ew

' Bi nd t he Dat aVi ew of menu i t ems t o t he l i st
l st Menu. Dat aSour ce = dvMenuI t ems
l st Menu. Dat aBi nd( )



Note
Module 3: Using Microsoft ADO.NET to Access Data 45


To save and test your work
1. Save your changes to Menu.aspx.
2. By using Internet Explorer, go to the Menu.aspx page,
http://localhost/ASPNET/menu.aspx
The page should look like the following illustration.

3. Test each hyperlink on the Menu.aspx page.


46 Module 3: Using Microsoft ADO.NET to Access Data


u Accessing Data with DataReaders
n Creating a DataReader
n Reading Data from a DataReader
n Demonstration: Accessing Data Using DataReaders
n Using DataSets vs. DataReaders

*****************************illegal for non-trainer use******************************
The benefit of using a DataSet is that it gives you a disconnected view of the
database. For long running applications, this is often the best approach. For
Web applications, developers usually perform short and simple operations with
each request, such as displaying data. For such operations, developers do not
need to maintain a DataSet object. In such cases, you can use a DataReader.
In this section, you will learn how to read data from a data source by using
DataReaders.

Module 3: Using Microsoft ADO.NET to Access Data 47


Creating a DataReader
n Create and Open the Database Connection
n Create the DataReader From a Command Object
n Close the Connection
Dim cmdAuthors As SqlCommand = New SqlCommand _
("select * from Authors", conn)
Dim dr As SqlDataReader
dr = cmdAuthors.ExecuteReader()
Dim cmdAuthors As SqlCommand = New SqlCommand _
("select * from Authors", conn)
Dim dr As SqlDataReader
dr = cmdAuthors.ExecuteReader()
Dim conn As SqlConnection = New SqlConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
conn.Open()
Dim conn As SqlConnection = New SqlConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
conn.Open()

*****************************illegal for non-trainer use******************************
When a large amount of data is being retrieved, holding memory open becomes
an issue. For example, reading 10,000 rows out of a database causes a
DataTable to allocate and maintain memory for those 10,000 rows for the
lifetime of the table. If 1,000 users do this against the same machine at the same
time, memory usage becomes critical.
To address such situations, the DataReader is designed to produce a read-only,
forward-only stream returned from the database. Only one record at a time is
ever in memory. There are two DataReader objects, the SqlDataReader and
the OleDbDataReader.
A DataReader keeps the connection open until the DataReader is closed.
To use a SqlDataReader, declare a SqlCommand instead of a
SqlDataAdapter. The SqlCommand exposes an ExecuteReadermethod that
takes a SqlDataReader as a parameter. Note that you must explicitly open and
close the SqlConnection when you use a SQLCommand.
Di mconn As Sql Connect i on = New Sql Connect i on _
( " ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs")
conn. Open( )

Di mcmdAut hor s As Sql Command = New Sql Command _
( " sel ect * f r omAut hor s" , conn)
Di mdr As Sql Dat aReader
dr = cmdAut hor s. Execut eReader ( )
. . .
dr . cl ose( )
conn. Cl ose( )


48 Module 3: Using Microsoft ADO.NET to Access Data


Error Handling with a DataReader
When using connections with the DataReader object, you should always use a
Finally blocking technique to ensure that, if anything fails, connections will be
closed.
Tr y
conn. Open( )
dr = cmdAut hor s. Execut eReader ( )
' use t he r et ur ned dat a i n t he dat ar eader
Cat ch e As Except i on
Consol e. Wr i t eLi ne( e. ToSt r i ng)
Fi nal l y
dr . Cl ose( )
conn. Cl ose( )
End Tr y


Module 3: Using Microsoft ADO.NET to Access Data 49


Reading Data from a DataReader
n Call Read for Each Record
l Returns false when there are no more records
n Call Get for Each Field
l Parameter is the ordinal position of the field
n Call Close to Free Up the Connection
myReader.Read()
lblName.Text = myReader.GetString(1) + ", " + _
myReader.GetString(2)
myReader.Close()
myReader.Read()
lblName.Text = myReader.GetString(1) + ", " + _
myReader.GetString(2)
myReader.Close()

*****************************illegal for non-trainer use**************************** **
After you have called the ExecuteReader method of the Command object, you
access a record in the DataReader by calling the Read method. The default
positioning in the DataReader is before the first record, therefore you must call
Read before accessing any data. When no more records are available, the Read
method returns a null value.
Reading Fields from the Current Record
To get the data from fields in the current record, call an appropriate Get method,
for example, GetDateTime, GetDouble, GetInt32, or GetString. The
parameter of the Get method is the ordinal value of the field that you want to
read.
For example, the following sample code reads the first name and last name
fields, both string values, from the first record of the DataReader, by using the
GetString() method:
myReader . Read( )
l bl Name. Text = myReader . Get St r i ng( 1) + " , " + _
myReader . Get St r i ng( 2)

You can also reference the fields of data in the current record of the data reader
by name, and then call an appropriate conversion function, as shown in the
following example code:
myReader ( "au_f name") . ToSt r i ng( )


50 Module 3: Using Microsoft ADO.NET to Access Data


Looping Through All Records
To loop through all the records in a DataReader, you can use a While loop, as
shown in the following sample code:
Whi l e myReader . Read( )
' do somet hi ng wi t h t he dat a
End Whi l e

Closing the DataReader
While the DataReader is in use, the associated connection is busy serving the
DataReader. Therefore, you must call Close to close the DataReader when
you are finished using it.
myReader . Cl ose( )


Module 3: Using Microsoft ADO.NET to Access Data 51


Demonstration: Accessing Data Using DataReaders

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to read data from a database by using a
SQLDataReader.
To run the demonstration
1. Edit the file <install folder>\DemoCode\ Mod03\Datareader.aspx
a. The Page_Load event procedure sets up the DataReader and outputs
the first record.
b. The Page_Unload event procedure closes the connection.
2. View the page in Internet Explorer.
3. Edit the file <install folder>\Democode\Mod03\datareadersp.aspx
This page fills a DataReader from a stored procedure and then displays the
results.
4. View the page in Internet Explorer.


52 Module 3: Using Microsoft ADO.NET to Access Data


Using DataSets vs. DataReaders
DataSet
1. Create a database
connection
2. Store query in DataAdapter
3. Populate DataSet with Fill
method
4. Create DataView
5. Bind DataView to list-bound
control
DataReader
1. Create a database connection
2. Open the database connection
3. Store query in SqlCommand
4. Populate DataReader with
ExecuteReader method
5. Call Read for each record, and
Get for each field
6. Manually display data
7. Close the DataReader and the
connection

*****************************illegal for non-trainer use******************************
The general procedure for accessing databases from ASP.NET is different
depending on whether you will be using a DataSet or a DataReader:
Using DataSets Using DataReaders

1. Connect to the database by using
SqlConnection or OleDbConnection.
1. Connect to the database by using
SqlConnection or OleDbConnection.
2. Store the database query in
SqlDataAdapter or
OleDbDataAdapter objects.
2. Open the connection with the Open
method.
3. Populate a DataSet from the
DataAdapter by using Fill.
3. Store database query in SqlCommand
or OleDbCommandobjects.
4. Set up a new DataView for the
desired table.
4. Populate a DataReader from the
Commandby using ExecuteReader
method.
5. Bind a server control, such as the
DataGrid, to the DataView.
5. Call Read and Get methods of the
DataReader to read data.
6. Close the DataReader.
7. Close the connection.


Module 3: Using Microsoft ADO.NET to Access Data 53


u Binding to XML Data
n Overview of XML
n Reading XML Data into a DataSet
n Demonstration: Reading XML Data into a DataSet

*****************************illegal for non-trainer use******************************
HTML is widely used for presenting information on the Web. HTML works
well as a presentation language, but it is not suitable for representing data. For
example, you can easily format data in an HTML table, but you cannot describe
the individual components of the information. To share information between
applications, you must have a language that can describe data in a standardized
way so that any application, present or future, can understand and use this data
correctly. XML is one such standardized language. XML not only helps you
structure your data but acts as a common language between different business
applications.
In this section, you will get an overview of XML. You will also learn how to
read and display XML data by using ADO.NET.

54 Module 3: Using Microsoft ADO.NET to Access Data


Overview of XML
n Machine-Readable and Human-Readable Data
n Defines the Data Content and Structure
n Separates Structure from Presentation
n Allows You to Define Your Own Tags and Attributes
<employee>
<name>Jake</name>
<salary>25000</salary>
<region>Ohio</region>
</employee>
<employee>
<name>Jake</name>
<salary>25000</salary>
<region>Ohio</region>
</employee>

*****************************illegal for non-trainer use******************************
Businesses today face many problems when it comes to organizing data. They
need to meet the following requirements:
n Data needs to be readable by both computers and users.
n Both the content and the structure of the data need to be defined.
n The structure of the data needs to be separate from the presentation of the
data.
n The structure needs to be open and extensible.

XML fulfills all these requirements.
XML defines the structure of data in an open and self-describing manner. This
allows data to be easily transferred over a network and consistently processed
by the receiver. XML describes how data is structured, not how it should be
displayed or used. XML documents contain tags that assign meaning to the
content of the document. These tags allow programmers to find the data they
need in the XML document.
For example, the following XML sample contains information about an
employee but does not specify how to display this information:
<empl oyee>
<name>J ake</ name>
<sal ar y>25000</ sal ar y>
<r egi on>Ohi o</ r egi on>
</ empl oyee>


Module 3: Using Microsoft ADO.NET to Access Data 55


XML is considered a markup language because it allows you to define data
structure by using markup tags. You can define your own tags that describe the
data in whatever way you find useful.
XML data is held in a simple, open format that is easily parsed by other
applications. The fact that XML documents contain text rather than binary data
is another key advantage. Applications can parse an XML document, looking
for specific tags of interest to those applications. Unknown tags and their
associated data can be freely ignored.

56 Module 3: Using Microsoft ADO.NET to Access Data


Reading XML Data into a DataSet
n Read the XML File
n Read the Contents of the File Stream
n Read Data from the StreamReader into a DataSet
fs = New FileStream _
(Server.MapPath("schemadata.xml"), _
FileMode.Open, FileAccess.Read)
fs = New FileStream _
(Server.MapPath("schemadata.xml"), _
FileMode.Open, FileAccess.Read)
Reader = New StreamReader(fs)
Reader = New StreamReader(fs)
ds.ReadXml(Reader)
ds.ReadXml(Reader)

*****************************illegal for non-trainer use******************************
DataSets in ADO.NET are designed to extract data in a way that is independent
of its data source. Therefore, reading data from an XML source is similar to
reading data from a database. To read XML data, you need to import the
System.IO namespace in your ASP.NET page.

You cant read XML data into a DataReader. You can read it only into a
DataSet.

For XML data, the DataSet supports a ReadXml method that takes a
FileStream as its parameter. The DataSet expects data to be in the following
format:
<Document El ement >
<Tabl eName>
<Col umnName1>col umn val ue</ Col umnName1>
<Col umnName2>col umn val ue</ Col umnName2>
<Col umnName3>col umn val ue</ Col umnName3>
</ Tabl eName>
<Tabl eName>
<Col umnName1>col umn val ue</ Col umnName1>
<Col umnName2>col umn val ue</ Col umnName2>
<Col umnName3>col umn val ue</ Col umnName3>
</ Tabl eName>
</ Document El ement >

Each TableName section corresponds to a single row in the table.

Note
Module 3: Using Microsoft ADO.NET to Access Data 57


The following example shows how to read the schema and data from an XML
file by using the ReadXml method, the FileStream object, and the
StreamReader object. Note that after the data is read into the DataSet, it is
indistinguishable from SQL datathe DataGrid binds to it in the same way.
To read XML data and display it in a DataGrid
1. First, open the XML file:
Di mf s As Fi l eSt r eam
f s = New Fi l eSt r eam_
( Ser ver . MapPat h( " schemadat a. xml " ) , _
Fi l eMode. Open, Fi l eAccess. Read)

2. Next, attach a StreamReader to the FileStream.
Di mReader As St r eamReader
Reader = New St r eamReader ( f s)

3. Finally, read the XML data from the StreamReader into the DataSet.
Di mds As New Dat aSet
ds. ReadXml ( Reader )


After the data has been read into a DataSet, the repeated elements in the XML
become the columns in the DataSet and can be bound to any control to be
displayed on the client.
The full sample code is as follows:
Di mds As New Dat aSet
Di mf s As Fi l eSt r eam
Di mReader As St r eamReader

' Read t he XML dat a i nt o a Dat aSet
f s = New Fi l eSt r eam_
( Ser ver . MapPat h( " schemadat a. xml " ) , _
Fi l eMode. Open, Fi l eAccess. Read)
Reader = New St r eamReader ( f s)
ds. ReadXml ( Reader )
f s. Cl ose( )

' Bi nd t he Dat aSet t o a Dat aGr i d
Di mSour ce As Dat aVi ew
Sour ce = new Dat aVi ew( ds. Tabl es( 0) )
MyDat aGr i d. Dat aSour ce = Sour ce
MyDat aGr i d. Dat aBi nd( )


58 Module 3: Using Microsoft ADO.NET to Access Data


Demonstration: Reading XML Data into a DataSet

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to read information from an XML file
and display it in a DataGrid control.
To run the demonstration
1. Open the file <install folder>\DemoCode\ Mod03\ Books1.xml.
This is the data that will be displayed from the ASPX page.
2. Edit the file <install folder>\DemoCode\ Mod03\xml.aspx.
a. There is a DataGrid control that uses templates to change the look of
the table.
b. The Page_Load event procedure reads the data from the Books1.xml
file into a DataSet and binds it to the DataGrid.
3. View the page in Internet Explorer.
4. Edit the file <install folder>\Democode\Mod03\aspXMLControl.aspx.
This page uses the XML Web control to read data from the Books1.xml file,
and apply the Books1.xsl style sheet.
5. View the page in Internet Explorer.


Module 3: Using Microsoft ADO.NET to Access Data 59


Review
n Overview of ADO.NET
n Connecting to a Data Source
n Accessing Data with DataSets
n Using Stored Procedures
n Accessing Data with DataReaders
n Binding to XML Data

*****************************illegal for non-trainer use******************************
1. What are some of the new objects in the ADO.NET object model?


2. What is the difference between a DataSet and a DataView?


3. What is the difference between a DataSet and a DataReader?



60 Module 3: Using Microsoft ADO.NET to Access Data


4. What is the purpose of the DataAdapter object?


5. Which method is used to populate a DataSet with results of a query?











Contents
Overview 1
Advantages of Partitioning an ASP.NET
Page 2
Creating and Using Code-Behind Pages 3
Creating and Using User Controls 12
Creating and Using Components 19
Lab 4: Separating Code from Content 27
Review 39

Module 4: Separating
Code from Content


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are ei ther registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 4: Separating Code from Content 1


Overview
n Advantages of Partitioning an ASP.NET Page
n Creating and Using Code-Behind Pages
n Creating and Using User Controls
n Creating and Using Components

*****************************illegal for non-trainer use******************************
Active Server Pages (ASP) applications contain a mix of Hypertext Markup
Language (HTML) and script, making the code difficult to read, debug, and
maintain. Microsoft ASP.NET eliminates this problem by promoting the
separation of code and content. That is, in ASP.NET, the user interface and the
user interface programming logic need not necessarily be written in a single
page.
There are three ways in which you can separate code and content in ASP.NET:
n By using code-behind files that are pre-compiled modules written in any of
the Microsoft .NET run-time-compliant languages.
n By creating user controlsfrequently used control sets and their logicand
using them as you would use controls in your ASP.NET pages.
n By moving business logic into components that can run on the server and
calling those components from server-side code.

After completing this module, you will be able to:
n Explain the need for code-behind pages.
n Create a code-behind page and use it with an ASP.NET page.
n Explain the advantages of user controls.
n Explain how user controls work.
n Create a component in Microsoft Visual Basic.
n Use a component in an ASP.NET page.

2 Module 4: Separating Code from Content


Advantages of Partitioning an ASP.NET Page
n Individual Members of the Development Team Can Work
on Separate, Individually-Owned Parts
n Developers Can Work Within Environments That Are
Familiar
n Web Authors Can Use HTML Development Tools to
Build the Interface

*****************************illegal for non-trainer use******************************
Partitioning ASP.NET pages into code and content has several advantages.
Partitioning eliminates confusing pages where code and HTML are intertwined,
producing pages that are easier to maintain and understand. In addition:
n Members of the development team can work on their own parts without
disturbing the work of others. For example, the interface designer can work
on the interface files at the same time that the programmer works on the
source code files.
n Partitioning code and content allows developers to use environments that
are familiar to them. For example, you can use separate editors to develop
the code.
n Web authors can use other HTML development tools to build the visible
interface part of an application.


Module 4: Separating Code from Content 3


u Creating and Using Code-Behind Pages
n Understanding How Code-Behind Pages Work
n Creating a Class File in Visual Basic
n Demonstration: Creating a Code-Behind Page
n Accessing Controls in a Code-Behind Page

*****************************illegal for non-trainer use******************************
User interface logic for a Web form relies on code that you create to interact
with the form. You can design your application so that the code resides in a
separate file known as the code-behind page, that is written in Visual Basic or
Microsoft Visual C#

. When you run the Web form, the code-behind class file
runs and dynamically produces the output for your page.
In this section, you will learn how code-behind pages work. You will also learn
how to create a code-behind class file in Visual Basic.

4 Module 4: Separating Code from Content


Understanding How Code-Behind Pages Work
n Use Page Directive to Link
the Two Files
n Call Procedures in the Code-
Behind Page
n Create Separate Files for User
Interface and Interface Logic
<%@ Page Inherits="myDemo"
Src="demo.vb"%>
<%@ Page Inherits="myDemo"
Src="demo.vb"%>
ds = getData()
ds = getData()
Public Class myDemo
Public Function getData()

End Function
End Class
Public Class myDemo
Public Function getData()

End Function
End Class
demo.vb
<%@Page
Inherits="myDemo"
Src= "demo.vb" %>
Page.aspx

*****************************illegal for non-trainer use******************************
Creating code-behind pages is relatively simple. It involves creating two
separate files, one for the user interface and the other for the user interface logic.
The interconnectivity between these two files is provided through the @Page
directive, which is used to specify optional settings at the page level.
Creating a User Interface File
First, you create the HTML for the interface. The interface file is an ASP.NET
page (that uses the .aspx extension). The first line of the interface ASP.NET
page is an @Page directive that specifies the name of the code-behind file and
the actual class name inside the code-behind file that will be used.
In the following example, the ASP.NET page is linked to the demo.vb class file.
The Inherits attribute specifies the class file to be used and the Src attribute
indicates the path to the class file itself.
<%@Page Language=" vb" I nher i t s=" myDemo" Sr c=" demo. vb" %>

Specifying the path to the class file is optional. If the path is omitted,
ASP.NET looks for the class file in the /bin directory of the application.

Creating a Code-Behind File
Next, you create a separate class file, in any of the supported languages, that
provides the functionality required for the user interface page. A code-behind
class file is identical to any other class file that you create in a particular
language.
In Visual Basic, the class file has a .vb extension. In Visual C#, the code-behind
page has a .cs extension. This ensures that the code-behind file is passed to the
correct compiler when the page is first executed.

Note
Module 4: Separating Code from Content 5


Using Code-Behind Procedures
To call a function or sub-procedure in a code-behind page, preface the name of
the procedure with the name of the code-behind page. For example, in the class
myDemo, in the code-behind page demo.vb, a function named getData returns
a DataSet object. The following sample code calls the getData function and
then displays the returned DataSet (ds) in the DataGrid control (dgAuthors).
Publ i c Sub Page_Load ( Sr c As Obj ect , E As Event Ar gs)
Di mds As Dat aSet
ds = get Dat a( )

dgAut hor s. Dat aSour ce=ds
dgAut hor s. Dat aMember =" Aut hor s"
dgAut hor s. Dat aBi nd( )
End Sub


6 Module 4: Separating Code from Content


Creating a Class File in Visual Basic
n Class File
n Using Objects from the ASP.NET Environment
n Inheriting from the ASP.NET Page Class
Public Class myDemo
Public Function getData() As DataSet

End Function
End Class
Public Class myDemo
Public Function getData() As DataSet

End Function
End Class
Imports System
Imports System.Web
Imports System
Imports System.Web
Public Class myDemo
Inherits System.Web.UI.Page

End Class
Public Class myDemo
Inherits System.Web.UI.Page

End Class

*****************************illegal for non-trainer use********************** ********
A code-behind class file is identical to any other class file that you might create
in your chosen programming language. The basic structure of a Visual Basic
class file looks like the following:
Publ i c Cl ass cl ass_name
Publ i c var i abl e_name As var i abl e_t ype
Publ i c Funct i on f unct i on_name( par amet er s) As r et ur n_ t ype

End Funct i on
Publ i c Sub sub_name( par amet er s)

End Sub
End Cl ass

Notice that, in the above class declaration, the functions, sub-procedures,
and the class are all public. Public procedures are used to invoke code-behind
pages from the user interface page.


Note
Module 4: Separating Code from Content 7


To convert the preceding class file structure into a code-behind class file, you
need to perform two steps:
1. Use the objects from the ASP.NET environment.
You need to import the objects from the ASP.NET environment that you
need to use in a class file. By default, all objects in an ASPX page import
the objects from the ASP.NET environment. However, this is not true for a
class file. Therefore, a class file, at the minimum, needs to import the
System and Web libraries from the ASP.NET environment. This is done as
follows:
I mpor t s Syst em
I mpor t s Syst em. Web

2. Inherit from the ASP.NET Page class.
Your class must inherit from the ASP.NET Page class so that it can be
integrated into the ASP.NET page in which it is used. This is done with the
Inherits statement.
Publ i c Cl ass cl ass_name
I nher i t s Syst em. Web. UI . Page

End Cl ass


The following is a code-behind page with one class named myDemo, and one
public function named getData. The function reads data from a database and
returns it to the user interface page as a DataSet object.
I mpor t s Syst em
I mpor t s Syst em. Web
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent

Publ i c Cl ass myDemo
I nher i t s Syst em. Web. UI . Page

Publ i c Funct i on get Dat a( ) As Dat aSet
Di mds As Dat aSet
Di mconn As Sql Connect i on
Di mcmdAut hor s As Sql Dat aAdapt er

conn = New Sql Connect i on _
( " ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs" )
cmdAut hor s = New Sql Dat aAdapt er _
( " sel ect * f r omAut hor s" , conn)

ds = new Dat aSet ( )
cmdAut hor s. Fi l l ( ds, " Aut hor s" )

r et ur n ( ds)
End Funct i on
End Cl ass


8 Module 4: Separating Code from Content


Demonstration: Creating a Code-Behind Page

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create a code-behind page and use it
from an ASP.NET page.
To run the demonstration
1. Edit the page <install folder>\Democode\Mod04\beforeCodeBehind.aspx
using Notepad.
This page has both code and content.
2. Open the files codeBehindDemo.vb and codeBehind.aspx in the folder
<install folder>\Democode\Mod04.

The file codebehind.aspx cannot be opened in Visual
Studio .NET. You must use Notepad or another text editor.

These files perform the same function as the beforeCodeBehind.aspx page,
but use a code-behind page.
3. View the page codeBehind.aspx in Microsoft Internet Explorer.


Important
Module 4: Separating Code from Content 9


To demonstrate using code-behind pages in Microsoft
Visual Studio .NET
Visual Studio .NET uses code-behind pages by default.
1. Add a new Web form to a Visual Studio .NET project.
2. Add a label Web control and a button Web control from the toolbox to the
page.
3. View the HTML for the page and notice the attributes of the @Page
directive.
4. Return to Design view and double-click the button Web control.
This opens the code-behind page, and creates a click event procedure for the
button.
Publ i c Sub But t on1_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on1. Cl i ck
End Sub

5. Add code to change the Text property of the label control.
Label 1. Text = " cl i cked"

6. Build the project.
In Visual Studio .NET, the code-behind pages are compiled into an
assembly. You need to build the project before they will be accessible.
7. View the page in Internet Explorer.


10 Module 4: Separating Code from Content


Accessing Controls in a Code-Behind Page
n Import Namespaces for Controls
n Declare Variables with Same Name as Controls
n Reference Properties of Controls
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Dim lbl As Label
Dim txt As TextBox
Dim lbl As Label
Dim txt As TextBox
Public Sub btn_Click (s as Object, e As EventArgs)
lbl.Text = "You are searching for " & txt.Text
End Function
Public Sub btn_Click (s as Object, e As EventArgs)
lbl.Text = "You are searching for " & txt.Text
End Function

*****************************illegal for non-trainer use******************************
You can create event procedures for the controls on a form in a code-behind
page. In this way, you can transfer most of the code from the user interface
page to a code-behind page.
To do this, you need to import the namespace for the controls you are using,
either System.Web.UI.WebControls or System.Web.UI.HtmlControls. You
then need to declare public variables for the controls on the ASPX page.
For example, the following is a form on the ASPX page with three controls:
<f or m r unat =ser ver >
<asp: t ext box i d="t xt " r unat ="ser ver " / >
<asp: but t on i d=" bt n" oncl i ck=" bt n_cl i ck"
t ext =" Cl i ck Me" r unat =" ser ver " / >
<P><asp: l abel i d=" l bl " r unat =" ser ver " / >
</ f or m>


Module 4: Separating Code from Content 11


The code-behind page can include the event procedure and reference the
controls on the page, as shown in the following example:
I mpor t s Syst em
I mpor t s Syst em. Web
I mpor t s Syst em. Web. UI . WebCont r ol s

Publ i c Cl ass myDemo
I nher i t s Syst em. Web. UI . Page

Publ i c l bl As Label
Publ i c t xt As Text Box

Publ i c Sub bt n_cl i ck( s As Obj ect , e As Event Ar gs)
l bl . Text = t xt . Text
End sub
End Cl ass


12 Module 4: Separating Code from Content


u Creating and Using User Controls
n Creating a User Control
n Using a User Control in an ASP.NET Page
n Demonstration: Creating a User Control

*****************************illegal for non-trainer use******************************
A user control is an ASP.NET page that is imported as a server control by
another ASP.NET page. User controls provide an easy way to partition and
reuse simple and common user interface (UI) functionality across a Web
application. User controls are not pre-compiled. However, because all
ASP.NET pages are compiled as soon as they are requested, user controls are
compiled on demand and cached in server memory.
User controls have many advantages:
n User controls are self-contained. They provide separate variable namespaces,
which means that none of the methods and variables of the user control
conflict with any existing methods and variables of the hosting page.
n User controls can be used more than once within a hosting page without
causing variable and method conflicts.
n User controls can be written in a different language from the main hosting
page.

The main difference between code-behind pages and user controls is that code-
behind pages mainly involve inheriting code classes into a page and user
controls also allow you to generate parts of the user interface.

Module 4: Separating Code from Content 13


Creating a User Control
n User-Defined Server Control with an . ascx Extension
l <%@ Control Language="vb" %>
l Contains HTML but not <HTML>, <BODY>, or <FORM>
l Contains code to handle its own events
n Public Properties and Methods are Promoted to
Properties and Methods of the Control in the Host Page
Public Property pNum As Integer
Get
Return CInt(txtNum.Text)
End Get
End Property
Public Property pNum As Integer
Get
Return CInt(txtNum.Text)
End Get
End Property

*****************************illegal for non-trainer use******************************
User controls are ASP.NET pages used as server controls. User controls have
an .ascx extension. This file extension ensures that the user controls page
cannot be executed as a stand-alone ASP.NET page. User controls largely
replace include files. They are used to address the same problems that were
solved by using include files, such as dealing with headers, navigation bar,
repeating blocks of code, and so on.
A user control consists of HTML and code, but because user controls are
included in existing pages, they do not contain <head>, <body>, or <form> tags.
Those tags are included in the host ASP.NET page. User controls participate in
the complete execution life cycle of every request and can handle their own
events, encapsulating some of the page logic from the containing ASP.NET
page. For example, a user control can handle its own postback in its
Page_Load event procedure.

14 Module 4: Separating Code from Content


The following code is the HTML part of a user control that combines a text box
and two input validation controls:
<%@Cont r ol Language=" vb" %>

<asp: t ext box i d=" t xt Num" r unat =" ser ver " / >
<asp: Requi r edFi el dVal i dat or i d=" t xt NumVal i dat or "
r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Num"
er r or Message="You must ent er a val ue"
di spl ay="dynami c">
</ asp: Requi r edFi el dVal i dat or >
<asp: RangeVal i dat or i d=" t xt NumRngVal i dat or " r unat =" ser ver "
cont r ol ToVal i dat e=" t xt Num"
er r or Message=" Pl ease ent er a number bet ween 0 and 99"
t ype="I nt eger "
mi ni mumVal ue="0"
maxi mumVal ue="99"
di spl ay="dynami c">
</ asp: RangeVal i dat or >

To expose values of controls to the containing page, create public properties.
For example, the following code creates a property named pNum that is the
Text property of the text box control in the user control:
<SCRI PT l anguage=" VB" r unat =" Ser ver " >
Publ i c Pr oper t y pNumAs I nt eger
Get
Ret ur n CI nt ( t xt Num. Text )
End Get
Set
t xt Num. Text = Val ue. ToSt r i ng( )
End Set
End Pr oper t y
</ SCRI PT>

All public variables, properties, and methods of a user control are promoted to
properties (that is, tag attributes) and methods of the control in the containing
page.

Module 4: Separating Code from Content 15


@Control directive
You can also have code-behind pages for user controls. The @Control
directive is used to reference a user control from a code-behind page. It also
defines user-control-specific attributes used by the ASP.NET page parser and
compiler. This directive can only be used with user controls.
<%@Cont r ol at t r i but e=val ue [ at t r i but e=val ue ] %>

For example, to reference a code-behind page for a user control, you use the
following line of code:
<%@Cont r ol I nher i t s=" myDemo" sr c=" demo. vb" %>

The @Control directive supports the same attributes as the @Page
directive, except the AspCompat and Trace attributes. To enable tracing, you
must add the Trace attribute to an @Page directive in the ASPX page that
contains the user control. You can only include one @Control directive
per .ascx file.


Note
16 Module 4: Separating Code from Content


Using a User Control in an ASP.NET Page
n Include User Controls in Another ASP.NET Page Using
the Register Directive
n Insert the User Control Like a Server Control
n Set Properties of the User Control
<%@ Register TagPrefix="conference"
TagName="validNum" Src="numberBox.ascx" %>
<%@ Register TagPrefix="conference"
TagName="validNum" Src="numberBox.ascx" %>
<conference:validNum id="num1"
runat="server"/>
<conference:validNum id="num1"
runat="server"/>
num1.pNum = 5
num1.pNum = 5

*****************************illegal for non-trainer use******************************
User controls are included in an ASP.NET page by using the @Register
directive:
<%@Regi st er TagPr ef i x=" conf er ence" TagName=" val i dnum"
Sr c=" number box. ascx" %>

The TagPrefix attribute determines a unique namespace for the user control so
that multiple user controls with the same name can be differentiated from each
other. The TagName attribute is the unique name for the user control. The Src
attribute is the virtual path to the user control file. After registering the user
control with the @Register directive, you can place the user control tag in the
ASP.NET page just as you would an ordinary server control (including the
runat="server" attribute).
<conf er ence: val i dNumi d=" num1" r unat =" ser ver " / >
<conf er ence: val i dNumi d=" num2" r unat =" ser ver " / >

When the main ASP.NET page is loaded, the run-time framework compiles the
user control file and makes it available to the page.
After the user control is available to the page, you can access its properties as
follows:
l bl Sum. Text = ( num1. pNum+ num2. pNum) . ToSt r i ng( )


Module 4: Separating Code from Content 17


Demonstration: Creating a User Control

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create and use a user control.
The files numberbox.ascx and add.aspx in the folder
<install folder>\Democode\Mod04 contain the completed code for this
demonstration.
To run the demonstration
1. Open the page <install folder>\Democode\Mod04\beforeuser.aspx.
This page has all controls and logic in one file.
2. Open the page numberbox.ascx in the folder
<install folder>\Democode\Mod04.
Numberbox.ascx is a user control that performs the same function as each
text box on the page beforeuser.asps.
3. Add the @Register directive to the beforeuser.aspx page to use the
numberbox.ascx user control.
<%@Regi st er TagPr ef i x=" demos" TagName=" val i dNum"
Sr c=" number box. ascx" %>

4. Delete the four input validation controls from the beforeuser.aspx page.
5. Change the two text box controls to be <demos:validNum> controls. Use
the same ID values.
Num1: <demos: val i dNumi d=" t xt Num1" r unat =" ser ver " / >
Num2: <demos: val i dNumi d=" t xt Num2" r unat =" ser ver " / >


18 Module 4: Separating Code from Content


6. Change the Submit event procedure to read values from the user controls.
Sub submi t ( s As Obj ect , e As Event Ar gs)
I f Page. I sVal i d Then
l bl Sum. Text = _
CSt r ( Conver t . ToI nt 32( t xt Num1. pNum) + _
Conver t . ToI nt 32( t xt Num2. pNum) )
End I f
End Sub

7. View the beforeuser.aspx page in Internet Explorer.
8. View the HTML source in Internet Explorer.


Module 4: Separating Code from Content 19


u Creating and Using Components
n Deploying Components
n Creating Components
n Using Components in an ASP.NET Page
n Demonstration: Creating and Using a Component

*****************************illegal for non-trainer use******************************
In ASP.NET, business objects are the building blocks for multi-tiered Web
applications, such as those with a layer for data access or common application
rules. In this section, you will learn how to write some simple components and
include them in your ASP.NET pages.
The classic use for an external component is in a two-tier scenario to perform
data access. This simplifies the code in your page, improving readability and
separating your UI logic from the back-end functionality.
The three-tiered application model extends the two-tiered scenario to include
business rules between the UI and data access logic. The three-tiered model
allows UI developers to work with a higher level of abstraction rather than
directly manipulating data through low-level data access component application
programming interfaces (APIs). The middle business component typically
enforces business rules and ensures that the relationships and primary key
restraints of the database are enforced.

20 Module 4: Separating Code from Content


Deploying Components
n No Registration Required
l Components may be deployed by simply copying to the /bin dir or
performing an FTP file transfer
n No Server Restart Required
l The Web server does not require a restart when you change your
application
l New requests immediately begin execution against the changed file
n No Namespace Conflicts
l Each assembly loaded from /bin is limited in scope to the application
in which it is running

*****************************illegal for non -trainer use******************************
A problem with using the classic Component Object Model (COM) model for
Web application components is that the components must be registered on the
server before they can be used from a traditional ASP application. Remote
administration of these components is often not possible, because the
registration utility must be run locally on the server. In addition, these
components remain locked on disk after they are loaded by an application and
the entire Web server must be stopped before these components can be replaced
or removed.
ASP.NET solves these problems by allowing components to be placed in a
well-known directory that is automatically found at run time. This directory is
named /bin, and is located immediately under the root directory for the
application.
Following are the advantages of storing components in the /bin directory:
n No registration required
No registration is required to make components available to the ASP.NET
application. Components may be deployed by simply copying a file to the
/bin directory or performing a File Transfer Protocol (FTP) file transfer.
n No server restart required
When the component is changed by replacing a .dll in the /bin directory,
new requests by ASP.NET applications immediately begin execution
against the changed file(s). ASP.NET allows currently executing requests to
complete before the old application is replaced with the updated
component(s). The Web server does not require a restart when you change
components.
n No namespace conflicts
Each component loaded from /bin is limited in scope to the application in
which it is running. This means that many applications could potentially use
different components with the same class or namespace names, without
conflict.

Module 4: Separating Code from Content 21


Creating Components
n A Component Is Basically a Class
n Creating a Component
n Compiling the Class
Imports System.Data.SQL
Namespace myComponent
Public Class ConferenceDB
Public Function getCategories(...)

End Class
End Namespace
Imports System.Data.SQL
Namespace myComponent
Public Class ConferenceDB
Public Function getCategories(...)

End Class
End Namespace
vbc /t:library /out:component.dll component.vb
vbc /t:library /out:component.dll component.vb

*****************************illegal for non-trainer use******************************
A component at its most basic level is simply a class. The component can be
instantiated from an ASP.NET page that imports the component.
Code-Behind vs. Components
A code-behind page is an uncompiled class file. It does not define a namespace
that can be used by many applications. Instead, it defines a class that the .aspx
page inherits from. Therefore, the .aspx page can immediately call methods and
use properties of the code-behind page; you do not need to instantiate an object.
An .aspx page uses a code-behind page by adding the following to the @Page
directive:
Code-Behind Example
<%@Page Language=" vb" I nher i t s=" myDemo" Sr c=" demo. vb" %>

A component is always compiled into a dynamic-link library (DLL). Any page
can access the DLL. You need to instantiate an object of the class before calling
its methods. An ASPX page uses a component by adding the following code:
Component Example
<%@I mpor t Namespace=" myComponent " %>


22 Module 4: Separating Code from Content


Creating a Component
A component class file includes a namespace declaration and class declarations.
Namespace myComponent
Publ i c Cl ass Conf er enceDB
. . .
End Cl ass
End Namespace

Namespaces are used as an organizational system. They provide a way to
present program components that are exposed to other programs and
applications. Namespaces are always Public; however, the classes within the
namespace may have Public, Friend, or Private access.
Just as you would with code-behind pages, you need to import any libraries that
you use in the page.
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent

The following code is an example of a simple class called the ConferenceDB
class. This class has a function that retrieves a list of categories from the
database.
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent

Namespace myComponent
Publ i c Cl ass Conf er enceDB

Publ i c Funct i on get Cat egor i es _
( conn As Sql Connect i on) As Dat aSet
' Ret r i eve a l i st of cat egor i es f r omt he dat abase
End Funct i on

End Cl ass
End Namespace


Example
Module 4: Separating Code from Content 23


Compiling the Component
To compile this class, you can either click Build on the Build menu in Visual
Studio .NET or run the compiler from the MS-DOS command prompt. The /t
option tells the compiler that you want to build a library (.dll), and the /out
option tells the compiler where to place the resulting assembly. An assembly is
a collection of resources that are built to work together to deliver a cohesive set
of functionality. An assembly carries all the rules necessary to ensure cohesion
of functionalities. It is the unit of access to the resources in the Common
Language Runtime (CLR).
vbc / t : l i br ar y / out : component . dl l component . vb

If the component imports other libraries, you must reference them in the
compile statement. For example, if you are using the System.Data namespace,
include the System.Data.dll library, as shown in the following example:
vbc / t : l i br ar y / out : component . dl l / r : Syst em. Dat a. dl l
component . vb

Finally, after compiling the component, move it to the \bin folder in the root of
the virtual directory for your Web site.

You must define a virtual directory for your Web site.

The component is now available for use in an ASP.NET page.

Important
24 Module 4: Separating Code from Content


Using Components in an ASP.NET Page
n Adding a Component
n Using the Component
<%@ Import Namespace="myComponent" %>
<%@ Import Namespace="myComponent" %>
Dim x As New ConferenceDB
ds = x.getCategories(conn)
Dim x As New ConferenceDB
ds = x.getCategories(conn)
component.dll
Namespace myComponent
Class ConferenceDB
End Class
End Namespace

*****************************illegal for non-trainer use******************************
By default, ASP.NET loads all assemblies from the /bin directory when the
application is started. The assemblies to load are specified through the
configuration system. Additional assemblies may also be imported into an
application by using the configuration file.
Because the assembly is pre-loaded by the ASP.NET run time, only a simple
namespace import or variable declaration is required to make the component
available.
There are two ways to use the classes defined in a component. You can either
import the namespace by using an @Import directive, or reference the
namespace when declaring a variable.
Using the @Import directive
To include any component in an ASP.NET page, you need to add the @Import
directive that specifies the namespace to include at the top of the page. For
example, to include the myComponent component, you add the following
directive at the top of the page:
<%@I mpor t Namespace=" myComponent " %>

You can then instantiate an object of the class by referencing the class name
directly, as shown in the following example.
Di mx As New Conf er enceDB


Module 4: Separating Code from Content 25


Referencing Namespace when Declaring a Variable
You can also declare a variable directly from a component, without adding the
@Import directive to the page, by referencing the namespace in the declaration.
For example, to declare a variable from the myComponent component, use the
following code:
Di mx As New myComponent . Conf er enceDB

If you create and compile the component in Visual Studio .NET, you will
need to preface the namespace with the name of the Visual Studio .NET project.
For example, if the component.vb file is located in a Visual Studio .NET project
named demos, you would use the following Imports statement or variable
declaration to reference it:
<%@I mpor t Namespace=" demos. myComponent " %>
or
Di mx As New demos. myComponent . Conf er enceDB


Calling Component Methods
After you have instantiated an object from the class, you can access its
properties and methods. The following example shows how to call the
getCategories method of the ConferenceDB class.
ds = x. get Cat egor i es( conn)


Note
26 Module 4: Separating Code from Content


Demonstration: Creating and Using a Component

*****************************illegal for non-trainer use******************************
In this demonstration, you will see a simple component and how to use it in an
ASP.NET page.
To run the demonstration
1. Open the file component.vb from the folder
<install folder>\DemoCode\Mod04.
2. Compile the file (manually, or using Visual Studio .NET).
a. If you use the batch file mkdemos.bat to compile the component, you
need to create a \bin folder in the <install folder> folder, which is the
root of the 2063 virtual directory, and move the component.dll file into it.
b. If you build in Visual Studio .NET, the assembly is automatically moved
to the \bin folder of the project, but you will need to change the
@Import directive in the displaycomponent.aspx page to:
<%@I mpor t Namespace=" pr oj ect name. myComponent " %>

3. Open the displaycomponent.aspx page.
The @Import directive imports the namespace from the component. The
getCategories function is called in the Page_Load event procedure.
4. View the displaycomponent.aspx page in Internet Explorer. View the source
HTML of the page.
The code from the component was not added to the file.


Module 4: Separating Code from Content 27


Lab 4: Separating Code from Content

*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Create a user control.
n Insert a user control into an .aspx page.
n Create and use components.

Prerequisite
Before working on this lab, you must know how to use Web controls in an
ASP.NET page.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab04\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab04\Solution.
The ASPNET Web application uses classes in the Conference component.
There are five files in this component: ConferenceDB.vb, CustomersDB.vb,
ProductsDB.vb, ShoppingCartDB.vb, and OrdersDB.vb. These files are in the
Components folder of the ASPNET Web application. If, for any reason, you
need to rebuild the Conference component, run the mk.bat batch file from a
command prompt. The mk.bat batch file creates the conference.dll component
and then puts it in the bin folder of the ASPNET Web application.

28 Module 4: Separating Code from Content


Scenario
All the Web pages in the ASPNET Web site have the same controls at the top
and down the left side of the page. These controls can be put into user controls
and then easily added to the pages. In Exercise 1, you will create a user control
and in Exercise 2, you will add the user control to the ProductsList.aspx page.
Also, many of the pages in the ASPNET Web site use data obtained from the
Conference database. In Exercise 3, you will create a component to isolate and
reuse the data access code. In Exercise 4, you will call methods on your
component from the ProductsList.aspx page.
Estimated time to complete this lab: 60 minutes

Module 4: Separating Code from Content 29


Exercise 1
Creating a Menu User Control
In this exercise, you will convert an .aspx page into a user control. The page
Menu.aspx reads categories of data from the database and displays them in a
DataList Web control. In this exercise, you will convert the Menu.aspx page
into a user control.
To create the user control file
1. Open the file named Menu.aspx from the ASPNET Web site.
2. Remove the HTML tags.
3. Remove the BODY tags.
4. Change the @Page directive into an @Control directive.
<%@Cont r ol Language=" vb" %>

5. Save the page as _Menu.ascx (overwrite the existing _Menu.ascx file).


30 Module 4: Separating Code from Content


Exercise 2
Using User Controls
In this exercise, you will add two user controls to the ProductsList.aspx page.
One control will be located along the top of the page and can be found in the
file _header.ascx. The other will be located at the left side of the page and can
be found in the file _menu.ascx that you just created in Exercise 1.
When you are finished with this exercise, the page ProductsList.aspx should
look like the following illustration.

To add the header and menu user controls
1. Open the page ProductsList.aspx in the ASPNET Web site.
2. Include the header and menu user controls at the beginning of the page by
using the @Register directive. Set the attributes for the controls as shown in
the following table.
TagPrefix TagName Src

Conference Header _Header.ascx
Conference Menu _Menu.ascx

Your code should look like the following:
<%@Regi st er TagPr ef i x=" Conf er ence" TagName=" Header "
Sr c=" _Header . ascx" %>
<%@Regi st er TagPr ef i x=" Conf er ence" TagName=" Menu"
Sr c=" _Menu. ascx" %>


Module 4: Separating Code from Content 31


3. Create an HTML table in the body of the page to hold the two user controls
and the contents of the original page. You will need to build the table
around the existing contents of the page.

HEADER

M
E
N
U


CONTENT

Your HTML code should look like the following:
<t abl e wi dt h=" 100%" bor der =0>
<t r ><t d>
<!- - _Header . ascx user cont r ol - - >
</ t d></ t r >
<t r ><t d>
<t abl e bor der =0>
<t r ><t d val i gn=" t op" >
<! - - _Menu. ascx user cont r ol - - >
</ t d>
<t d>

<! - - Exi st i ng cont ent s of t he page - - >
<! - - bet ween <body> and </ body> t ags - - >

</ t d>
</ t r >
</ t abl e>
</ t d></ t r >
</ t abl e>


32 Module 4: Separating Code from Content


4. Add the header and menu user controls to the correct position in the table.
Your HTML code should look like the following:
<t abl e wi dt h=" 100%" bor der =0>
<t r ><t d>
<!- - _Header . ascx user cont r ol - - >
<Conf er ence: Header r unat =" ser ver " / >
</ t d></ t r >
<t r ><t d>
<t abl e bor der =0>
<t r ><t d val i gn=" t op" >
<! - - _Menu. ascx user cont r ol - - >
<Conf er ence: Menu r unat =" ser ver " / >
</ t d>
<t d>

<! - - Exi st i ng cont ent s of t he page - - >
<! - - bet ween <body> and </ body> t ags - - >

</ t d>
</ t r >
</ t abl e>
</ t d></ t r >
</ t abl e>


To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer, go to the ProductsList page of the ASPNET Web
site by viewing:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15

CategoryID=15 corresponds to the Conference Trackscategory in
the Categories table of the database.

Notice the header and menu user controls.


Note
Module 4: Separating Code from Content 33


Exercise 3
Building a Component
Currently, the page ProductsList.aspx reads data from the database and displays
it in a Repeater control. In this exercise, you will build a component,
GetProducts.vb, to read the data from the database. Then, in Exercise 4, you
will use that component in the ProductsList.aspx page.
To create the GetProducts.vb component
1. Create a new file named GetProducts.vb in the Components folder of the
ASPNET Web site.
If you are using Visual Studio .NET, do the following:
a. Right-click on the Components folder in the ASPNET project in the
Solution Explorer window, click Add, and then click Add Component.
b. In the Add New Item dialog box, click Component Class, type
GetProducts.vb in the Name field, and then click Open to generate and
open the new file.
2. Add the following code to import namespaces:
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent

3. Create a new namespace named db2063.
4. Create a public class named Products.
Your code should look like the following:
Namespace db2063
Publ i c Cl ass Pr oduct s

End Cl ass
End Namespace



34 Module 4: Separating Code from Content


To add a method to the Products class
1. Create a new function named GetProducts that takes an Integer parameter
named categoryID and returns a DataSet.
Publ i c Funct i on Get Pr oduct s( cat egor yI D As I nt eger ) As _
Dat aSet

2. Open the ProductsList.aspx page.
3. Cut the content of the Page_Load event procedure, except for the first
instruction that reads the CategoryID query string parameter and the last
two instructions that set the DataSource of the Repeater controls. The
Page_Load event procedure code should look like the following after you
have cut the instructions as specified above:
Sub Page_Load( Sour ce As Obj ect , E As Event Ar gs)
' Obt ai n Cat egor yI D f r omQuer ySt r i ng
Di mcat egor yI D As I nt eger = _
CI nt ( Request . Par ams( " Cat egor yI D" ) )

' Bi nd t o t he cont r ol
r epLi st . Dat aSour ce = dsPr oduct s. Tabl es( 0) . Def aul t Vi ew
r epLi st . Dat aBi nd( )
End Sub

4. Save the changes to ProductsList.aspx.
5. Paste this code into the GetProducts function in the GetProducts.vb
component.

Module 4: Separating Code from Content 35


6. Add a return statement to return the Dataset at the end of the function.
Your function should look like the following:
Publ i c Funct i on Get Pr oduct s( cat egor yI D As I nt eger ) As _
Dat aSet
Di mconn As Sql Connect i on
Di mst r Conn As St r i ng
Di mcmdPr oduct s As Sql Dat aAdapt er
Di mpar amCat egor yI D As Sql Par amet er
Di mdsPr oduct s As New Dat aSet

' Cr eat e t he connect i on
st r Conn = _
" ser ver =l ocal host ; ui d=sa; pwd=1Aspnet ; dat abase=Conf "
conn = New Sql Connect i on( st r Conn)

' Cal l t he Pr oduct sByCat egor y st or ed pr ocedur e
cmdPr oduct s = _
New Sql Dat aAdapt er ( " Pr oduct sByCat egor y" , conn)
cmdPr oduct s. Sel ect Command. CommandType = _
CommandType. St or edPr ocedur e

' Add Par amet er s
par amCat egor yI D = _
New Sql Par amet er ( " @Cat egor yI D" , Sql DbType. I nt , 4)
par amCat egor yI D. Val ue = cat egor yI D
cmdPr oduct s. Sel ect Command. Par amet er s. Add( par amCat egor yI D)

' Fi l l t he Dat aSet
cmdPr oduct s. Fi l l ( dsPr oduct s, " Pr oduct s" )

' Ret ur n t he Dat aSet
r et ur n dsPr oduct s

End Funct i on

Visual Studio .NET Beta 2 may insert parentheses at the end of your
function declaration or elsewhere. Be sure to compare your code with the
preceding example and remove any extra parentheses before continuing.

7. Save your changes to GetProducts.vb.


Note
36 Module 4: Separating Code from Content


To compile the component
There are two ways to compile the component: in an MS-DOS command
prompt, or in Visual Studio .NET.
1. To compile the component in an MS-DOS command prompt:
a. Open an MS-DOS command prompt.
b. Navigate to the folder InetPub\wwwroot\ASPNET\components.
c. Run the following command:
vbc / t : l i br ar y / out : . . \ bi n\ db2063. dl l / r : Syst em. dl l
/ r : Syst em. Web. dl l / r : Syst em. Xml . dl l / r : Syst em. Dat a. dl l
Get Pr oduct s. vb

The compiler generates a file named db2063.dll in the ASPNET\bin
directory.
2. To compile the component in Visual Studio .NET, on the Build menu, click
Build.
The compiler adds the new class to the project assembly named
ASPNET.dll in the ASPNET\bin directory.


Module 4: Separating Code from Content 37


Exercise 4
Calling a Component
In this exercise, you will call the component that you built in Exercise 3 to get a
DataSet of products that you will display on the ProductsList.aspx page.
Client
Middle-tier
components
Data
GetProducts.vb ProductsByCategory Stored Procedure

ProductList.aspx

To call the component from the ProductsList.aspx page
1. Open the page ProductsList.aspx from the ASPNET Web site.
2. Edit the Page_Load event procedure.
3. Declare a variable named productCatalog that is an instance of the
Products class in the db2063 namespace.

If you used Visual Studio .NET to compile the component, you must
preface the namespace of the component with the root namespace (the
project name) of the project.

If you used a command prompt to compile the component, your code should
look like the following:
Di mpr oduct Cat al og As New db2063. Pr oduct s

If you used Visual Studio .NET to compile the component, your code
should look like the following:
Di mpr oduct Cat al og As New ASPNET. db2063. Pr oduct s

4. Declare a DataSet variable named dsProducts.
5. After the code that reads the categoryIDparameter from the QueryString
object, call the GetProducts method of the component and save the result in
the dsProducts variable.
Your code should look like the following:
Di mdsPr oduct s As New Dat aSet

dsPr oduct s = pr oduct Cat al og. Get Pr oduct s( Cat egor yI D)



Note
38 Module 4: Separating Code from Content


To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer, go to the ProductsList page of the ASPNET Web
site by viewing:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
The page should display the table of conference tracks.


Module 4: Separating Code from Content 39


Review
n Advantages of Partitioning an ASP.NET Page
n Creating and Using Code-Behind Pages
n Creating and Using User Controls
n Creating and Using Components

*****************************illegal for non -trainer use******************************
1. List some of the advantages of separating code from content.


2. How do you link the user interface page to its code-behind file?


3. What are the ASP.NET namespaces that you need to import in a code-
behind class file?



40 Module 4: Separating Code from Content


4. What are some of the differences between a regular ASP.NET page and a
user control?


5. What is the biggest advantage that ASP.NET offers for using external
components?


6. How do you use a user control from an ASP.NET page?


7. How do you use a component from an ASP.NET page?












Contents
Overview 1
Overview of Tracing 2
Trace Information 3
Page-Level Trace 4
Application-Level Trace 10
Lab 5: Adding Trace to an ASP.NET Page 16
Review 21

Module 5: Using Trace
in Microsoft ASP.NET
Pages


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 5: Using Trace in Microsoft ASP.NET Pages 1


Overview
n Overview of Tracing
n Trace Information
n Page-Level Trace
n Application-Level Trace

*****************************illegal for non-trainer use******************************
In earlier versions of Active Server Pages (ASP), code tracing was
accomplished by inserting Response.Write statements wherever required. A
drawback of this technique was the removal of the excess code that was added
when the application was deployed, and the resulting inability to use the output
from the Response.Write statements in a production environment. Microsoft
ASP.NET overcomes such drawbacks by introducing an automatic tracing
mechanism. This tracing mechanism can be enabled and disabled either on a
page-by-page basis or for an entire application, and it can be configured in the
web.config file.
After completing this module, you will be able to:
n Describe page-level and application- level tracing.
n Enable and disable tracing for an ASP.NET page.
n Add custom trace information.

2 Module 5: Using Trace in Microsoft ASP.NET Pages


Overview of Tracing
n With Tracing You Can:
l Output variables or structures
l Assert whether a condition is met
l Trace through the execution path of the application
n Can Be Enabled and Disabled, Either on a Page-By-Page
Basis or for an Entire Application

*****************************illegal for non-trainer use******************************
The tracing feature in ASP.NET enables you to insert debugging print
statements into your code. These statements allow you to output variables or
structures, assert whether a condition is met, or trace through the execution path
of the application.
All of this information is output to an .aspx page or saved to a log, depending
on settings in the web.config file.
You can also use the Debug object to output debugging information. By using
methods in the Debug object to print debugging information and check your
logic with assertions, you can make your code more robust without impacting
your shipping product's performance and code size.
While you are debugging an application during development, both your trace
and debug output statements go to the Output window in Microsoft
Visual Studio .NET. However, with trace statements, you can debug a
production Web site simply by changing a setting in the web.config file and
having the trace statements output on the page.
In this course, we will focus only on the trace feature of ASP.NET.

Module 5: Using Trace in Microsoft ASP.NET Pages 3


Trace Information

*****************************illegal for non -trainer use******************************
Tracing provides plenty of information to the developer of an ASP.NET
application. The trace output screen contains the following categories of
information.
Category Description

Control Tree List of all items on the page.
Cookies Collection List of cookies being used.
Form Collection List of controls and their values on the form being posted.
Headers Collection List of items in the Hypertext Transfer Protocol (HTTP)
header.
Request Details Information about the request: session ID, time of request,
type of request, and request status.
Server Variables List of all server variables and their values.
Trace Information Output from standard and custom trace statements.


4 Module 5: Using Trace in Microsoft ASP.NET Pages


u Page-Level Trace
n How Does Page-Level Trace Work?
n Demonstration: Adding Page-Level Trace Statements
n Tracing into a Component

*****************************illegal for non-trainer use******************************
You can use page-level tracing to write debugging statements directly to the
output of a page and to conditionally execute debugging code when tracing is
enabled. The performance data and the developer-specified messages (if any)
are injected into the Hypertext Markup Language (HTML) output stream to the
client to help clarify precisely what occurs when the framework processes a
page request.
In this section, you will learn how the page-level trace mechanism works.

Module 5: Using Trace in Microsoft ASP.NET Pages 5


How Does Page-Level Trace Work?
n Enabling Tracing for a Page
n Sorting Output by Category
n Inserting Trace Messages
n Conditional Execution with Trace.IsEnabled
<%@ Page Language="VB" Trace="true"%>
<%@ Page Language="VB" Trace="true"%>
<%@ Page Language="VB" Trace="true"
TraceMode="SortByCategory"%>
<%@ Page Language="VB" Trace="true"
TraceMode="SortByCategory"%>
Trace.Write("category", "message")
Trace.Write("category", "message")
If Trace.IsEnabled
strTrace = 'create trace string here
End If
Trace.Write(strTrace)
If Trace.IsEnabled
strTrace = 'create trace string here
End If
Trace.Write(strTrace)

*****************************illegal for non -trainer use******************************
The page-level trace mechanism performs two functions when it is enabled:
n It automatically appends a table of performance data to the end of the page.
n It allows developers to insert custom diagnostic messages throughout their
code.

Enabling Tracing for a Page
The trace capability must be enabled prior to use. To enable tracing for a page,
include the following directive at the top of the page code:
<%@Page Language=" VB" Tr ace=" t r ue" %>

The page exposes the Trace property of the type TraceContext, which can be
used to output debugging statements to the page output. The default value of the
Trace attribute is set to False.
Sorting Trace Messages
The TraceContext class contains the TraceMode property that defines how
trace messages are sorted in the page output.
<%@Page Tr ace=" t r ue" Tr aceMode=" Sor t ByCat egor y" %>

TraceMode is of the type TraceModeEnum, and has two possible values:
n SortByTime
Trace messages are output in order of chronological occurrence. This is the
default setting.
n SortByCategory
Trace messages are sorted alphabetically by the category argument to the
Trace.Write and Trace.Warn methods.


6 Module 5: Using Trace in Microsoft ASP.NET Pages


Inserting and Organizing Trace Messages
You can use the Trace object to write debugging statements. You can use two
methods to insert custom messages: Trace.Write and Trace.Warn.
Trace.Write is used to display messages. Trace.Warn is used to display
warnings. Trace.Write and Trace.Warn are easy to distinguish because
Trace.Warn uses a red font color for its output, whereas Trace.Write uses the
default font color.
In their simplest forms, each method takes two string arguments:
Tr ace. Wr i t e( " cat egor y" , " message" )
Tr ace. War n( " cat egor y" , " message" )

The category argument is used to organize messages. For example:
Tr ace. Wr i t e( " Cust omTr ace" , " Begi nni ng User Code. . . " )
Tr ace. War n( " Cust omTr ace" , " Ar r ay count i s nul l ! " )

Conditional Execution with Trace.IsEnabled
Often, you will need to execute additional code to construct the statements to
pass to the Trace.Write or Trace.Warn methods . The code should execute
only if tracing is enabled for the page. To support this, the page exposes a
Boolean property, Trace.IsEnabled, that returns True only if tracing is
enabled for the page. You should first check the Trace.IsEnabled property to
guarantee that your debugging code will execute only when tracing is enabled.
I f Tr ace. I sEnabl ed
st r Tr ace = " cr eat e a t r ace st r i ng her e"
End I f
Tr ace. Wr i t e( st r Tr ace)


Module 5: Using Trace in Microsoft ASP.NET Pages 7


Demonstration: Adding Page-Level Trace Statements

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to use trace at the page level.
To run the demonstration
1. Edit the file add.aspx in the folder <install folder>\Democode\Mod05.
2. Enable tracing by adding the Trace="True" attribute to the @Page
directive.
<%@Page Language=" vb" Tr ace=" Tr ue" %>

3. View the page in Microsoft Internet Explorer.
Trace messages are shown on the page.
4. Add a custom trace message to the Page_Load event.
Tr ace. Wr i t e ( "add Page_Load", "t xt Num1 = " &
Cst r ( t xt Num1. pNum) )

5. View the page again.
6. Disable tracing, and then view the page again.
No trace messages are shown on the page.
7. Add a trace message to the numberbox.ascx user control.
8. Enable tracing in add.aspx, and view the page in Internet Explorer.


8 Module 5: Using Trace in Microsoft ASP.NET Pages


Tracing into a Component
n Import the System.Web Library
n Enable Tracing in Class Constructor
n Add Trace Statements to Method
Imports System.Web
Imports System.Web
HttpContext.Current.Trace.IsEnabled = True
HttpContext.Current.Trace.IsEnabled = True
HttpContext.Current.Trace.Write _
("component", "this is my trace statement")
HttpContext.Current.Trace.Write _
("component", "this is my trace statement")

*****************************illegal for non -trainer use******************************
If you have a component that is called from an ASP.NET page, you can also
add trace statements to the component.
To add trace to a component
1. At the top of the component, import the System.Web library.
I mpor t s Syst em. Web

2. In the constructor of the class to which you want to add trace statements,
enable tracing with the following statement:
Ht t pCont ext . Cur r ent . Tr ace. I sEnabl ed = Tr ue

In the preceding code, HttpContext.Current gets the Context object for
the current request.
3. Next, in the method, use the following:
Ht t pCont ext . Cur r ent . Tr ace. Wr i t e _
( "component ", "t hi s i s my t r ace st at ement ")



Module 5: Using Trace in Microsoft ASP.NET Pages 9


The following table lists some useful information about the results of enabling
trace on a page or component.
Case Result

If you enable trace in the constructor
of the component.
All pages that access the component will have
trace enabled even if the page does not have it
enabled.
If you enable trace in a component
method.
Only the page that accesses the method of the
component will have trace enabled, even if the
page does not have trace enabled.
If you disable trace in the constructor
of the component.
All pages that access the component will have
trace disabled even if the page has trace
enabled.
If you do not explicitly enable or
disable trace for a component, but the
page that calls the component has
trace enabled.
Trace in the component will be enabled for that
specific page.


10 Module 5: Using Trace in Microsoft ASP.NET Pages


u Application-Level Trace
n How Does Application-Level Trace Work?
n Demonstration: Adding Application-Level Trace
Statements

*****************************illegal for non-trainer use******************************
ASP.NET also provides a way to enable tracing for the entire application, rather
than just a single page of the application. An ASP.NET application is the
collection of files and folders in a virtual root of Internet Information Services
(IIS).
In this section, you will learn how an application-level trace works.

Module 5: Using Trace in Microsoft ASP.NET Pages 11


How Does Application-Level Trace Work?
n Application-Level Trace Collects Additional Statistics
from a Request in the trace.axd File
n Enabling Application-Level Trace in web.config
<trace enabled="true"
traceMode="SortByCategory"
requestLimit="40"
pageOutput="true"/>
<trace enabled="true"
traceMode="SortByCategory"
requestLimit="40"
pageOutput="true"/>

*****************************illegal for non-trainer use******************************
In addition to the page-level trace functionality, ASP.NET provides a way to
enable trace output for an entire application. Enabling trace at the application
level has the effect of enabling page- level trace for every page within that
application, provided that there is no page-level directive to explicitly disable
trace. When application- level tracing is enabled, the ASP.NET runtime also
collects several additional statistics, such as the state of the control hierarchy,
the contents of session and application state, the form and query string input
values, and so on. These statistics are collected for a specified number of
requests as determined by the applications configuration file.
Enabling Tracing
With ASP.NET, there is a configuration file that you can use to configure
certain application attributes. This file is named web.config and is located in the
root folder of the application. You will learn more about the web.config file in
Module 7, Creating a Microsoft ASP.NET Web Application, in Course
2063B, Introduction to Microsoft ASP.NET.
The web.config file is in Extensible Markup Language (XML) format; therefore,
all section and attribute names are case-sensitive.
To enable tracing for an application, place the following code in the web.config
file in the applications root folder.
<t r ace enabl ed=" t r ue" / >


12 Module 5: Using Trace in Microsoft ASP.NET Pages


By using the above configuration, each page in the application will output page-
level trace statements to the file trace.axd in the applications root folder, as
shown in the following illustration.

If you want trace messages to be displayed on the individual pages of your
application, set the PageOutput attribute of the trace element to True.
<t r ace enabl ed=" t r ue" pageOut put =" t r ue" / >

The trace section in the configuration file is contained in a <system.web>
section inside the <configuration> section.
<conf i gur at i on>
<syst em. web>
<t r ace enabl ed=" t r ue" / >
</ syst em. web>
</ conf i gur at i on>



Note
Module 5: Using Trace in Microsoft ASP.NET Pages 13


Setting Trace Attributes
The trace section of the configuration file also supports an attribute for
controlling whether trace statements are output to the client browser or are
available only from trace.axd. The attributes supported in the trace
configuration section are listed in the following table.
Value Description

enabled Set to True or False. Indicates whether tracing is enabled for the
application or not. Default is True.
pageOutput Indicates whether trace information should be rendered at the end of
each page, or accessible only through the trace.axd utility. Default is
False (trace information is only accessible through trace.axd).
requestLimit Number of trace requests to store on the server. Default is 10.
traceMode Set to sortByTime or sortByCategory. Indicates the display order
for trace messages. Default is sortByTime.

The following example shows how you can set trace attributes. The following
configuration collects trace information for up to 40 requests and prevents trace
statements from being output to the requesting browser:
<t r ace enabl ed=" t r ue" t r aceMode=" sor t ByCat egor y"
r equest Li mi t =" 40" pageOut put =" f al se" / >


14 Module 5: Using Trace in Microsoft ASP.NET Pages


Demonstration: Adding Application-Level Trace Statements

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to use trace at the application level.
To run the demonstration
1. Copy the web.config file from the folder
<install folder>\DemoCode\Mod05 to the <install folder>, which is the
virtual root of the 2063 Web site.
2. Edit the web.config file and enable application-level tracing by adding the
following line of code to the file:
<t r ace enabl ed=" t r ue" / >

3. View the page http://localhost/2063/DemoCode/Mod05/postback.aspx in
Internet Explorer.
You will not see any trace output in the page.
4. View the page http://localhost/2063/trace.axd in Internet Explorer and look
at the details for the postback.aspx request.

You may need to click Refresh to see the latest entries in the
trace.axd page.

This is where the details are shown. Scroll down to show the values sent to
the form.

Note
Module 5: Using Trace in Microsoft ASP.NET Pages 15


5. Change web.config to display the trace messages on the page by adding the
pageOutput="true" attribute to the trace element.
6. View the page http://localhost//2063/DemoCode/Mod05/postback.aspx in
Internet Explorer again.
Now the trace messages are displayed on the page.
7. When you are done with this demonstration, delete the web.config file in the
root of the 2063 virtual directory so that tracing will be turned off for future
demonstrations.


16 Module 5: Using Trace in Microsoft ASP.NET Pages


Lab 5: Adding Trace to an ASP.NET Page

***************** ************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Enable and disable tracing for an ASP.NET page.
n Add custom trace messages to an ASP.NET page and a middle-tier
component.

Prerequisite
Before working on this lab, you must know how to compile a component.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab05\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab05\Solution.
Estimated time to complete this lab: 30 minutes

Module 5: Using Trace in Mi crosoft ASP.NET Pages 17


Exercise 1
Enabling Tracing
In this exercise, you will enable and disable tracing and add custom messages to
the trace stream.
To enable tracing in a page
1. Open the file ProductsList.aspx in the folder InetPub\wwwRoot\ASPNET.
2. At the beginning of the code, modify the existing @Page directive, add the
trace attribute, and set its value to True, as shown in the following code:
<%@Page Language=" vb" t r ace=" t r ue" %>

3. Save your changes to the ProductsList.aspx page.
4. View the page in Internet Explorer.
You should see the trace information at the bottom of the page.

To add custom trace messages
1. Go to the beginning of the Page_Load event procedure of the
ProductsList.aspx page and add a trace message that displays Beginning of
Page_Load in a category named Product List.
Your code should look like the following:
Tr ace. Wr i t e( " Pr oduct Li st " , " Begi nni ng of Page_Load" )

2. Add another trace message to the end of the Page_Load event procedure
that displays End of Page_Load.
3. Add a third trace message that displays the value of the variable categoryID
after reading it from the QueryString.
4. Save your changes to ProductsList.aspx.

18 Module 5: Using Trace in Microsoft ASP.NET Pages


5. View ProductsList.aspx in Internet Explorer, passing the CategoryID=15:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
You should see your custom messages in the Trace Information section, as
shown in the following illustration.



Module 5: Using Trace in Microsoft ASP.NET Pages 19


Exercise 2
Tracing into a Component
In this exercise, you will add trace statements to the DB2063 component that is
called from the ProductsList.aspx page.
To enable tracing in the DB2063 component
1. Open the file GetProducts.vb in the folder
InetPub\wwwRoot\ASPNET\Components.
2. Import the System.Web library.
Your import statement should look like the following:
I mpor t s Syst em. Web

3. In the GetProducts method, enable tracing by setting the
HttpContext.Current.Trace.IsEnbledproperty to True.
Your code should look like the following:
Ht t pCont ext . Cur r ent . Tr ace. I sEnabl ed = t r ue


You can also put this command in the constructor of the class if you need
to use tracing in the whole component.

To add custom trace messages
1. Go to the beginning of the GetProducts method and add a custom trace
message that displays Beginning of GetProducts in a category named
DB2063.Products Component.
Your additional instruction should look like the following:
Ht t pCont ext . Cur r ent . Tr ace. Wr i t e _
( "DB2063. Pr oduct s Component ", _
" Begi nni ng of Get Pr oduct s" )

2. Add another trace message at the end of the procedure, before the Return
command that displays End of GetProducts.
3. Add a third trace message to the GetProducts method that displays the
value of the categoryID parameter .


Note
20 Module 5: Using Trace in Microsoft ASP.NET Pages


To save and test
1. Save your changes to GetProducts.vb.
2. Compile the component.
a. To compile the component by using an MS-DOS command prompt,
open an MS-DOS command prompt, navigate to the folder
InetPub\wwwroot\ASPNET\components, and run the following
command:
vbc / t : l i br ar y / out : . . \ bi n\ db2063. dl l / r : Syst em. dl l
/ r : Syst em. Web. dl l / r : Syst em. Xml . dl l / r : Syst em. Dat a. dl l
Get Pr oduct s. vb

b. To compile the component by using Visual Studio .NET, click Build on
the Build menu.

If you compile the component by using Visual Studio .NET, you will
need to change the Page_Load event procedure in the ProductsList.aspx
page to instantiate the Products object from the newly built DB2063
component in the ASPNET project.
Di mpr oduct Cat al og As New ASPNET. db2063. Pr oduct s


3. View the ProductsList.aspx page in Internet Explorer, again passing the
categoryID=15:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
You should see your custom messages from the page and from the
component in the Trace Information section, as shown in the following
illustration.



Note
Module 5: Using Trace in Microsoft ASP.NET Pages 21


Review
n Overview of Tracing
n Trace Information
n Page-Level Trace
n Application-Level Trace

*****************************illegal for non-trainer use******************************
1. How do you enable page-level tracing?


2. What is the difference between the Trace.Write and Trace.Warn methods?


3. What property is used to sort trace messages in a page?


4. How do you enable application- level trace?



22 Module 5: Using Trace in Micros oft ASP.NET Pages


5. If you have trace enabled in a component, but disabled in the page that calls
the component, will the trace messages be displayed?


6. If you have trace enabled for a page, but neither enabled nor disabled in a
component called by the page, will the trace messages from the component
be displayed?











Contents
Overview 1
What Is a Web Service? 2
Calling a Web Service from a Browser 12
Calling a Web Service by Using a Proxy 15
Creating a Simple Web Service by Using
Visual Basic 22
Creating and Calling a Web Service by
Using Visual Studio .NET 26
Lab 6: Using Web Services 35
Review 47

Module 6: Using Web
Services


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 6: Using Web Services 1


Overview
n What Is a Web Service?
n Calling a Web Service from a Browser
n Calling a Web Service by Using a Proxy
n Creating a Simple Web Service by Using Visual Basic
n Creating and Calling a Web Service by Using
Visual Studio .NET

*****************************illegal for non-trainer use******************************
The Web has helped to facilitate better communication within and between
companies by providing fast access to information. For many organizations,
however, browsing data-driven pages does not adequately satisfy their business
needs. Programmable Web sites that directly link organizations, applications,
services, and devices with one another would better meet these needs.
Web services provide a simple, flexible, standards-based model for binding
applications together over the Internet, and taking advantage of existing
infrastructure and applications. Web applications can easily be assembled by
using locally developed services and existing services, regardless of which
platforms, development languages, or object models have been used to
implement the constituent services or applications.
After completing this module, you will be able to:
n Explain the goal of Web services and how they fit into the Web architecture.
n Describe the Web services execution model.
n Call a Web service from a browser.
n Call a Web service by using a proxy.
n Use the data returned by a Web service.
n Create a simple Web service by using Microsoft Visual Basic.

2 Module 6: Using Web Services


u What Is a Web Service?
n Features of Web Services
n Web Services Execution Model
n Finding Existing Web Services
n Examples of Existing Web Services
n Demonstration: Calling a Web Service from the Browser

*****************************illegal for non-trainer use**************************** **
Web services provide a simple, flexible, standards-based model for binding
applications together over the Internet and taking advantage of the existing
infrastructure and applications. In this section, you will learn about the need for
Web services and about their architecture. You will also learn about existing
Web services and how to find them.

Module 6: Using Web Services 3


Features of Web Services
n Allow Applications to Communicate Across the Internet
n Language Independent
n Protocol Independent
n Platform Independent
n Stateless Architecture

*****************************illegal for non-train er use******************************
One of todays most pressing challenges for developers is application
integration. Application integration is the process of taking a group of
applications and turning them into easy-to-use Web applications, even if they
run on different operating systems, were created with different programming
languages, and were built with different object models.
Like components, Web services represent black-box functionality that
developers can reuse without worrying about how to implement the service.
Web services provide well-defined interfaces (called contracts) that describe the
services they represent.
Developers can assemble applications by using a combination of remote
services, local services, and custom code. For example, a company might
assemble an online store that uses the Microsoft Passport service to authenticate
users, a third-party personalization service to adapt Web pages to each users
preferences, a credit-card processing service, a sales tax service, package-
tracking services from each shipping company, an in-house catalog service that
connects to the companys internal inventory management applications, and
custom code to individualize the interface and make it unique.
Unlike current component technologies, however, Web services do not use
protocols that are specific to certain object models, such as the Distributed
Component Object Model (DCOM), which requires specific, homogeneous
infrastructures on the computers that run the client and the server. Web services
communicate by using standard Web protocols and data formats, such as
Hypertext Transfer Protocol (HTTP), Extensible Markup Language (XML), and
Simple Object Access Protocol (SOAP). Any system that supports these Web
standards can support Web services.
A Web service can be used internally by a single application, or it can be used
externally by many applications that access it through the Internet. Because it is
accessible through a standard interface, a Web service allows disparate systems
to work together. The Web services model is independent of languages,
platforms, and object models.

4 Module 6: Using Web Services


The Web service model is supported by Microsoft ASP.NET, which is a unified
Web development platform that has grown from Active Server Pages (ASP)
technology. The ASP.NET Web services model assumes a stateless service
architecture. Stateless architectures are generally more scalable than stateful
architectures. Each time a service request is received, a new object is created.
There is a request for the method call, the method call is returned, and then the
object is destroyed. Services can use the ASP.NET State Management services
to maintain a state between requests.

Module 6: Using Web Services 5


Web Services Execution Model

*****************************illegal for non-trainer use******************************
The Web services execution model involves two entities: the client and the
service provider.

The term client is often misinterpreted. In this sense, a client is a Web
browser that views the results of calling a Web service.

The preceding slide illustration shows how Web services are used between a
client and the Web server. Each component has a specific role in the execution
model.
Web Service Model
In the Web service model, the Web service developer:
1. Creates the .asmx file that includes the namespace, classes, properties, and
methods.
2. Declares methods as Web methods that can be accessed over the Internet.

The following is an example of a simple .asmx file :
<%@WebSer vi ce Language=" VB" Cl ass=" Mat hSer vi ce" %>

I mpor t s Syst em. Web. Ser vi ces
I mpor t s Syst em

Cl ass Mat hSer vi ce
<WebMet hod( ) > Publ i c Funct i on Add( i nt 1 As I nt eger , _
i nt 2 As I nt eger ) As I nt eger
r et ur n( i nt 1 + i nt 2)
End Funct i on

End Cl ass


Note
6 Module 6: Using Web Services


Client
In the Web service model, the client:
1. Calls the Web service from the browser to determine which methods are
available.
When you call a Web service from a browser, you access the description
page, which lists the methods that are included in the Web service. The
protocol that is used in this case is HTTP, and the data is returned as XML.
2. Calls a method of the Web service from the browser.
When you call a method of a Web service from a browser, the protocol that
is used is HTTP, and the data is returned as XML.

Web Server
You can also call methods of the Web service by using code on an ASP.NET
page. To call a Web service from an ASP.NET page, the developer must:
1. Find out which Web services are available. This involves finding the
Uniform Resource Locator (URL) for the Web service.
2. Compile the .asmx file (Web service) into a proxy by using the Wsdl.exe
utility. This creates a .vb or .cs file that contains source code for the proxy.
You will learn about proxy files and how to compile an .asmx file into a
proxy in the next section of this module.
3. Compile the proxy (the .vb or .cs file you created in the previous step) into
a .dll file in the /bin directory of the Web site.
4. Open the ASP.NET Web page.
a. Create an instance of the proxy.
b. Call the methods of the Web service.
c. Use the data returned by the Web service.

As the preceding slide illustration shows, the proxy resides on the same
server as the Web page (.aspx) that calls it. An advantage of using a proxy is
that it translates the returned data from the server into a data type that the .aspx
page can use. If you call a Web service method directly from an .aspx page
without using a proxy, you will receive the data in XML form, which must be
parsed in another step.


Note
Module 6: Using Web Services 7


To learn more about the Web services execution model, view the Web Services
Execution Model animation. Open the file 2063B_06A001.swf from the
Media folder.



8 Module 6: Using Web Services


Finding Existing Web Services
n UDDI
l Defines a way to publish and discover information about
Web services
l Relies on a distributed registry of businesses and their
service descriptions implemented in a common XML
format
n Businesses Individually Register Information About the
Web Services by Using UDDI Business Registration
http://www.uddi.org
http://uddi.microsoft.com

*****************************illegal for non -trainer use******************************
Getting information about which business partners have Web services and
finding specific information about the available Web services is very difficult
for companies today. The Universal Description, Discovery and Integration
(UDDI) specification defines a way to publish and discover information about
Web services.
UDDI relies on a distributed registry that has been implemented in a common
XML format. This registry is a list of businesses, along with descriptions of
their available services. The UDDI specification consists of several related
documents and an XML schema that defines a SOAP-based programming
protocol for registering and discovering Web services.
The core component of UDDI is the UDDI business registration, an XML file
that is used to describe a business entity and its Web services. Conceptually, the
information provided in a UDDI business registration consists of three
components: White Pages, which include address, contact, and known
identifiers; Yellow Pages, which include industrial categorizations based on
standard taxonomies; and Green Pages, which include the technical information
about the services that are exposed by the organization. Green Pages include
references to specifications for Web services, as well as any support that may
be required for pointers to file and URL-based discovery mechanisms.
Businesses individually register information about the Web services that they
expose for other businesses to use. This information can be added to the UDDI
business registry through a Web site, or by using tools that use the
programmatic service interfaces described in the UDDI programmers
application programming interface (API) specification. The UDDI business
registry is a logically centralized, physically distributed service with multiple
root nodes that replicate data with each other regularly. When a business
registers with a single instance of the business registry service, the service
shares the data automatically with other UDDI root nodes. After the data has
been distributed, it becomes freely available to anyone who needs to discover
which Web services are exposed by a particular business.

Module 6: Using Web Services 9


For more information about UDDI, go to the UDDI Web site at
http://www.uddi.org/ or the Microsoft UDDI Project Web site at
http://uddi.microsoft.com

10 Module 6: Using Web Services


Examples of Existing Web Services
n Find Web Services at:
l http://www.xmethods.net
l http://www.gotdotnet.com
l http://dotnet.microsoft.com

*****************************illegal for non-trainer use******************************
You can find existing Web services at the following Web sites:
n http://www.xmethods.net
n http://www.gotdotnet.com
n http://dotnet.microsoft.com

Some examples of Web services that can be found at these sites include:
n FedEx Tracker
Provides acc ess to FedEx Tracking information.
n Weather-temperature
Gives the current temperature in a given United States zip code region.
n Barnes and Noble Price Quote
Returns the price of a book at barnesandnoble.com when you provide an
International Standard Book Number (ISBN).


Module 6: Using Web Services 11


Demonstration: Calling a Web Service from the Browser

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to call a Web Service.
To run the demonstration
1. View the description page for the MathService Web service at
http://localhost/2063/Democode/Mod06/mathservice.asmx
2. Click the Add link.
3. Fill in parameters for the Add method, and then click Invoke.
4. Return to the mathservice.asmx page and view the Web Service Description
Language (WSDL) contract.


12 Module 6: Using Web Services


Calling a Web Service from a Browser
http://server/vroot/webservice.asmx
http://server/vroot/webservice.asmx

*****************************illegal for non -trainer use******************************
Because Web Services are accessible by using URLs, HTTP, and XML,
programs running on any platform and in any language can access them.
If you know the base URL for a Web service (the URL to the .asmx file that is
the base of the Web service), you can use this URL to access a Web page
known as the HTML description page. The HTML description page provides
information about what a Web service does, the methods it contains and their
parameters, and its response type. In addition, you can use the description page
to test the functionality of the Web service.

Module 6: Using Web Services 13


For example, suppose that you access a Web service called hotel_Full.asmx that
is used to retrieve details from a hotel. You know the base URL for this service
is http://localhost/ASPNET/hotel_full.asmx. Entering the base URL with no
extensions or parameters produces a page that displays information about the
service and the methods it contains.

In addition to viewing information about the Web service in the browser, you
can obtain a more formal definition of the Web service by viewing its Web
Service Description Language (WSDL) contract. A Service Description link at
the top of the description page allows you to view the contract, which contains
an XML description of the Web service and its contents. You can use this file to
generate a proxy manually.
WSDL Contract
The WSDL contract is an XML document. The document defines the format of
messages that the Web service understands. The service description acts as an
agreement that defines the behavior of a Web service and instructs potential
clients in how to interact with it.
In addition to message format definitions and messaging patterns, the service
description also contains the address that is associated with each Web service
entry point. The format of this address depends on the protocol that is used to
access the service, such as a URL for HTTP or an e-mail address for Simple
Mail Transfer Protocol (SMTP).

14 Module 6: Using Web Services


Calling a Web Service from a Browser (continued)
n Pass the Name of the Method and All Required
Parameters to the URL of the Web Service
n Return Value Is in XML Format
http://server/vroot/webservice.asmx/method?param=value
http://server/vroot/webservice.asmx/method?param=value

*****************************illegal for non-trainer use******************************
You can also call the methods of a Web service directly from a browser.
To call a Web service method, pass the name of the method, the required
parameters, and the values of the parameters to the URL of the Web service.
The Web service returns data in XML format when it is called from a Web
browser by using HTTP.
For example, if a Web service named hotel_full has a method named Price that
takes one parameter named strRoomType1, you can call it directly from the
browser by viewing the following URL:
http://localhost/conference/hotel_full.asmx/Price?strRoomType1=single
The following XML is data that was returned from this URL:
<?xml ver si on="1. 0"?>
<doubl e xml ns=" ht t p: / / t empur i . or g/ " >200</ doubl e>

If you want to use this kind of data in your Web application, you must parse it
in a separate step.

Module 6: Using Web Services 15


u Calling a Web Service by Using a Proxy
n Compiling an .asmx File into a Proxy
n Compiling the Proxy into a DLL
n Calling Web Service Methods
n Demonstration: Calling a Web Service by Using a Proxy

*****************************illegal for non-trainer use******************************
Another method for calling a Web service is by using a proxy. In this section
you will learn how to call a Web service by using a proxy.

You will first learn how to create a Web service manually, and then learn
how to create it by using Microsoft Visual Studio .NET.


Note
16 Module 6: Using Web Services


Compiling an .asmx File into a Proxy
n A Proxy Class:
l Looks like the original class but does not contain any
application logic
l Allows a client to access a Web service as if it were a
local COM object
n Creating a Proxy Class from an .asmx File
wsdl /l:vb /n:myNameSpace
http://location/service.asmx?wsdl
wsdl /l:vb /n:myNameSpace
http://location/service.asmx?wsdl

*****************************illegal for non-trainer use******************************
A proxy class is code that looks exactly like the class it is meant to represent,
but does not contain any of the application logic. Instead, it contains marshaling
and transport logic. The Proxy object allows a client to access a Web service as
if it were a local Component Object Model (COM) object, which lets any
COM-enabled language access the Web servic e easily. You can create a proxy
class from an SDL file.
The Microsoft .NET Framework software development kit (SDK) includes a
tool called Wsdl.exe that you can use to create a proxy class.
wsdl [ opt i ons] {URL | pat h}

In the preceding syntax, URL is the Uniform Resource Location (URL) to a
WSDL contract file (.wsdl), XSD schema file (.xsd), or a discovery document
(.disco). Path is the path to a local WSDL contract, XSD schema, or discovery
document (including .discomap files).

Syntax
Module 6: Using Web Services 17


The following table provides a detailed description of the options that are used
with the Wsdl.exe command.
Option Description

/urlkey Specifies the configuration key to use to read the default value for
the URL property when generating code. Also called
/appsettingurlkey.
/baseurl Specifies the base URL to use when calculating the URL fragment.
You must use the /urlkey option with this option. Also called
/appsettingbaseutl.
/d[omain] Specifies the domain name to use when connecting to a server that
requires authentication.
/l[anguage] The language that is used for the generated proxy: CS (Microsoft
Visual C#

; default), VB (Microsoft Visual Basic), or JS (Microsoft


JScript .NET).
/n[amespace] The namespace of the generated proxy. Default value is the global
namespace.
/nologo Suppresses the Microsoft startup banner display.
/o[ut] The location in which to create the proxy file and the filename for
the file. The default location is the current directory; the default
filename is based on the Web Service name.
/p[assword] Specifies the password to use if connecting to a server that requires
authentication.
/protocol The protocol that is used to generate the proxy: SOAP, HttpGet,
HttpPost, or a custom protocol as specified in the configuration file.
Default value is SOAP.
/proxy: The URL of the proxy server that is used to establish a connection.
Default uses the system proxy settings. Associated with this are
three other options:
n /pd (or /proxydomain) which sets the domain in which the proxy
server resides,
n /pp (or /proxypassword) which sets the password required by the
proxy server,
and
n /pu (or /proxyusrename) which sets the username required to
connect to the proxy server.
/server Generates an abstract class for a Web service that is based on the
contract. Default generates a client proxy class.
/u[sername] Specifies the username to use when connecting to a server that
requires authentication.
/? Displays command syntax and options for the Wsdl.exe tool.

Wsdl.exe generates a single source file as output. This file contains a proxy
class that has been defined by using the specified language and the methods that
are exposed by the Web service. Each proxy method contains the appropriate
network invocation and marshalling code that is necessary to invoke and
receive a response from the remote Web service.

18 Module 6: Using Web Services


For example, to compile a store Web service file named Store.asmx into a
proxy, you could type the following code:
wsdl / l : vb / n: mySt or e
ht t p: / / l ocal host / St or e/ St or e. asmx?wsdl

Here, myStore is the namespace of the Web service.
This code creates a proxy class in a file named Store.vb that contains methods
that are exposed by the Web service.

Module 6: Using Web Services 19


Compiling the Proxy into a DLL
n Compiling a Proxy Class into a DLL
n The . dll File Is Published in the /bin Folder
vbc /out:..\bin\proxyclassname.dll
/t:library
/r:System.Web.Services.dll proxyclassname.vb
vbc /out:..\bin\proxyclassname.dll
/t:library
/r:System.Web.Services.dll proxyclassname.vb

*****************************illegal for non-trainer use******************************
After you create a proxy class, you need to compile it into a dynamic -link
library (DLL). You can use the following syntax to compile a Visual Basic
proxy class into a DLL:
vbc / out : . . \ bi n\ pr oxycl assname. dl l / t : l i br ar y
/ r : Syst em. Web. Ser vi ces. dl l pr oxycl assname. vb

In the preceding codes syntax, you use the /t switch to specify the target output
type of the compiled resource. You use the value library to create a stand-alone
file that contains the class and the metadata for a given class or classes. You use
the /r swit ch to reference an assembly that contains the metadata and classes
that you need within the class instance.
If you want to compile the Store.vb class into a DLL, you could use the
following code:
vbc / out : . . \ bi n\ St or e. dl l / t : l i br ar y
/ r : Syst em. Web. Ser vi ces. dl l st or e. vb

Note that in the preceding codes syntax, the output is stored in the /bin folder.
To use the proxy DLL, you need to publish the DLL in the /bin folder. The /bin
folder resides in the root of the Web virtual site, or in the root in Internet
Information Services (IIS).

Example
20 Module 6: Using Web Services


Calling Web Service Methods
n Creating an Instance of the Proxy
n Calling Methods
Dim myStoreProxy As myStore.Store
myStoreProxy = New myStore.Store()
Dim myStoreProxy As myStore.Store
myStoreProxy = New myStore.Store()
Dim ds As DataSet
ds = myStoreProxy.products()
Dim ds As DataSet
ds = myStoreProxy.products()

*****************************illegal for non-trainer use******************************
Create an Instance
To use a proxy in an .aspx page, you need to create an instance of the proxy in
your page. For example, to use the Store proxy, you create an instance of it by
writing the following code:
Di mmySt or ePr oxy As mySt or e. St or e
mySt or ePr oxy = New mySt or e. St or e( )

In the preceding code, myStore is the namespace of the proxy class, and Store
is the actual proxy class.
Call a Method
You can call the methods of a Web service from an .aspx page directly by using
the proxy, and you can then access the data that the Web service returns.
For example, if the Store class has a Web-callable method named products
that returns a DataSet of all the products sold by the store, you could call the
method by using the following code:
Di mds As Dat aSet
ds = mySt or ePr oxy. pr oduct s( )


Module 6: Using Web Services 21


Demonstration: Calling a Web Service by Using a Proxy

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create and use a proxy to call a Web
service.
To run the demonstration
1. Create a bin directory in the folder <install folder>.
This is the virtual root directory of the 2063 Web site.
2. Build the proxy DLL for the MathService Web service by running
<install folder>\Democode\Mod06\mkService.bat.
This batch file creates a proxy DLL named mathserver.dll and moves it to
the \bin directory.
3. Open the file <install folder>\Democode\Mod06\math.aspx to show how to
call the Web service from code.
4. View math.aspx in Microsoft Internet Explorer.
5. Enter numbers in the two text boxes, and then click =.


22 Module 6: Using Web Services


u Creating a Simple Web Service by Using Visual Basic
n Writing a Web Service
n Demonstration: Creating a Web Service

*****************************illegal for non -trainer use******************************
The biggest advantage of Web services is that they can be created easily. In this
section, you will learn how to create a Web service and expose methods.

Module 6: Using Web Services 23


Writing a Web Service
n Adding a Page Directive
n Importing the Namespaces
<%@ WebService Language="VB" Class= "MyStore" %>
<%@ WebService Language="VB" Class= "MyStore" %>
Imports System
Imports System.Web.Services
Imports System
Imports System.Web.Services

*****************************illegal for non-trainer use******************************
Writing a simple Web service takes only a few minutes, and can be
accomplished in any text editor.
As an example, consider a Web service called MyStore. MyStore exposes a
method for getting the price for all the products in the store.
Adding the Page Directive
At the top of the .asmx file is a directive that identifies the file as a Web service
and specifies the language for the service.
<%@WebSer vi ce Language=" VB" Cl ass=" MySt or e" %>

Importing the Namespaces
Next, import the System and the System.Web.Services namespaces. The
WebMethod() attribute resides in the System.Web.Services namespace. You
can use the WebMethod() attribute to call a method from the Web.
I mpor t s Syst em
I mpor t s Syst em. Web. Ser vi ces


24 Module 6: Using Web Services


Writing a Web Service (continued)
n Defining a Class with WebMethods
n Save the File with an .asmx Extension
Public Class MyStore
<WebMethod()> Public Function _
Price() As String
Price = "The item costs $10."
End Function
End Class
Public Class MyStore
<WebMethod()> Public Function _
Price() As String
Price = "The item costs $10."
End Function
End Class

*****************************illegalf or non-trainer use******************************
Defining a Class File
In the same .asmx file, you must also define a class that encapsulates the
functionality of the Web service. This class should be public, and inherit from
the WebService base class. Each method that will be exposed from the service
needs to flagged with a <WebMethod()> custom attribute in front of it. This
attribute is required to create a Web-callable method. If the method does not
have the <WebMethod()> custom attribute, the method will not be exposed
from the service. The following code has the MyStore class and the Price
method:
Publ i c Cl ass MySt or e
<WebMet hod( ) > Publ i c Funct i on Pr i ce( ) As St r i ng
Pr i ce = "The i t emcost s $10. "
End Funct i on
End Cl ass

Saving a Web Service
Web Service files are saved with an .asmx file extension. The ASP.NET
runtime automatically compiles files that have an .asmx extension when a
request to the service is made.

Module 6: Using Web Services 25


Demonstration: Creating a Web Service

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create a simple Web service that
subtracts two numbers.
To run the demonstration
1. Edit the file <install folder>\Democode\Mod06\MathService.asmx.
2. Create a Subtract method that subtracts one number from another.
3. View the page http://localhost/2063/Democode/Mod06/mathservice.asmx
4. Fill in parameters for the Subtract method, and then click Invoke.
5. If you want to call this new method service from an ASP.NET page, you
can use the mkservice.bat file to compile it. Then call the Subtract method
in the math.aspx page.


26 Module 6: Using Web Services


u Creating and Calling a Web Service by Using
Visual Studio .NET
n Creating a Web Service by Using Visual Studio .NET
n Demonstration: Creating a Web Service by Using
Visual Studio .NET
n Calling a Web Service by Using Visual Studio .NET
n Demonstration: Calling a Web Service by Using
Visual Studio .NET

*****************************illegal for non-trainer use******************************
Visual Studio .NET makes creating and calling Web services easy.
In Visual Studio .NET, you can easily expos e any function, in any language, as
a Web service. You do not need to learn XML and SOAP to take advantage of
Web services. When you compile your business objects, Visual Studio .NET
automatically generates an XML file that describes the function and, when it is
called, the function will automatically send and receive XML packets.
After you build the Web service, both the compiled code and the XML file that
describes the public methods of the service are published to the Web server.
The Web service can then be invoked through HTTP, and XML will
automatically be used to pass data to and from the service.
In Visual Studio .NET, you can drag any exposed Web service directly into
your application. Doing so enables Visual Studio .NET to treat the Web service
as a class. Calling the Web service is as simple as creating a new instance of the
Web Service class and then calling an exposed method.
In this section, you will learn how to create and call Web services by using
Visual Studio .NET.

Module 6: Using Web Services 27


Creating a Web Service by Using Visual Studio .NET
n Creating a Web Service:
1. Create a new project in Visual Studio .NET
2. Select the ASP.NET Web Service option and specify
the name of the Web service
3. Open the Web service in the code view and declare its
Web-callable functions
4. Compile the Web service by using the Build option

*****************************illegal for non-trainer use******************************
When you use Visual Studio .NET to create a Web service, you do not need to
add several lines of code that you need to add when using Microsoft Notepad or
another text editor.
You can simply declare the Web-callable functions of the Web service.
Visual Studio .NET automatically creates the code for adding pages directives,
importing namespaces, and declaring the class structure when you create a new
project for the Web service.
To learn how to create a Web service by using Visual Studio .NET, consider a
simple Web service called Stocks.

28 Module 6: Using Web Services


To create a Web service in Visual Basic
1. Create a new project in Visual Studio .NET.
2. Select the ASP.NET Web Service option, type a name for the Web service,
and then click OK.

By default, Visual Studio .NET creates a Web service file named
Service1.asmx.

You can change the default name of the Web service file
(Service1.asmx) and the default name of the class (Service1).


Note
Module 6: Using Web Services 29


3. Open the .asmx file in code view, and then declare its Web-callable
functions. For example, the following illustration shows a GetRating
method.


4. Compile the Web service by clicking Build on the Build menu.

Visual Studio .NET compiles the Web service code and deploys it as a DLL to
the \bin directory of the Web site.

30 Module 6: Using Web Services


Demonstration: Creating a Web Service by Using Visual
Studio .NET

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to create a simple stock rating service.
The rating service returns a Buy value if the ticker symbol ACME is entered.
To run this demonstration
1. Create a new project in Visual Studio .NET.
It is important to create a new project for the ASP.NET Web service.
2. Select the ASP.NET Web Service option, and then specify the name of the
Web service as Stocks.
A Stocks folder is created in the folder \Inetpub\wwwroot.
3. Open the default .asmx file, Service1.asmx, in code view by right-clicking
the file in the Solution Explorer and clicking View Code.
The default name of the class is Service1 (the code is in the file
Sevice1.asmx.vb).
4. Create a GetRating function as follows:
<WebMet hod( ) > Publ i c Funct i on Get Rat i ng( Ti cker As St r i ng) _
As St r i ng
I f Ti cker ="ACME" Then
Ret ur n "Buy"
El se
Ret ur n " Sel l "
End I f
End Funct i on

5. Save the file.
6. On the Build menu, click Build to compile the Web service.
7. Open the Web service in Internet Explorer by viewing
http://localhost/Stocks/Service1.asmx


Module 6: Using Web Services 31


Calling a Web Service by Using Visual Studio .NET
n Calling a Web Service:
1. Open a Web Application project
2. Create a Web reference for the Web service by using
the Add Web Reference dialog box
3. Create an instance of the Web service
4. Call the functions of the Web service
5. Build the Web application project

*****************************illegal for non-trainer use******************************
To use a Web service from Visual Studio .NET, you can simply add a Web
reference to it. After browsing to the Web service URL, you can reference the
service from your project. Because the WSDL for the Web service contains
both the URL of the Web service and all of the functions that are available,
Visual Studio .NET can automatically create the code that calls the service from
your page.

32 Module 6: Using Web Services


To call a Web service by using Visual Studio .NET
1. Open a Web Application project in Visual Studio .NET.
2. On the Project menu, click Add Web Reference.
3. In the Address field of the Add Web Reference dialog box, type the URL
of the Web service that you are accessing, press ENTER, and then click
Add Reference .

Visual Studio .NET creates a Web reference to the Web service with the
name of the server hosting the Web service, as shown in the following
illustration.


Module 6: Using Web Services 33


4. In a function in an ASPX page, create an instance of the Web service, and
then call its functions.
For example, if you have a button to call the GetRating() method of the
Stocks Web service, use the following code in the Click event procedure:
Sub But t on1_Cl i ck( s As Obj ect , e As Event Ar gs)
Di mser vi ce As New Get St ocks. l ocal host . ser vi ce1( )
l bl Resul t s. Text = ser vi ce. Get Rat i ng( "ACME")
End Sub

When you use Web services in a Visual Studio .NET project, the
proxy is built for you and added to the assembly for the project. Therefore,
to reference a Web service, you must use the name of the project, the name
of the Web reference, and then the name of the WSDL file created by
Visual Studio .NET.

5. Compile the Web application by clicking Build on the Build menu.


Note
34 Module 6: Using Web Services


Demonstration: Calling a Web Service by Using Visual Studio .NET

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to call a Web service called Stocks by
using Visual Studio .NET.
To run the demonstration
1. Create a new ASP.NET Web Application project in Visual Studio .NET
called GetStocks.
2. Add a Web reference to the Web service that you created in the previous
demonstration. It should be located at http://localhost/Stocks/service1.asmx
3. Open the default Webform1.aspx page in design view and add a text box, a
button, and a label using the Web Forms section of the Toolbox. Use the
default properties for each.
4. Create a Click event procedure for the button.
Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on1. Cl i ck
Di mser vi ce As New Get St ocks. l ocal host . ser vi ce1( )
Label 1. Text = ser vi ce. Get Rat i ng( Text Box1. Text )
End Sub

5. Build the Web application by clicking Build on the Build menu.
6. View the .aspx page in Internet Explorer.
7. Test the Web service by entering the ACME stock symbol in the text box
and clicking the button.


Module 6: Using Web Services 35


Lab 6: Using Web Services

*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Call a Web service from an ASP.NET page.
n Create a Web service by using Visual Basic.

Prerequisites
Before working on this lab, you must know:
n How to create an event procedure for a server control.
n How to create a class in Visual Basic .

Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab06\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab06\Solution.

36 Module 6: Using Web Services


Scenario
After selecting a track for the ASP.NET conference, the user can reserve a room
in a hotel for the duration of the conference. From the CheckOut.aspx page, it is
possible to select one of two hotels at which to stay. Selecting a hotel calls the
hotel_reservation.aspx page.
There are two hotels that have contracted with the conference. For the purposes
of this lab, one hotel will always be full; the other will always have rooms
available.
In Exercise 1, you will add code to the hotel_reservation.aspx page to call an
existing Web service to get information about the Full hotel.
In Exercise 2, you will create a Web service for a third hotel by using
Visual Basic.
In Exercise 3, you will add code to the hotel_reservation.aspx page to get
information about the second hotel, hotel_Empty.
Estimated time to complete this lab: 60 minutes

Module 6: Using Web Services 37


Exercise 1
Using a Web Service
In this exercise, you will call a Web service for a hotel named Full. If time
permits, in Exercise 3, you will call another Web service for a hotel named
Empty, and then retrieve information regarding room availability.
The Web service for the Full hotel is named Hotel_Full.dll. The Web service
for the Empty hotel is named Hotel_Empty.dll. There are five methods in each
service.
n Reserve takes room types and start and end dates and returns a Boolean
value that indicates whether a room is available.
<WebMet hod( ) >publ i c Funct i on Reser ve (
st r RoomType1 As St r i ng, st r RoomType2 As St r i ng,
dt mSt ar t Dat e As Dat e, dt mEndDat e As Dat e) As Bool ean

n Price returns a double value that is the price of the hotel for one night.
<WebMet hod( ) >publ i c Funct i on Pr i ce(
st r RoomType1 As St r i ng) As Doubl e

n Description returns a string that describes the hotel.
<WebMet hod( ) >publ i c Funct i on Descr i pt i on( ) As St r i ng

n Room returns a string that describes the rooms of the hotel.
<WebMet hod( ) >publ i c Funct i on Room( ) As St r i ng

n Food returns a string that describes the food available at the hotel.
<WebMet hod( ) >publ i c Funct i on Food( ) As St r i ng


To call the Full hotel Web service
1. Open the hotel_reservation.aspx file.
2. Add three label Web controls to the page with the following IDs:
lblDescription, lblRoom, and lblFood. Place them before the drop-down
list (just before the line: <b> Select a Room Type: </b><br>).
3. If you are using Visual Studio .NET, add a reference to the Full hotel Web
service:
a. Right-click ASPNET in the Solution Explorer, and then click Add Web
Reference.
b. In the Add Web Reference dialog box, type
http://localhost/ASPNET/Hotel_Full.asmx in the Address field, press
ENTER, and then click Add Reference.

38 Module 6: Using Web Services


4. Create a Page_Load event procedure.
a. If you are using Visual Studio .NET, create a proxy variable for the Full
hotel named hotel_FullProxy of type ASPNET. localhost.hotel_Full
and then create an instance of the proxy object.
Your code should look like the following:
Di mhot el _Ful l Pr oxy As ASPNET. l ocal host . hot el _Ful l
hot el _Ful l Pr oxy = New ASPNET. l ocal host . hot el _Ful l ( )

b. If you are using Microsoft Notepad, create a proxy variable for the Full
hotel named hotel_FullProxy of type myHotel_Full.hotel_Full and
then create an instance of the proxy object.

The proxy has already been created and compiled into the
hotel_Full.dll DLL and placed in the \bin directory. The namespace for the
Web service is myHotel_Full.

Your code should look like the following:
Di mhot el _Ful l Pr oxy As myHot el _Ful l . hot el _Ful l
hot el _Ful l Pr oxy = New myHot el _Ful l . hot el _Ful l ( )

c. Call the Description, Room, and Food methods of the Full hotels Web
service to read information about the hotel. Display the returned
information in the corresponding label controls, as shown in the
following table.
Label Method

lblDescription Description
lblRoom Room
lblFood Food

Your code should look like the following:
l bl Descr i pt i on. Text = hot el _Ful l Pr oxy. Descr i pt i on( )
l bl Room. Text = hot el _Ful l Pr oxy. Room( )
l bl Food. Text = hot el _Ful l Pr oxy. Food( )



Note
Module 6: Using Web Services 39


To save and test your work
1. Save your changes to the file hotel_reservation.aspx.
2. If you are using Visual Studio .NET, build the project by clicking Build on
the Build menu.
3. Using Internet Explorer, go to the hotel reservation page of the ASPNET
Web site by viewing http://localhost/ASPNET/hotel_reservation.aspx.
4. You should see information displayed about the hotel, as shown in the
following illustration.



40 Module 6: Using Web Services


Exercise 2
Creating a Web Service
In this exercise, you will create a Web service for another hotel, hotel_New.
To create the framework of the Web service
1. If you are using Notepad, create a new .asmx file named hotel_New.asmx,
and then add the @WebService directive, the Imports statements, and the
Class definition.
Your code should look like the following:
<%@WebSer vi ce Language=" VB" Cl ass=" hot el _New" %>

I mpor t s Syst em. Web. Ser vi ces
I mpor t s Syst em

Cl ass hot el _New

End Cl ass

2. If you are using Visual Studio .NET, create a new Web service project
named hotel_New.

Visual Studio .NET creates an .asmx file named Service1.asmx with
a class named Service1. Change the name of the Service1.asmx file to
hotel_new.asmx, and then change the name of the Class to hotel_New.

3. Copy the five methods from the hotel_Empty.asmx Web service into the
hotel_New Web service.

To customize the WebMethods
In the hotel_New.asmx page, modify the Price, Description, Room, and
Food methods to return new values.

To save and test your work
1. Save your changes to hotel_New.asmx.
2. If you are using Visual Studio .NET, build the project by clicking Build on
the Build menu.
3. If you are using Microsoft Notepad, open an MS-DOS command prompt.
a. Navigate to the folder InetPub\wwwroot\ASPNET.
b. Run the following commands:
wsdl / l : vb / n: myHot el _New
ht t p: / / l ocal host / ASPNET/ hot el _New. asmx? wsdl

vbc / out : . \ bi n\ hot el _New. dl l / t : l i br ar y / r : Syst em. dl l
/ r : Syst em. Xml . dl l / r : Syst em. Web. Ser vi ces. dl l
hot el _New. vb


Note
Module 6: Using Web Services 41


4. Using Internet Explorer, go to the description page of the Web Service.
The Web service is located at http://localhost/ASPNET/hotel_New.asmx if
you are using Microsoft Notepad.
The Web service is located at http://localhost/hotel_New/hotel_New.asmx if
you are using Visual Studio .NET.
5. Test the Price, Description, Room, and Food methods.

To call hotel_New from hotel_reservation.aspx
In the hotel_reservation.aspx page, call the hotel_New Web service instead
of the hotel_Full Web service.

Refer to Exercise 1 of this lab for detailed instructions on how to call
a Web service from the hotel_reservation.aspx page.



Note
42 Module 6: Using Web Services


Exercise 3 (If Time Permits)
Calling Another Web Service
In Exercise 1, you called a Web service named Hotel_Full. In this exercise, you
will call another Web service named Hotel_Empty, and then retrieve
information regarding room availability.
To call another Web service
The user selects a hotel on the Checkout.aspx page and that hotel is passed to
the hotel_reservation.aspx page in the HotelID variable. The values are 1 for
the Full hotel, and 2 for the Empty hotel.
1. At the beginning of the Page_Load event procedure in
hotel_reservation.aspx, read the value of the HotelID variable using the
request.Params function. Store the value in an integer variable named
intHotelID.
Your code should look like the following:
Di mi nt Hot el I D As I nt eger
i nt Hot el I D = CI nt ( Request . Par ams( " Hot el I D" ) )

2. Initialize the text in label lblReservationConfirmation with an empty
string.

Module 6: Using Web Services 43


3. Test the value of the variable intHotelID.
a. If the value is 1, move the code to a proxy for the Full hotel, and call
methods from that Web service to this location.
b. If the value is 2, create a new proxy for the Empty hotel, and call
methods from this Web service.
The Page_Load event should look like the following:
Di mi nt Hot el I D As I nt eger
i nt Hot el I D = CI nt ( Request . Par ams( " Hot el I D" ) )

' I ni t i al i ze t he r eser vat i on conf i r mat i on message
l bl Reser vat i onConf i r mat i on. Text = " "

' Whi ch hot el i s i t ?
Sel ect Case i nt Hot el I D
Case 1
' Cr eat e a pr oxy f or t he Ful l hot el
Di mhot el _Ful l Pr oxy As myHot el _Ful l . hot el _Ful l
hot el _Ful l Pr oxy = New myHot el _Ful l . hot el _Ful l ( )
' Get t he gener al , r oomand f ood descr i pt i ons
l bl Descr i pti on. Text = hot el _Ful l Pr oxy. Descr i pt i on( )
l bl Room. Text = hot el _Ful l Pr oxy. Room( )
l bl Food. Text = hot el _Ful l Pr oxy. Food( )
Case 2
' cr eat e a pr oxy f or t he Empt y hot el
Di mhot el _Empt yPr oxy As myHot el _Empt y. hot el _Empt y
hot el _Empt yPr oxy = New myHot el _Empt y. hot el _Empt y( )
' Get t he gener al , r oomand f ood descr i pt i ons
l bl Descr i pt i on. Text = hot el _Empt yPr oxy. Descr i pt i on( )
l bl Room. Text = hot el _Empt yPr oxy. Room( )
l bl Food. Text = hot el _Empt yPr oxy. Food( )
End Sel ect


To save and test your work
1. Save your changes to the file hotel_reservation.aspx.
2. Using Internet Explorer, go to Checkout.aspx page in the ASPNET Web site,
http://localhost/ASPNET/Checkout.aspx
3. Click Hotel Full.
You should see the descriptions from the Full hotel.
4. Return to the Checkout page, and then click Hotel Empty.
You should see the descriptions from the Empty hotel.


44 Module 6: Using Web Services



To get the availability of the room
On the hotel_reservation.aspx page, when the user clicks Submit, call the
Reserve method of the hotel Web service and, if there is an available room, call
the Price method to determine the price of the room.
1. Inside the Submit buttons click event procedure (cmdSubmit_Click), after
the test for the calendar dates, add code to retrieve the HotelIDvariable
from the query string.
2. Test the type of hotel. Again, the values are 1 for the Full hotel, and 2 for
the Empty hotel.
3. For each of the two cases, create a proxy for the corresponding Web service
and call the Reserve method.
The Reserve method requires the following parameters:
Parameter Data Type Description

strRoomType1 String Indicates if the room should be single or double.
strRoomType2 String Indicates if the room should be smoking or non-
smoking.
dtmStartDate Date The starting date.
dtmEndDate Date The ending date.

Module 6: Using Web Services 45


4. Display a message in the lblReservationConfirmation label indicating the
availability of a room.
If there is an available room, include in the message the type of room that
was selected, the dates requested, and the price.
The code that you have added should look like the following:
Di mi nt Hot el I D As I nt eger
Di mbl nRoomFr ee As Bool ean = Fal se
Di mdbl Pr i ce As Doubl e = 0. 00

' Obt ai n Hot el I D f r omQuer ySt r i ng
i nt Hot el I D = CI nt ( Request . Par ams( " Hot el I D" ) )

' Ask t he hot el ser vi ce i f t her e i s an avai l abl e r oom
Sel ect Case i nt Hot el I D
Case 1
' Cr eat e a pr oxy f or t he Ful l hot el
Di mhot el _Ful l Pr oxy As myHot el _Ful l . hot el _Ful l
hot el _Ful l Pr oxy = new myHot el _Ful l . hot el _Ful l ( )
' Get t he avai l abi l i t y of t he sel ect ed t ype of r oom
' f or t he speci f i ed dat es
bl nRoomFr ee = hot el _Ful l Pr oxy. Reser ve _
( l st RoomType1. Sel ect edI t em. Text , _
l st RoomType2. Sel ect edI t em. Text , _
cal St ar t i ngDat e. Sel ect edDat e, _
cal Endi ngDat e. Sel ect edDat e)
' Get t he pr i ce
dbl Pr i ce = hot el _Ful l Pr oxy. Pr i ce _
( l st RoomType1. Sel ect edI t em. Text )
Case 2
' Cr eat e a pr oxy f or t he Empt y hot el
Di mhot el _Empt yPr oxy As myHot el _Empt y. hot el _Empt y
hot el _Empt yPr oxy = new myHot el _Empt y. hot el _Empt y( )
' Get t he avai l abi l i t y of t he sel ect ed t ype of r oom
' f or t he speci f i ed dat es
bl nRoomFr ee = hot el _Empt yPr oxy. Reser ve _
( l st RoomType1. Sel ect edI t em. Text , _
l st RoomType2. Sel ect edI t em. Text , _
cal St ar t i ngDat e. Sel ect edDat e, _
cal Endi ngDat e. Sel ect edDat e)
' Get t he pr i ce
dbl Pr i ce = hot el _Empt yPr oxy. Pr i ce _
( l st RoomType1. Sel ect edI t em. Text )
End Sel ect

' code cont i nued on next page

46 Module 6: Using Web Servi ces


' code cont i nued f r ompr evi ous page

' Bui l d t he conf i r mat i on message
I f bl nRoomFr ee Then
l bl Reser vat i onConf i r mat i on. Text = _
"Roomavai l abl e. " & _
" <br ><br > Your sel ect i on was: <br >" & _
l st RoomType1. Sel ect edI t em. Text & ", " & _
l st RoomType2. Sel ect edI t em. Text & " <br >" & _
" f r om" & _
cal St ar t i ngDat e. Sel ect edDat e. ToShor t Dat eSt r i ng( ) _
& " t o " & _
cal Endi ngDat e. Sel ect edDat e. ToShor t Dat eSt r i ng( ) _
& "<br ><br >" & "The pr i ce wi l l be: " & _
Syst em. St r i ng. For mat ( " {0: c}" , dbl Pr i ce)
El se
l bl Reser vat i onConf i r mat i on. Text = _
" No r oomavai l abl e. "
End I f


To save and test your work
1. Save your changes to the file hotel_reservation.aspx.
2. Using Internet Explorer, go to the Checkout.aspx page in the ASPNET Web
site, http://localhost/ASPNET/Checkout.aspx
3. Click Hotel Full.
4. Select a room type and starting and ending dates, and then click Reserve .
You should see a message stating that there is no room available.
5. Return to the Checkout.aspx page and click Hotel Empty.
6. Select a room type and starting and ending dates, and then click Reserve .
You should see a message stating that a room is available and its price
should be displayed.


Module 6: Using Web Services 47


Review
n What Is a Web Service?
n Calling a Web Service from a Browser
n Calling a Web Service by Using a Proxy
n Creating a Simple Web Service by Using Visual Basic
n Creating and Calling a Web Service by Using
Visual Studio .NET

*****************************illegal for non-trainer use******************************
1. What is the main purpose of Web services?


2. How do you find an existing Web service?


3. What are the different methods of calling a Web service?


4. What is the WSDL contract for a Web service?



48 Module 6: Using Web Services


5. How do you create methods for a Web service?


6. How do you call methods of a Web service?











Contents
Overview 1
Requirements of a Web Application 2
What Is New in ASP.NET? 3
Sharing Information Between Pages 13
Securing an ASP.NET Application 24
Lab 7: Creating an ASP.NET Web
Application 38
Review 50

Module 7: Creating a
Microsoft ASP.NET
Web Application


Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.



Module 7: Creating a Microsoft ASP.NET Web Application 1


Overview
n Requirements of a Web Application
n What Is New in ASP.NET?
n Sharing Information Between Pages
n Securing an ASP.NET Application

*****************************illegal for non-trainer use******************************
Just as in Active Server Pages (ASP), Microsoft ASP.NET supports the
concept of a Web application with applic ation-specific settings and services. An
ASP.NET application is defined as all the files, pages, handlers, modules, and
executable code that can be invoked from a virtual directory and its sub-
directories on a Web application server.
In this module, you will learn about some of the files that are used to build Web
applications and some of the capabilities of an ASP.NET application, such as
maintaining state and authentication. You will also learn how to configure and
deploy an ASP.NET application.
After completing this module, you will be able to:
n Describe cookie-less sessions.
n Set up cookie-less sessions in the web.config file.
n Use event procedures in global.asax.
n Set up page output caching for ASP.NET pages.
n Share information between pages of an ASP.NET application by using
ASP.NET cache, web.config, session variables, and a database.
n Describe how authentication works.
n Set up authentication for an application in web.config.

2 Module 7: Creating a Microsoft ASP.NET Web Application


Requirements of a Web Application
n State Maintenance
n Security
n Performance and Scalability
n Easy Configuration
n Easy Deployment

*****************************illegal for non-trainer use******************************
A good Web application meets the following requirements:
n State maintenance
Web applications should be able to maintain state across pages. If state is
maintained between pages, information supplied by users can be reused and
users do not need to enter the same information multiple times.
n Security
A good Web application should have security features. Most importantly, it
should be able to authenticate and authorize users who can access the
application.
n Performance and scalability
All Web applications should be built with high performance and scalability
in mind. Caching is an extremely important technique for building high-
performance, scalable Web server applications.
n Easy configuration
Configuration is an important aspect of any application. A central
requirement of any Web application server is a rich and flexible
configuration system. The objective is to enable developers to associate
settings easily with an installable application without needing to embed
values into code. This allows administrators to adjust or customize these
values easily after the Web application has been deployed.
n Easy deployment
Historically, one of the biggest problems associated with Web applications
is deployment. A well-designed Web application is easy to deploy.


Module 7: Creating a Microsoft ASP.NET Web Application 3


u What Is New in ASP.NET?
n Cookie-less Session IDs
n Configuration File (web.config)
n Setting Up Cookie-less Sessions
n Global Application File (Global.asax)
n Demonstration: Using Event Procedures in Global.asax
n Page Caching

*****************************illegal for non -trainer use******************************
In addition to all of the features provided by ASP, ASP.NET provides several
new features designed to enhance the functionality of an application. This
section focuses on the new features in ASP.NET.

4 Module 7: Creating a Microsoft ASP.NET Web Application


Cookie-less Session IDs
n Each Active Session Is Identified and Tracked Using
Session IDs
n SessionIDs Are Communicated Across Client-Server
Requests Using an HTTP Cookie or Included in the URL
n Using a Cookie
l Default mechanism for storing SessionIDs
n Cookie-less Sessions
l Information is encoded into URLs
http://server/(h44a1e55c0breu552yrecobl)/page.aspx
http://server/(h44a1e55c0breu552yrecobl)/page.aspx

*****************************illegal for non-trainer use******************************
Each active session in ASP.NET is identified and tracked by using a 120-bit
SessionID string containing Uniform Resource Locator (URL) -legal ASCII
characters. SessionID values are generated by using an algorithm that
guarantees both uniqueness and randomness. SessionIDs are communicated
across client-server requests by using either a Hypertext Transfer Protocol
(HTTP) cookie or included in the URL.
Using Cookies
Cookies are a mechanism by which data can be maintained in a file on the
user's computer. By default, SessionIDs are stored in cookies.
However, users can turn of f cookies through a setting in their browsers. This
creates the risk that your Web application will not work if it requires session
information conveyed by cookies and a user has disabled cookies in his or her
browser.

Module 7: Creating a Microsoft ASP.NET Web Application 5


Using Cookie-less Sessions
The ability to use cookie-less sessions in ASP.NET is a new concept that was
not available with earlier technologies, including ASP.
This method uses URLs, as opposed to cookies, to pass the SessionID to an
ASP.NET page. It involves encoding data into a URL, which is done
automatically by the browser. This enables you to use session state even with
browsers that have cookie support disabled.
For example, the browser generates the following URL for a request to the
ShoppingCart.aspx page on the http://localhost/conference web site:
http://localhost/conference/(h44a1e55c0breu552yrecobl)/ShoppingCart.aspx
To enable cookie-less sessions, add the following to the web.config
configuration file:
<sessi onSt at e cooki el ess=" t r ue" / >


6 Module 7: Creating a Microsoft ASP.NET Web Application


Configuration File (web.config)
n All Configuration Information for an ASP.NET
Application Is Contained in web.config
n Web.config Can Be Placed in the Same Folder as the
Application Files
n Web.config Contains Sections for Each Major Category
of ASP.NET Functionality
<configuration>
<system.web>
<trace enabled="true"
requestlimit="40" pageoutput="true"/>
</system.web>
</configuration>
<configuration>
<system.web>
<trace enabled="true"
requestlimit="40" pageoutput="true"/>
</system.web>
</configuration>

*****************************illegal for non-trainer use******************************
ASP.NET configuration uses hierarchical configuration architecture. All
configuration information for an ASP.NET application is contained in
configuration files named web.config that can be placed in the same directories
as the application files. Child directories inherit the settings of the parent
directories unless overridden by a web.config file in the child directory.
If a web.config file is present at the root directory of a Web serverfor
example, Inetpub\wwwrootthe configuration settings will apply to every
application in that server.
The presence of a web.config file within a given directory or application root is
optional. If a web.config file is not present, all configuration settings for the
directory are automatically inherited from the parent directory. The root
configuration file for all Web applications is named machine.config, and is
found in the c:\winnt\Microsoft.NET\Framework\v<version_number>\ Config
folder.

Module 7: Creating a Microsoft ASP.NET Web Application 7


In a web.config file, there are sections for each major category of ASP.NET
functionality, as shown in the following table.
Section name Description

<browsercaps> Responsible for controlling the settings of the browser
capabilities component.
<compilation> Responsible for all compilation settings used by ASP.NET.
<globalization> Responsible for configuring the globalization settings of an
application.
<httpmodules> Responsible for configuring HTTP modules within an
application. HTTP modules participate in the processing of
every request into an application. Common uses include security
and logging.
<httphandlers> Responsible for mapping incoming URLs to IHttpHandler
classes . Sub-directories do not inherit these settings. Also
responsible for mapping incoming URLs to
IHttpHandlerFactory classes. Data represented in
<httphandlerfactories> sections are hierarchically inherited by
sub-directories.
<iisprocessmodel> Responsible for configuring the ASP.NET process model
settings on Internet Information Services (IIS) Web Server
Systems.
<authentication>
<identity>
<authorization>
Responsible for all security settings used by the ASP.NET
security HttpModule.
<sessionState> Responsible for configuring the session state HttpModule.
<trace> Responsible for configuring the ASP.NET trace service.

ASP.NET configuration settings are represented within these configuration
sections. For example, as you saw in Module 5, Using Trace in Microsoft
ASP.NET Pages, in Course 2063B, Introduction to Microsoft ASP.NET, you
can turn the trace feature on for an entire application in the <trace>
configuration section as follows:
<conf i gur at i on>
<syst em. web>
<t r ace enabl ed="t r ue"
r equest l i mi t =" 40" pageout put =" t r ue" / >
</ syst em. web>
</ conf i gur at i on>


8 Module 7: Creating a Microsoft ASP.NET Web Application


Setting Up Cookie-less Sessions
n Session State Is Configured in the <sessionState>
Section of web.config
n <sessionState> Settings:
l cookieless
l timeout
n Setting Up Cookie-less Session
<sessionState cookieless="true />
<sessionState cookieless="true />
l mode
l sqlConnectionString

*****************************illegal for non-trainer use********************** ********
Session state features can be configured by the <sessionState> section in the
web.config file. The <sessionState> section sets the behavior of the session
state throughout the application. The following table lists the settings of the
<sessionState> section and their descriptions.
Setting Description

cookieless="[true/false]" Indicates whether cookies should be used to store Session
IDs. The default value is False. When the value is False,
cookies are used.
mode="[off/InProc/
SQLServer/StateServer]"
Specifies where the session information is kept: in memory
on the Web server; in a Microsoft SQL Server

database;
or in a separate process on the Web server or remote
computer.
sqlConnectionString Specifies the connection string for a SQL Server. For
example, "data source=127.0.0.1;user id=sa; password=".
This attribute is required when mode is set to sqlserver.
timeout="[number of
minutes]"
Specifies the number of minutes a session can be idle
before it is abandoned. The default value is 20 minutes.

For example, to double the default timeout of 20 minutes, the following can be
added to the web.config of an application:
<sessi onst at e t i meout ="40" / >

Setting Up a Cookie-less Session
By default, ASP.NET uses cookies to identify requests within a single session.
If cookies are not available, or have been disabled by the user, a session can be
tracked by adding a session identifier to the URL. You can enable cookie -less
sessions as follows:
<sessi onst at e cooki el ess=" t r ue" / >


Module 7: Creating a Microsoft ASP.NET Web Application 9


Global Application File (Global.asax)
n Global.asax is Similar to Global.asa in ASP Applications
n Global.asax Supports More Than 15 Events
l As page is requested: BeginRequest,
AuthenticateRequest, AuthorizeRequest
l As page is returned: EndRequest

*****************************illegal for non-trainer use******************************
Similar to ASP, ASP.NET supports one global declarative file per application
for application events and state called global.asax. The global.asax file is
similar to ASPs global.asa, but has numerous new events that are not supported
by global.asa.

In ASP.NET, global.asax can be used as an .asax file or as a component
that can be deployed in the applications /bin directory.

Events
The event model provided by ASP.NET supports more than 15 events. This is
different from global.asa, which had only Application and Session OnStart and
OnEnd events.
For example, in ASP, if you wanted some code to run at the beginning of every
page, you would have needed to use an Include file at the top of every ASP
page. Using the ASP.NET global.asax file, you can simply declare the code in
the Application_BeginRequest event procedure, which is called at the
beginning of every request for the application.
Sub Appl i cat i on_Begi nRequest ( s As Obj ect , e As Event Ar gs)
. . .
End Sub


Note
10 Module 7: Creating a Microsoft ASP.NET Web Application


ASP.NET still supports the Application and Session OnStart and OnEnd event
procedures, but Global.asax also includes events that are fired when a client
requests a page. The following table lists events that can be used when a page is
requested.
Event Name Description

Application_Error This event is fired when an un-handled
error occurs within an application.
Application_BeginRequest This event is fired whenever a new
request is received.
Application_AuthenticateRequest This event indicates that the request is
ready to be authenticated.
Application_AuthorizeRequest This event signals that the request is
ready to be authorized.
Application_ResolveRequestCache This event is used by the output cache
module to stop the processing of requests
that have been cached.
Application_AcquireRequestState This event signals that per-request state
should be obtained.
Application_PreRequestHandlerExecute This event signals that the request
handler is about to execute.

Global.asax also includes events that are fired when the requested page is sent
back to the client. The following table lists these events.
Event Name Description

Application_PostRequestHandlerExecute This event is first available after the
handler (such as an ASP.NET page), or
Web service has completed its work.
Application_ReleaseRequestState This event is called when the request
state should be stored, because the
application is finished with it.
Application_UpdateRequestCache This event signals that code processing
is complete and the file is ready to be
added to the ASP.NET cache.
Application_EndRequest This event is the last event called when
the application ends.
Application_PreRequestHeaderSent This event provides the opportunity to
add, remove, or update headers and the
response body.


Module 7: Creating a Microsoft ASP.NET Web Application 11


Demonstration: Using Event Procedures in Global.asax

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to display events fired in the
global.asax file.
To run this demonstration
1. Copy the file <install folder>\Democode\Mod07\global.asax to the folder
<install folder>.
This is the root of the 2063 virtual directory.
2. Open the file global.asax. There are Response.Write statements in the event
procedures.
3. View http://localhost/2063/DemoCode/Mod07/GlobalEvents.aspx in
Microsoft Internet Explorer.
4. Delete the global.asax file from the root of the 2063 virtual directory.


12 Module 7: Creating a Microsoft ASP.NET Web Application


Page Caching
n Output Caching
l Caches content generated from dynamic pages
l Page is compiled into IL and native code
l Native code is cached as Page class and is available to
serve for the next request
l Page class is updated when the source ASP.NET file is
changed or cache timeout happens
n Setting the Cache Timeout
<%@ OutputCache Duration= "900" %>
<%@ OutputCache Duration= "900" %>

*****************************illegal for non-trainer use******************************
Page caching allows you to cache dynamic content. When an ASP.NET page is
accessed for the first time, the page is compiled into Intermediate Language (IL)
and to native code. This native code is cached as Page class and is available to
serve the next request. This cached Page class is updated and rebuilt when the
source ASP.NET file is changed or the cache timeout is reached.
Setting the Cache Timeout Value
You can specify the cache timeout value by setting the output cache page
directive. For example, to cache an ASP.NET page for 15 minutes, add the
following @OutputCache directive to the .aspx page:
<%@Out put Cache Dur at i on=" 900" %>

The unit for time for the Duration attribute is seconds.
This cache option is very useful for pages that do not change often (or do not
change within a known time period).

Creating an output cache for an application should be your final task in
application development. Otherwise, when you debug your pages, instead of
getting new and modified pages, you may get old pages that are stored in the
output cache.


Note
Module 7: Creating a Microsoft ASP.NET Web Application 13


u Sharing Information Between Pages
n Using ASP.NET Cache
n Using web.config Variables
n Demonstration: Using web.config Variables
n Using Session and Application Variables
n Demonstration: Using Session Variables
n Saving Session and Application Variables in a Database
n Discussion: Different Ways of Sharing Information

*****************************illegal for non-trainer use********** ********************
It is often necessary to share information between the pages of a Web
application. The information being shared can be either static or dynamic.
In this section, you will learn how to share both static and dynamic data
between pages of a Web application.

14 Module 7: Creating a Microsoft ASP.NET Web Application


Using ASP.NET Cache
n ASP.NET Cache:
l Stores objects and values for reuse in an application
n Placing Objects in ASP.NET Cache
n Retrieving Objects From ASP.NET Cache
Cache.Insert("mykey", myValue, _
Nothing, DateTime.Now.AddHours(1), _
TimeSpan.Zero)
Cache.Insert("mykey", myValue, _
Nothing, DateTime.Now.AddHours(1), _
TimeSpan.Zero)
myValue = Cache("mykey")
If myValue <> Nothing Then
DisplayData(myValue)
End If
myValue = Cache("mykey")
If myValue <> Nothing Then
DisplayData(myValue)
End If

*****************************illegal for non-trainer use******************************
The ASP.NET cache can be used to store objects and values that you reuse in
your application. ASP.NET provides a full-featured cache engine that can be
used by pages to store and retrieve arbitrary objects across HTTP requests. The
ASP.NET cache is private to each application and stores objects in memory.
The lifetime of the cache is equivalent to the lifetime of the application. This
means that, when the application is restarted, the cache is recreated.
The ASP.NET cache also provides a way to pass values between pages within
the same application. The ASP.NET cache methods implement automatic
locking; therefore, it is safe for objects to be accessed concurrently from more
than one page. The only drawback is that another page may change the values
that you place in the cache. It is not a per-user cache.
The cache provides a simple dictionary interface that allows you to insert
objects easily and retrieve them later. In the simplest case, placing an item in
the cache is exactly like adding an item to a dictionary:
Cache( " mykey" ) = myVal ue

Retrieving this data is equally simple:
myVal ue = Cache( " mykey" )
I f myVal ue <> Not hi ng Then
Di spl ayDat a( myVal ue)
End I f

You can also supply parameters when inserting an item into the cache by using
the Insert method.

Module 7: Creating a Microsoft ASP.NET Web Application 15


Cache.Insert Syntax
Cache. I nser t ( key As St r i ng, _
val ue As Obj ect , _
dependenci es As CacheDependency, _
absol ut eExpi r at i on As Dat eTi me, _
sl i di ngExpi r at i on As Ti meSpan )

n key is the cache key used to reference the object.
n value is the object to be cached.
n dependencies should be set to Nothing.
n absoluteExpiration is the time at which the cached object expires and is
removed from the cache.
n slidingExpiration is the interval between the time the cached object was
last accessed and when that object is scheduled to expire. For example, if
slidingExpiration is set to 20 minutes, the object will expire and be
removed from the cache 20 minutes after the object was last accessed.

The following code shows how to use the ASP.NET cache to store a DataView
that is used in an ASPX page. The first time the page is requested, it reads data
from the database and then stores it in the ASP.NET cache. At every
subsequent request for the page, the DataView is retrieved from the cache,
eliminating a call to the database. This example uses absolute expiration to set
the cache to expire one hour from the first time it was accessed.
Di mdvMenuI t ems As Dat aVi ew
dvMenuI t ems = Cache( " dvMenuI t ems" )

I f ( dvMenuI t ems = Not hi ng) Then
Di mpr oduct s As New Conf er ence. Pr oduct sDB
dvMenuI t ems = pr oduct s. Get Pr oduct Cat egor i es( ) . _
Tabl es( 0) . Def aul t Vi ew
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now. AddHour s( 1) , Ti meSpan. Zer o)
End I f

MyLi st . Dat aSour ce = dvMenuI t ems
MyLi st . Dat aBi nd( )

To set the cache to use sliding expiration and expire one hour after the last time
it was accessed, apply the following parameters to the Insert method:
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now, Ti meSpan. Fr omHour s( 1) )


16 Module 7: Creating a Microsoft ASP.NET Web Application


Using web.config Variables
n Store Application Variables in web.config
n Retrieve in an .aspx File
<configuration>
<appsettings>
<add key="pubs" value=
"server=localhost;uid=sa;pwd=;database=pubs"/>
</appsettings>
</configuration>
<configuration>
<appsettings>
<add key="pubs" value=
"server=localhost;uid=sa;pwd=;database=pubs"/>
</appsettings>
</configuration>
Dim appSetting As NameValueCollection
Dim strConn As String
appSetting = CType(Context.GetConfig _
("appsettings"), NameValueCollection )
strConn = appSetting("pubs").ToString()
Dim appSetting As NameValueCollection
Dim strConn As String
appSetting = CType(Context.GetConfig _
("appsettings"), NameValueCollection )
strConn = appSetting("pubs").ToString()

*****************************illegal for non-trainer use******************************
You can use the <appsettings> section of the web.config file as a repository for
application settings. In the <appsettings> section, you can create key/value pairs
for data that is commonly used throughout your application. This is very useful
because you can define all application configuration data in a central location.
For example, you can store a database connection string for an application in a
central location, instead of having it in each ASP.NET page.
The following web.config file creates two key/value pairs for the connection
strings for the databases used in the application:
<conf i gur at i on>
<appset t i ngs>
<add key=" pubs"
val ue="ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs" / >
<add key=" nor t hwi nd"
val ue=" ser ver =l ocal host ; ui d=sa; pwd=; dat abase=nor t hwi nd"
/ >
</ appset t i ngs>
</ conf i gur at i on>

Use the GetConfig method of the Context object to read the data from the
web.config file. You need to supply the name of the section and the name of the
key to retrieve. The GetConfig method returns a NameValueCollection
variable containing the key/value pairs defined in the requested section.

Module 7: Creating a Microsoft ASP.NET Web Application 17


For example, the following sample code reads the value of the pubs key from
the <appSettings> section.
Di mappSet t i ng As NameVal ueCol l ect i on
Di mst r Conn As St r i ng
appSet t i ng = CType( Cont ext . Get Conf i g( " appset t i ngs" ) , _
NameVal ueCol l ect i on)
st r Conn = appSet t i ng( "pubs") . ToSt r i ng( )

You can also use the GetConfig method of the HttpContext object to access
configuration information from a component. The syntax for this is:
appSet t i ng = _
CType( Ht t pCont ext . Cur r ent . Get Conf i g( " appset t i ngs " ) , _
NameVal ueCol l ect i on)


18 Module 7: Creating a Microsoft ASP.NET Web Application


Demonstration: Using web.config Variables

*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create a constant in web.config and
use the constant from different ASP.NET pages.
To run the demonstration
1. Create a new web.config file in the folder
<install folder>\DemoCode\Mod07.
2. Add the <configuration> tag with an <appsettings> section.
3. Add a new key to the <appsettings> section:
<conf i gur at i on>
<appSet t i ngs>
<add key=" i nt Number I nConf i g" val ue=" 9" / >
</ appSet t i ngs>
</ conf i gur at i on>

4. Open the file <install folder>\DemoCode\ Mod07\ UsingConfigVar1.aspx.
The intNumberInConfig value is retrieved and displayed in the
Page_Load event procedure.
5. View the UsingConfigVar1.aspx page in Internet Explorer.
The value of intNumberInConfig, 9, is displayed.
6. Click Next.
The UsingConfigVar2.aspx page opens and displays the same value.


Module 7: Creating a Microsoft ASP.NET Web Application 19


Using Session and Application Variables
n Session Object Stores Information for a Particular User
Session
n Application Object Shares Information Among All Users
of a Web Application
Sub Session_Start(s As Object, e As EventArgs)
Session("BackColor") = "beige"
Session("ForeColor") = "black"
End Sub
Sub Session_Start(s As Object, e As EventArgs)
Session("BackColor") = "beige"
Session("ForeColor") = "black"
End Sub
Sub Application_Start(s As Object, e As EventArgs)
Application("NumberofVisitors") = 0
End Sub
Sub Application_Start(s As Object, e As EventArgs)
Application("NumberofVisitors") = 0
End Sub

*****************************illegal for non-trainer use******************************
You can use session and application variables to share information between
pages of an ASP.NET application.
You generally initialize session and application variables in the Start event
procedures of the Session and Application objects in the global.asax file.
Session Variables
You use the Session object to store information that is needed for a particular
user session. Variables stored in the Session object will not be discarded when
the user goes between pages in the Web application. Instead, these variables
will persist for the entire user session. The following example illustrates how
session variables are used to store information about a particular user session.
<scr i pt l anguage=" VB" r unat =" ser ver " >
Sub Sessi on_St ar t ( S As Obj ect , E As Event Ar gs)
Sessi on( " BackCol or " ) = " bei ge"
Sessi on( " For eCol or " ) = " bl ack"
Sessi on( " Font Name" ) = " ver dana"
End Sub
</ scr i pt >


20 Module 7: Creating a Microsoft ASP.NET Web Application


Application Variables
You can use the Application object to share information among all users of a
Web application. An Application object is created when the first user of the
application requests an .aspx file. It is destroyed when all users have exited the
application and the application is unloaded.
For example, you might store the total number of visitors to a Web site in an
application- level variable.
Sub Appl i cat i on_St ar t ( s As Obj ect , e As Event Ar gs)
Appl i cat i on( " Number of Vi si t or s" ) = 0
End Sub

A disadvantage of using session and application variables is that the
memory occupied by these variables will not be released until the value is either
removed or replaced. For example, keeping seldom-used 10-megabyte (MB)
recordsets in application-state permanently is not the best use of system
resources.

Reading Session and Application Variables
To use a session or application variable in an ASP.NET page, simply read the
value from the Session or Application object.
Sessi on( " BackCol or " )
Sessi on( "For eCol or " )
Sessi on( " Font Name" )
Appl i cat i on( "Number of Vi si t or s")


Note
Module 7: Creating a Microsoft ASP.NET Web Application 21


Demonstration: Using Session Variables

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to share the same session variable
through two different ASP.NET pages.
To run the demonstration
1. Copy the file <install folder>\Democode\Mod07\global.session to the root
of the 2063 virtual folder and rename it global.asax.
2. Open the file global.asax and initialize a session variable named intNumber
to 3 by adding the following code to the Session_Start event procedure:
Sessi on( " i nt Number " ) =3

3. Open the file <install folder>\Democode\Mod07\UsingSessionVar1.aspx.
The session variable is retrieved and displayed in the Page_Load event
procedure.
4. View the page
http://localhost/2063/democode/Mod07/UsingSessionVar1.aspx in
Internet Explorer.
The value of the session variable, 3, is displayed.
5. Click Next.
The UsingSessionVar2.aspx page opens, increments the session variable by
4, and displays the new value, 7.
6. Click Back to return to the UsingSessionVar1.aspx, which displays the new
value of the session variable.


22 Module 7: Creating a Microsoft ASP.NET Web Application


Saving Session and Application Variables in a Database
n Session State Can Be Stored in a Separate SQL Server
Database
n A Temporary Table Is Used for the Serialized Session
Data
n Advantages:
l State can be recovered even if an application crashes
l An application can be partitioned across multiple Web
farm machines

*****************************illegal for non-trainer use******************************
In ASP.NET, an application can store session state in a separate SQL Server
database. A temporary table is used for the serialized session data. The table
can be accessed by a combination of stored procedures and managed data
access components for SQL Server.
By cleanly separating the storage of session data from the application usage of
it, ASP.NET provides advantages that did not exist in ASP:
n Ability to recover from application crashes
Because all state is stored externally from an individual worker process, it
will not be lost if the process crashes or is forcibly restarted.
n Ability to partition an application across multiple Web farm servers
Because all state is stored externally from worker processes, you can
partition an application across multiple worker processes running on
multiple servers. The model for communicating state between a worker
process and a state service running on the same server is almost identical to
models in which the state service is located on a completely different
machine.

To configure your application to store session state in a separate database, set
the mode attribute of the sessionState section to SQLServer and set the
sqlConnectionString attribute to the connection string for the server.
For more information on saving session information in a database, see Session
State in the Microsoft .NET Framework software development kit (SDK)
documentation.

Module 7: Creating a Microsoft ASP.NET Web Application 23


Discussion: Different Ways of Sharing Information

*****************************illegal for non-trainer use**************** **************

24 Module 7: Creating a Microsoft ASP.NET Web Application


u Securing an ASP.NET Application
n What Is Authentication?
n Forms Authentication Architecture
n Setting Up Security in web.config
n Creating a Login Form
n Demonstration: Setting Up Security in web.config

*****************************illegal for non-trainer use******************************
Securing Web sites is a critical is sue for Web developers. A secure system
requires careful planning, and Web site administrators and programmers must
have a clear understanding of the options for securing a site. Security, in the
context of an ASP.NET application, involves performing three fundamental
functions for all requests: authentication, authorization, and impersonation.
Authentication is the process verifying that the user requesting a page is
actually that user. To authenticate a request, you accept credentials from a user
and validate those credentials against some authority.
After you have authenticated the user, the authorization process determines
whether that user should be granted access to a given resource.
Another important feature of server applications is the ability to control the
identity under which server application code is executed. When a server
application executes code with the identity of the requesting entity, this is
known as impersonation.
In this section, you will learn about securing an ASP.NET application by
implementing authentication and authorization in web.config.

Module 7: Creating a Microsoft ASP.NET Web Application 25


What Is Authentication?
n Authentication
l Accept credentials from a user
l Validate the credentials
n Types of ASP.NET Authentication
l Windows authentication
l Passport authentication
l Forms authentication

*****************************illegal for non-trainer use******************************
Authentication is the process of accepting credentials from a user and validating
those credentials against some authority. If the credentials are valid, you have
an authenticated identity.
Authentication in ASP.NET is implemented through authentication providers.
ASP.NET authentication providers are the code modules that contain the code
necessary to authenticate the requestor s credentials.
The first version of ASP.NET will ship with support for the following
authentication providers:
n Windows authentication
This method is used in conjunction with the IIS authentication.
Authentication is performed by IIS in one of three ways: Basic, Digest, or
Integrated Windows Authentication. The advantage of using this
authentication type is that it requires minimum coding. Also, because it is
Microsoft Windows NT authentication, there is no additional cost to
implement this type of security. However, because the resources for
authentication are not embedded in the ASP.NET application, using this
method involves additional effort when deploying the application.
For more information on Windows authentication, see the Microsoft .NET
Framework SDK documentation.
n Passport authentication
Passport authentication is a centralized authentication service provided by
Microsoft that offers a single sign-in and core profile services for member
sites. It is a Web service and an integral part of the Microsoft .NET
Framework.
For more information on Passport authentication, go to:
http://www.passport.com/Business

26 Module 7: Creating a Microsoft ASP.NET Web Application


n Forms authentication
Forms authentication refers to a system where unauthenticated requests are
redirected to a Hypertext Markup Language (HTML) form (by using HTTP
client-side redirection). The user provides credentials and submits the form.
If the application validates credentials on the form, the system issues a
cookie to the user. Subsequent requests are issued with the cookie in the
request headers; therefore, they are authenticated.


Module 7: Creating a Microsoft ASP.NET Web Application 27


Forms Authentication Architecture
Client requests page
Authorized
ASP.NET
Authentication
Not
Authenticated Authenticated
Login Page
(Users enter
their credentials)
Authenticated
Cookie
Authorized
Not
Authenticated
Access Denied
Requested
Page


*****************************illegal for non-trainer use******************************
The most commonly used authentication type in ASP.NET applications is
forms authentication.
A request for a page protected by forms authentication must still go through IIS
first. Therefore, you must set IIS authentication to Anonymous Access. This
allows all requests to get to ASP.NET before being authenticated.

For more information on setting up Anonymous Access, see the Security
section in the IIS documentation.

The following is the set of events that take place during forms authentication:
1. A client generates a request for a protected page.
2. IIS receives the request, and passes it to the ASP.NET application. Because
the authentication mode is set to Anonymous Access, IIS authentication is
not used.
3. ASP.NET checks to see if a valid authentication cookie is attached to the
request. If it is, this means that the users credentials have already been
confirmed, and the request is tested for authorization. The authorization test
is performed by ASP.NET and is accomplished by comparing the
credentials contained in the requests authorization cookie to the
authorization settings in the applications configuration file (web.config). If
the user is authorized, access is granted to the protected page.
4. If there is no cookie attached to the request, ASP.NET redirects the request
to a login page (the path of which resides in the applications configuration
file), where the user enters the required credentials, usually a name and
password.

Tip
28 Module 7: Creating a Microsoft ASP.NET Web Application


5. The application code on the login page checks the credentials to confirm
their authenticity and, if authenticated, attaches a cookie containing the
credentials to the request. If authentication fails, the request is returned with
an Access Denied message.
6. If the user is authenticated, ASP.NET checks authorization as in step 3, and
can either allow access to the originally requested, protected page or redirect
the request to some other page, depending on the design of the application.
Alternatively, it can direct the request to some custom form of authorization
where the credentials are tested for authorization to the protected page.
Usually if authorization fails, the request is returned with an Access
denied message.


Module 7: Creating a Microsoft ASP.NET Web Application 29


Setting Up Security in web.config
n Setting Up Authentication
n Setting Up Authorization
<system.web>
<authentication mode="Forms">
<forms name="name" loginurl="login.aspx"/>
</authentication>
</system.web>
<system.web>
<authentication mode="Forms">
<forms name="name" loginurl="login.aspx"/>
</authentication>
</system.web>
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="Mary"/>
</authorization>
</system.web>
</location>
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="Mary"/>
</authorization>
</system.web>
</location>

*****************************illegal for non-trainer use******************************
Security for ASP.NET applications is set up in the applications web.config file.
The security settings in web.config are included in the <authentication>,
<authorization>, and <identity> sections.

You can set up authentication only in the web.config file in the root of
your Web application.

Setting Up Authentication
Begin by setting the authentication method for the application in an
<authentication> subsection of the <system.web> section, as shown in the
following example.
<conf i gur at i on>
<syst em. web>
<aut hent i cat i on mode=" aut hmode" >
</ aut hent i cat i on>
</ syst em. web>
</ conf i gur at i on>

As mentioned earlier in this module, ASP.NET supports three types of
authentication: Windows authentication, Forms authentication, and Passport
authentication. You can set the authentication mode for an application by
setting the mode attribute in the <authentication> tag to "None", "Windows",
"Passport", or "Forms".

Note
30 Module 7: Creating a Microsoft ASP.NET Web Application


If you set the authentication mode to Forms, you need to add a <forms>
element to the <authentication> section, as shown in the following example:
<syst em. web>
<aut hent i cat i on mode="For ms">
<f or ms name=". namesuf f i x" l ogi nur l =" l ogi n. aspx" / >
</ aut hent i cat i on>
</ syst em. web>

In the <forms> section, you configure settings of the cookie. Set the name
attribute to the suffix to be used for the cookies and the loginUrl attribute to the
URL of the page to which un-authenticated requests are redirected.
Setting Up Authorization
After specifying the authentication mode, you need to either mark the entire
Web application as needing authorization or specify which pages are secure and
require authorization.
Securing an Entire Application
To mark the entire application as secure, create an <authorization> section in
the <authentication> section, as illustrated in the following code example:
<syst em. web>
<aut hent i cat i on mode=" For ms" >
<f or ms name=" . aspxaut h"
l ogi nur l =" l ogi n. aspx" / >
<aut hor i zat i on>
</ aut hor i zat i on>
</ aut hent i cat i on>
</ syst em. web >


Module 7: Creating a Microsoft ASP.NET Web Application 31


Securing Specific Pages
To mark only specific pages as secure, create a <location> section with
<sys tem.web> and <authorization> sub-sections for each secure page in your
Web application:
<l ocat i on pat h="Shoppi ngCar t . aspx">
<syst em. web>
<aut hor i zat i on>
</ aut hor i zat i on>
</ syst em. web>
</ l ocat i on>

Any configuration settings contained in the <location> section will be directed
at the file or directory indicated in the path attribute. There can be multiple
<location> sections in the <configuration> section.
In the <system.web> section, you create an <authorization> subsection to
specify what type of authorization will be enforced. Create <allow> or <deny>
tags to allow or deny users access to a page. Within these tags, "?" indicates
anonymous users, whereas "*" means all users. For example, the following
code denies access to all anonymous users.
<aut hori zat i on>
<deny user s="?"/ >
</ aut hor i zat i on>

The following code allows the user Mary access to a page:
<aut hor i zat i on>
<al l ow user s="Mar y"/ >
</ aut hor i zat i on>

The following example denies all anonymous users access to the
ShoppingCart.aspx page.
<l ocat i on pat h="Shoppi ngCar t . aspx">
<syst em. web>
<aut hor i zat i on>
<deny user s="?"/ >
</ aut hor i zat i on>
</ syst em. web>
</ l ocat i on>

For more information about setting up authorization in web.config, see
ASP.NET Authorization in the Microsoft .NET Framework SDK
documentation.

32 Module 7: Creating a Microsoft ASP.NET Web Application


Creating a Login Form
n Login Page Verifies and Checks the Credentials of a User
l Login page validates user credentials and redirects if valid
n Reading User Credentials from Cookie
l User.Identity.Name returns the value saved by
CookieAuthentication.RedirectFromLoginPage
Sub cmdLogin_Click(s As Object, e As EventArgs)
If (login(txtEmail.Value, txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage _
(txtEmail.Value, False)
End If
End Sub
Sub cmdLogin_Click(s As Object, e As EventArgs)
If (login(txtEmail.Value, txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage _
(txtEmail.Value, False)
End If
End Sub

*****************************illegal for non-trainer use******************************
During authentication, all requests are redirected to the login page specified in
the loginurl attribute of the <cookie> tag. The login page verifies and checks
the credentials of a user.
How Does a Login Page Work?
If the authentication mode is set to "Forms", ASP.NET looks for a cookie
attached to a request for a secure page. If it does not find one, it redirects the
request to a specified login page.
On the login page, the user enters the required credentials. The page checks the
entered credentials either through application-specific code or by calling
FormsAuthentication.Authenticate. If the credentials are valid, a cookie is
generated and the user is redirected to the originally requested page by calling
FormsAuthentication.RedirectFromLoginPage . However, if the credentials
are not valid, the user stays on the login page and is given a message that
indicates that the login credentials are invalid.
The RedirectFromLoginPage method takes two parameters, userName,
which specifies the name of the user for forms authentication purposes, and
createPersistentCookie. If the value of createPersistentCookie is True, a
cookie is created on the users machine.

Module 7: Creating a Microsoft ASP.NET Web Application 33


The following table lists all the methods of the FormsAuthentication object,
which can be used in the authentication process.
Method Function

Authenticate Given the supplied credentials, this method attempts to
validate the credentials against those contained in the
configured credential store.
GetAuthCookie Creates an authentication cookie for a given user name.
This does not set the cookie as part of the outgoing
response, so that an application can have more control over
how the cookie is issued.
GetRedirectUrl Returns the redirect URL for the original request that
caused the redirect to the login page.
RedirectFromLoginPage Redirects authenticated users back to the original URL they
requested.
SetAuthCookie Creates an authentication ticket for the given userName and
attaches it to the cookies collection of the outgoing
response. It does not perform a redirect.
SignOut Given an authenticated user, calling SignOut removes the
authentication ticket by doing a SetCookie with an empty
value. This removes either durable or session cookies.

Creating a Login Page
A login page is simply an ASP.NET page with an HTML form, a Submit
button, and a Click event procedure for the Submit button.
The following is an example of a form on a login page:
<f or m r unat =ser ver >
Emai l : <i nput i d=" t xt Emai l " t ype=" t ext " r unat =ser ver / >
<BR>
Passwor d<i nput i d=" t xt Passwor d" t ype=" passwor d"
r unat ="ser ver "/ >
<BR>
<asp: but t on t ext =" Logi n" OnCl i ck=" Logi n_Cl i ck"
r unat =" ser ver " / >
<asp: l abel i d=" l bl Msg" r unat =" ser ver " / >
</ f or m>


34 Module 7: Creating a Microsoft ASP.NET Web Application


In the Click event procedure of the Submit button, you validate the information
entered in the form, then call FormsAuthentication.RedirectFromLoginPage
if it is valid. The RedirectFromLoginPage method issues the cookie and then
redirects the user to the originally requested page. The following sample code
uses a custom function named Login to validate the username and password,
and then calls RedirectFromLoginPage if they are valid:
<scr i pt l anguage="VB" r unat =ser ver >
Sub cmdLogi n_Cl i ck( Sender As Obj ect , E As Event Ar gs)
Di mst r Cust omer I d As St r i ng
' Val i dat e User Cr edent i al s
st r Cust omer I d = Logi n( t xt Emai l . Val ue, t xt Passwor d. Val ue)

I f ( st r Cust omer I d <> "") Then
For msAut hent i cat i on. Redi r ect Fr omLogi nPage _
( st r Cust omer I d, Fal se)
El se
l bl Msg. Text = " I nval i d Cr edent i al s: Pl ease t r y agai n"
End I f
End Sub
</ scr i pt >

Reading Credentials from Cookie
After a user has been authenticated, you can obtain the user name of the
authenticated user programmatically by using the User.Identity.Name property.
This is useful to build an application that uses the users name as a key to save
information in a database table or directory resource.
Using Credentials from web.config
If you do not want to write your own validation function, you can create a list
of users in the web.config file and use the FormsAuthentication.Authenticate
method to validate a username and password pair.
The following web.config file creates two valid users for an application:
<syst em. web>
<aut hent i cat i on mode="For ms">
<f or ms l ogi nur l =" democode/ Mod07/ Logi nDemo. aspx" >
<cr edent i al s passwor dFor mat =" Cl ear " >
<user name="r ut h" passwor d="passwor d"/ >
<user name="bob" passwor d=" passwor d" / >
</ cr edent i al s>
</ f or ms>
</ aut hent i cat i on>
</ syst em. web>


Module 7: Creating a Microsoft ASP.NET Web Application 35


The following event procedure on the login page calls the Authenticate method
to authenticate only those users from the web.config file:
Sub cmdLogi n_Cl i ck( S As Obj ect , E As Event Ar gs)
I f ( For msAut hent i cat i on. Aut hent i cat e _
( t xt Emai l . val ue, t xt Passwor d. Val ue) )
For msAut hent i cat i on. Redi r ect Fr omLogi nPage _
( t xt Emai l . Val ue, Fal se)
El se
l bl Msg. Text = " I nval i d Cr edent i al s: Pl ease t r y agai n"
End I f
End Sub


36 Module 7: Creating a Microsoft ASP.NET Web Application


Demonstration: Setting Up Security in web.config

*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to set up authentication in web.config
and how to create an authentication cookie in a login file.
To run the demonstration
1. Copy the files <install folder>\Democode\Mod07\config.demo,
LoginDemo.aspx, SecurePageDemo1.aspx, SecurePageDemo2.aspx,
UsingSessionVar1.aspx, and UsingSessionVar2.aspx to the root of the 2063
virtual directory.
2. Rename the file config.demo to web.config.
3. Edit the file web.config.
There is an <authentication> section that redirects all unauthenticated
requests to the LoginDemo.aspx page.
Two pages have been set up as secure pages.
4. Edit the file <install folder>\LoginDemo.aspx.
The cmdLogin_Click event procedure validates the user name and
password and calls RedirectFromLoginPage if they are valid.
5. View the unsecured page http://localhost/2063/Us ingSessionVar1.aspx page
in Internet Explorer.
6. View the secure page http://localhost/2063/SecurePageDemo1.aspx page in
Internet Explorer.
You are redirected to the LoginDemo.aspx page.

Module 7: Creating a Microsoft ASP.NET Web Application 37


7. Type an e-mail name and an invalid password (password is the only valid
password) and click Sign In Now.
It will fail because the password is invalid.
8. Type password for the password field and click Sign In Now again. You
will be redirected to the SecurePageDemo1.aspx page.
9. View the secure page http://localhost/2063/SecurePageDemo2.aspx in
Internet Explorer.


38 Module 7: Creating a Microsoft ASP.NET Web Application


Lab 7: Creating an ASP.NET Web Application

*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Use forms authentication to authenticate and authorize users when accessing
secured pages.
n Use the ASP.NET cache to save data for the _menu.aspx page.
n Maintain state of an application by saving data in a database.

Prerequisite
Before working on this lab, you must know how to use a component.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab07\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab07\Solution.

Module 7: Creating a Microsoft ASP.NET Web Application 39


Scenario
In Exercise 1, you will use the ASP.NET cache to store a DataSet that is used
by the _menu.aspx page.
When users want to sign into the conference system, they need to enter a valid
e-mail name and corresponding password. This is done on the login.aspx page
or through register.aspx in the case of a new user. In this lab, you will first
complete the login.aspx and register.aspx pages to attempt to authenticate a user
through the use of a cookie (forms authentication). Exercises 2 and 4 involve
variations on forms authentication of this user. Exercise 3 illustrates how to
retrieve the customer ID of the authenticated user from any of the pages of your
application. You can use this ID to store customer information or products
selected by the customer in the database.
Estimated time to complete this lab: 60 minutes

40 Module 7: Creating a Microsoft ASP.NET Web Application


Exercise 1
Storing Data
In this exercise, you will programmatically cache the DataView used by the
DataList control in the file _Menu.ascx. You will then look at web.config to
see how the connection string for the Conf database is stored.
To read the DataView from the cache
1. Open the file _Menu.ascx file in the folder InetPub\wwwRoot\ASPNET.
2. At the beginning of the Page_Load event procedure, immediately after the
dvMenuItems variable is declared, add code to read the contents of the
dvMenuItems item from the cache and save it in the dvMenuItems variable.
Your code should look like the following:
dvMenuI t ems = Cache( " dvMenuI t ems" )

3. Test the contents of dvMenuItems. If the content is empty:
a. Create the DataView from the database by using the code that is already
in the event procedure.
b. Store the DataViewin the cache. Create the cache such that it will be
stored for one hour.
Your code should look like the following:
I f ( dvMenuI t ems I s Not hi ng) Then
Response. Wr i t e ( " Get t i ng i t ems f r omt he dat abase. <P>" )
Di mpr oduct s As New Conf er ence. Pr oduct sDB

dvMenuI t ems = pr oduct s. Get Pr oduct Cat egor i es( ) . _
Tabl es( 0) . Def aul t Vi ew
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now. AddHour s( 1) , Ti meSpan. Zer o)
El se
Response. Wr i t e ( " Got i t ems f r omt he cache. <P>" )
End I f


To save and test your work
1. Save your changes to _Menu.ascx.
2. By using Internet Explorer, go to the home page of the ASPNET Web site
by viewing http://localhost/ASPNET/default.aspx
The items are retrieved from the database.
3. Refresh the page in Internet Explorer.
The items are retrieved from the cache.


Module 7: Creating a Microsoft ASP.NET Web Application 41


To investigate web.config application settings
As you can see in the _Menu.ascx file, the GetProductCategories() method is
used to get the items for the menu from the database. This method is in the
ProductsDB.vb component.
1. Open the ProductsDB.vb file from the Components folder and locate the
GetProductCategories method.
The SQL connection string is obtained from
ConferenceDB.ConnectionString.
2. Open the ConferenceDB.vb file from the Components folder and locate the
ConnectionString property.
The connection string is read from the DSN key in the <appSettings>
section of the web.config file.
3. Open the web.config file in the ASPNET Web site and locate the DSN key
in the <appSettings> section.


42 Module 7: Creating a Microsoft ASP.NET Web Application


Exercise 2
Using Forms Authentication
In this exercise, you will validate the users name and password from the
login.aspx page with information stored in the database. If the information is
valid, you will transfer the contents of the temporary shopping cart into a
permanent shopping cart for the user. Next, you will create an authentication
cookie that will be used throughout the Web site.
You will use two different classes in the conference component:
Conference.ShoppingCartDB manipulates the shopping cart and
Conference.CustomersDB accesses the customer information in the Conf
database.

The source code for these classes can be found in the
\Components\ShoppingCartDB.vb and \Components\CustomerDB.vb files in
the ASPNET Web site.

You will call the following methods:
n Conference.ShoppingCartDB.GetShoppingCartID() returns a string with
the ID of the current shopping cart.
Publ i c Funct i on Get Shoppi ngCar t I d( ) As St r i ng

n Conference.ShoppingCartDB.MigrateCart() migrates the items from one
shopping cart (temporary) to another (permanent). The permanent shopping
cart uses the customer's ID as the shopping cart ID.
Publ i c Sub Pr ocedur e Mi gr at eCar t ( ol dCar t I d As St r i ng,
NewCar t I d As St r i ng)

n Conference.CustomersDB.Login() validates an e-mail name and password
pair against credentials stored in the customers table of the database. If the
e-mail name and password pair is valid, the method returns the customer ID.
In the case of an invalid e-mail name and password pair, this method returns
an empty string.
Publ i c Funct i on Logi n( emai l As St r i ng, passwor d As St r i ng)
As St r i ng



Note
Module 7: Creating a Microsoft ASP.NET Web Application 43


To connect to a data source
1. Open the file Login.aspx in the folder InetPub\wwwRoot\ASPNET.
2. In the cmdLogin_Click event procedure, declare the variables as shown in
the following table.
Variable name Data Type

shoppingCart New Conference.ShoppingCartDB
strTempCartID String
accountSystem New Conference.CustomersDB
strCustomerID String

3. Call the Login method of the accountSystem object and store the returned
customer ID in the variable strCustomerID. Pass the e-mail name and
password to the Login method:
Your code should look like the following:
st r Cust omer I d = _
account Syst em. Logi n( t xt Emai l . Val ue, t xt Passwor d. Val ue)

4. If the returned CustomerID is empty, this indicates that the user is not
authorized to log on. Output a "login failed" message in the spnInfo label.
5. If the returned CustomerID is not empty, the user is authorized to log on and
you need to migrate the contents of the temporary shopping cart to a
permanent one by performing the following operations:
a. Get the shopping cart ID by using the GetShoppingCartId method of
the shoppingCart object and store it in the strTempCartID variable.
b. Migrate any existing temporary shopping cart items to the permanent
shopping cart by using the MigrateCart method of the shoppingCart
object. Pass the temporary shopping cart ID and the customer ID to the
method.
c. Create a non-persistent cookie and direct the user back to the Login page
by calling the RedirectFromLoginPage method of the
FormsAuthentication object.
Your code should look like the following:
I f ( st r Cust omer I d <> " " ) Then
' Get t he ol d Shoppi ng Car t I D
st r TempCar t I D = shoppi ngCar t . Get Shoppi ngCar t I d( )

' Mi gr at e exi st i ng shoppi ng car t i nt o
' per manent shoppi ng car t
shoppi ngCar t . Mi gr at eCar t ( st r TempCar t I D, st r Cust omer I d)

' Redi r ect br owser back t o or i gi nat i ng page
For msAut hent i cat i on. Redi r ect Fr omLogi nPage( _
st r Cust omer I d, f al se)
El se ' Logi n f ai l ed
spnI nf o. i nner HTML = "Logi n Fai l ed"
End I f



44 Module 7: Creating a Microsoft ASP.NET Web Application


To save and test your work
1. Save your changes to login.aspx.
2. By using Internet Explorer, go to the Login page of the ASPNET Web site
by viewing http://localhost/ASPNET/Login.aspx
3. Fill out the e-mail field with someone@microsoft.com with a blank
password and click Sign In Now.
You will get the Login Failed message.
4. Fill in the password field with the value password and click Sign In Now.
You will be redirected to the default page of the ASPNET Web site,
default.aspx.

The e-mail name and password pair
someone@microsoft.com/password is already in the database.



Note
Module 7: Creating a Microsoft ASP.NET Web Application 45


Exercise 3
Retrieving Cookie Data in ASP.NET Pages
In this exercise, you will add code to the GetID.aspx page that reads the
customer ID (also known as Cart ID) from the authentication cookie. If the
customer has not been authenticated, you will use a temporary ID. The
GetID.aspx page is not directly linked to the ASPNET Web site. Instead, it
simply reads the customer ID or temporary ID and displays it.
To read the customer ID
1. Add the GetID.aspx page to the ASPNET Web site.
a. On the Project menu, click Add Existing Item.
b. In the Add Existing Item dialog box, navigate to the
<install folder>\Labs\Lab07\Starter folder.
c. Select the GetID.aspx file, and then click Open.

You will be asked if you want to create a new class file. Click No.

2. Open the GetID.aspx file.
3. Locate the comment:
' TO DO: Read t he cust omer I D

4. Test the value of User.Identity.Name.
5. If the string is not empty (""), output the value of User.Identity.Name using
Response.write.

Note
46 Module 7: Creating a Microsoft ASP.NET Web Application


6. If the string is empty, the user has not previously been authenticated.
a. Read the value of the Conference_CartID cookie. This cookie is issued
the first time a non-authentic ated user accesses the shopping cart.
b. If the cookie is not empty, output the value of the Conference_CartID
cookie.
c. If the cookie is empty, output a message that says that the customer is
not authenticated, and has not yet accessed the shopping cart.
Your code should look like the following:
I f User . I dent i t y. Name <> " " Then
Response. wr i t e( " Cust omer I D f r omaut hent i cat i on " & _
"cooki e: <br >")
Response. wr i t e( User . I dent i t y. Name)
El se
I f Request . Cooki es( " Conf er ence_Car t I D" ) I s Not hi ng Then
Response. wr i t e( " Cust omer not aut hent i cat ed " & _
"and has not accessed t he shoppi ng car t yet ")

El se
Response. wr i t e( " Tempor ar y Cust omer I D st or ed " & _
" i n a cooki e: <br >" )
Response. wr i t e( _
Request . Cooki es( " Conf er ence_Car t I D" ) . Val ue)

End I f
End I f

To save and test your work
1. Save your changes to GetID.aspx.
2. Start a new instance of Internet Explorer and go to the GetID.aspx page by
viewing http://localhost/ASPNET/GetID.aspx
You should be able to see the message stating that the customer is not
authenticated and has not yet accessed the shopping cart.
3. Click Go to Home Page.
4. Select an item and add it to the shopping cart.
5. Go back to the GetID.aspx page and click Refresh.
You should see the message that a temporary customer ID is stored in a
cookie, as well as the value of the temporary ID.
6. Click Go to Login Page.
7. Enter a valid e-mail name and password, and then click Sign In Now. For
this lab, use someone@microsoft.com for the user name and password for
the password.
8. Go back to the GetID.aspx page, and click Refresh.
You should see the message that the customer ID is from an authentication
cookie and the value of the Customer ID.


Module 7: Creating a Microsoft ASP.NET Web Application 47


To view the GetShoppingCartId method
1. Open the ShoppingCartDB.vb file in the Components folder of the ASPNET
Web site.
2. Locate the GetShoppingCartID method.
This method returns an ID to be used for adding items to a shopping cart in
the database. The method returns the value of the authenticated user, the
value stored in the Conference_CartID cookie, or a new temporary ID
created by calling Guid.NewGuid.


48 Module 7: Creating a Microsoft ASP.NET Web Application


Exercise 4
Using Forms Authentication in Register.aspx
In this exercise, you will add a new customer to the database. Next, you will
create an authentication cookie for the new customer. Afterward, you will
transfer the content of the temporary shopping cart into the new customers
permanent shopping cart and redirect to the shopping cart page
(ShoppingCart.aspx).
As you did in the previous exercise, you will call two different components: the
first, named Conference.ShoppingCartDB, is used to manipulate the shopping
cart; the second, Conference.CustomersDB is used to access to the customer
information.
You will need to call the Conference.CustomersDB.AddCustomer() method,
which inserts a new customer record into the customers database. This method
returns a unique Customer ID.
Publ i c Funct i on AddCust omer ( f ul l Name As St r i ng, emai l As
St r i ng, passwor d As St r i ng) As St r i ng

To connect to a data source
1. Open the file Register.aspx in the folder InetPub\wwwRoot\ASPNET.
2. Delete the following ins truction from the cmdValidation_Click event
procedure:
Response. Redi r ect ( " val i dOK. aspx" )

3. In the cmdValidation_Click event procedure, declare the following
variables:
Variable Name Data Type

shoppingCart New Conference.ShoppingCartDB
strTempCartID String
accountSystem New Conference.CustomersDB
strCustomerID String

4. Call the GetShoppingCartId method of the shoppingCart object to read
the current shopping cart ID. Save the value in the strTempCartID variable.
5. Create a new customer in the Customers table of the database by calling the
AddCustomer method of the accountSystem object. Save the created
customer ID in the strCustomerID variable.
Your code should look like the following:
st r Cust omer I d = _
account Syst em. AddCust omer ( t xt Ful l Name. Text , _
t xt Emai l . Text , t xt Passwor d. Text )

Use the Text property of these controls because they are Web
controls.


Note
Module 7: Creating a Microsoft ASP.NET Web Application 49


6. If the returned CustomerID is not empty, the user was added to the database
and you need to migrate the items in the temporary shopping cart to the
permanent shopping cart:
a. Authenticate a non-persistent cookie by passing the strCustomerID
parameter to the SetAuthCookie method.
b. Get the shopping cart ID by using the GetShoppingCartId method of
the shoppingCart object and store it in the strTempCartID variable.
c. Migrate any existing shopping cart items to the permanent shopping cart
by using the MigrateCart method of the shoppingCart object. Pass the
temporary cart ID and the customer ID to the MigrateCart method.
d. Redirect the user to the shoppingCart.aspx page he or she came from by
calling the Navigate method of the Page object.
Your code should look like the following:
I f ( st r Cust omer I d <> " " ) Then
' Set t he user ' s aut hent i cat i on name t o t he cust omer I d
For msAut hent i cat i on. Set Aut hCooki e( st r Cust omer I d, Fal se)

' Mi gr at e any exi st i ng shoppi ng car t i t ems i nt o
' t he per manent shoppi ng car t
shoppi ngCar t . Mi gr at eCar t ( st r TempCar t I D, st r Cust omer I d)

' Redi r ect br owser back t o shoppi ng car t page
Response. Redi r ect ( "Shoppi ngCar t . aspx")
End I f


To save and test your work
1. Save your changes to Register.aspx.
2. Using Internet Explorer, go to the register page of the ASPNET Web site by
viewing http://localhost/ASPNET/register.aspx
3. Create a new user with your full name, your e-mail address, and a password,
and then click Submit.
4. To verify whether this new user was successfully registered, open the Login
page by viewing http://localhost/ASPNET/login.aspx. Enter the e-mail
address and password of the new user you just registered, and then click
Sign In Now!
You should receive validation and be redirected to the home page of the
ASPNET Web site, default.aspx.


50 Module 7: Creating a Microsoft ASP.NET Web Application


Review
n Requirements of a Web Application
n What Is New in ASP.NET?
n Sharing Information Between Pages
n Securing an ASP.NET Application

*****************************illegal for non-trainer use******************************
1. How do you set up a Web application to use cookie-less sessions?


2. Where is global.asax file of an application located?


3. Where is the web.config file for an application located?


4. In web.config, all configuration information must reside under what tags?



Module 7: Creating a Microsoft ASP.NET Web Application 51


5. How do you specify which authentication method will be used by an
ASP.NET application?


6. What is the difference between output cache and ASP.NET cache?


7. How can you secure an entire application?





THIS PAGE INTENTIONALLY LEFT BLANK

Vous aimerez peut-être aussi