Workbook Introduction to Microsoft® ASP.NET

Introduction to Microsoft
ASP.NET
®
Workbook
Course Number: 2063B
Part Number: X08-50211
Released: 09/2001
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 introduc ed 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
Contents
iii
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 Scrip ting 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 courserelated 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.
Introduction
Contents
Introduction
1
Course Materials
Prerequisites
2
3
Course Objectives
4
Course Outline
5
Setup
7
Lab Overview
8
Lab Demonstration
11
Microsoft Certified Professional Program
13
Facilities
15
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
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******************************
1
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.
Note 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 course’s
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 [email protected].
Introduction
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)
3
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 serverside 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 developer’s 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.
Note If you performed a default installation of the course files,
<install folder> will be c:\Program Files\Msdntrain\2063.
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.
Lab file
is used in
File name
Purpose
_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 preconference 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.
Lab file
is used in
File name
Purpose
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.
Note 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.
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.
Note A valid user name and password that you can use on the login.aspx
page is: [email protected], 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.
Note 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.
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)
For More Information 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 [email protected] if you have specific
certification questions.
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/
Important 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 products— MSDN Training courses
help get you started.
Introduction
Facilities
Class Hours
*****************************illegal for non-trainer use******************************
Building Hours
Phones
Parking
Messages
Rest Rooms
Smoking
Meals
Recycling
15
THIS PAGE INTENTIONALLY LEFT BLANK
Module 1: Working with
Microsoft ASP.NET
Contents
Overview
Introducing ASP.NET
1
2
Creating Web Forms
11
Adding ASP.NET Code to a Page
Handling Page Events
23
30
Discussion: ASP vs. ASP.NET
35
Lab 1: Using ASP.NET to Output Text
Review
36
42
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
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 enterpriseclass 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.
1
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 AS P.NET.
Module 1: Working with Microsoft ASP.NET
The Microsoft .NET Framework
Web
Services
Services
User
Interface
ADO.NET: Data & XML
Base Class Library
Visual Studio.NET
Orchestration
Orchestration
.NET
.NET
Framework
Internet
Internet
COM+
Common Language Runtime
.NET
Enterprise
Servers
Building
Block
Block
Services
Windows
*****************************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, languageindependent 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
3
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.
Note 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.
Module 1: Working with Microsoft ASP.NET
Classes and Namespaces
ASP.NET includes a range of useful classes and namespaces. Namespaces are
used as an organizational system— a 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.
Note 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 user’s 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 company’
s internal inventory
management applications.
Web services provide the building blocks for constructing distributed Webbased 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.
7
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 cookieless 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 site’s 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 site’s 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
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.
11
12
Module 1: Working with Microsoft ASP.NET
What Are Web Forms?
n
.aspx extension
n
@Page Directive
<%@
<%@ Page
Page Language="vb"
Language="vb" %>
%>
n
Framework Is an Object Model
n
Denoted by the runat="server" Attribute
<Form
<Form runat="server">
runat="server">
</Form>
</Form>
n
Contain Client-side and Server-side Code
n
Contain HTML and Server Controls
*****************************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 AS P. 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
n
13
A Web form is denoted by the runat="server" attribute
The runat="server" attribute ensures that the form is executed at the server.
<Form runat="server">
</Form>
n
Contain client-side and server-side code
In the previous versions of ASP, controls on forms could invoke only clientside 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.
Note ASP.NET and ASP pages can coexist on the same machine. The file
extension determines only whether ASP or ASP.NET processes it.
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 control’s tag. For
example, the following is an HTML input box, turned into a server control:
<INPUT TYPE="TEXT" runat="server">
Note 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.
16
Module 1: Working with Microsoft ASP.NET
Types of Server Controls
n
HTML Controls
l
Exist within the System.Web.UI.HtmlControls
namespace
<input
<input type="text"
type="text" id="txtName"
id="txtName" runat="server">
runat="server">
<span
<span id="spnStarter"
id="spnStarter" runat="server">
runat="server">
starter</span>
starter</span>
n
Web Controls
l
Exist within the System.Web.UI.WebControls
namespace
<asp:TextBox
<asp:TextBox id="txtName"
id="txtName" runat="server"
runat="server"
Text="[Entry
Keywords]"/>
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:
<input type="text" runat="server" id="txtName" value="some
text">
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 id="spnStarter" runat="server">starter text</span>
The HTML controls exist in the System.Web.UI.HtmlControls namespace.
Note 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 tags— that is, tags
with a prefix. The prefix is used to map the tag to the namespace of the runtime 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:TextBox id="txtName" runat="server" Text="[Entry
Keywords]"></asp:TextBox>
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.
18
Module 1: Working with Microsoft ASP.NET
How Do Server Controls Work?
n
Declared with runat="server" Attribute
<input
<input type="text"
type="text" id="text2"
id="text2" runat="server">
runat="server">
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
*****************************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.
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 runat="server">
Name: <INPUT type="text" runat="server">
<p>Profession: <SELECT runat="server">
<OPTION> Software Engineer </OPTION>
<OPTION> Software Tester </OPTION>
<OPTION> Program Manager </OPTION>
</SELECT>
<p><INPUT type="Submit" Value="Save" runat="server">
</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.
20
Module 1: Working with Microsoft ASP.NET
This is the HTML that is returned to the browser:
<FORM name="ctrl1" method="post" action="server_controls.aspx"
id="ctrl1">
<INPUT type="hidden" name="__VIEWSTATE"
value="a0z-1466413384__x">
Name: <INPUT value="Jane" name="ctrl3" type="text">
<p>
Profession:
<SELECT name="ctrl5">
<OPTION value="Software Engineer">
Software Engineer</OPTION>
<OPTION value="Software Tester">
Software Tester</OPTION>
<OPTION selected value="Program Manager">
Program Manager</OPTION>
</SELECT>
<p>
<input type="submit" value="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:label id="label1" runat="server"/>
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.
Note 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.
<input type="text" runat="server">
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.
Module 1: Working with Microsoft ASP.NET
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.
23
24
Module 1: Working with Microsoft ASP.NET
Creating an ASP.NET <SCRIPT> Section
n
Declaring the Language
<script
<script language="VB"
language="VB" runat="server">
runat="server">
<script
<script language="C#"
language="C#" runat="server">
runat="server">
n
Declaring Functions and Subroutines
<SCRIPT
<SCRIPT LANGUAGE="VB"
LANGUAGE="VB" runat="server">
runat="server">
Sub
Sub login
login ()
()
'contents
'contents of
of routine
routine
End
Sub
End Sub
</SCRIPT>
</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.
<SCRIPT LANGUAGE="VB" runat="server">
In ASP.NET, you declare functions and sub-procedures within the <SCRIPT>
tags.
<SCRIPT LANGUAGE="VB" runat="server">
Sub login()
'contents of routine
End Sub
</SCRIPT>
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:
objThis is objThat
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.Write (“Hello”)
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.
Dim strName as String
Dim strTitle, strAddress as String
You can turn on Option Explicit by setting the Explicit attribute of the
@Page direc tive to true.
<%@Page Language="vb" Explicit="true" %>
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:
Dim X As Integer = 1
is equivalent to these statements:
Dim X As Integer
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 errorhandling 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()
Try
Open "TESTFILE" For Output As #1
Write #1, CustomerInformation
Catch
Kill "TESTFILE"
Finally
Close #1
End try
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
<input
<input type="submit"
type="submit" value="Submit!"
value="Submit!"
onServerClick="GreetMe"
onServerClick="GreetMe" runat="server">
runat="server">
n
Create an Event Procedure in Your Page Code
Sub
Sub GreetMe(s
GreetMe(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
n
Access Properties of Controls in the Event Procedure
Sub
Sub GreetMe(s
GreetMe(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
spnGreeting.InnerHTML
=
"Hello
spnGreeting.InnerHTML = "Hello "" && __
txtName.Value
txtName.Value
End
End Sub
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:
<input type="submit" value="Submit!"
onServerClick="GreetMe" runat="server">
Note OnClick is a client-side event, whereas OnServerClick is a serverside 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 GreetMe(s As Object, e As EventArgs)
spnGreeting.InnerHTML = "Hello " & txtName.Value
End Sub
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 img_OnClick(s As Object, e As ImageClickEventArgs)
label1.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.
<input type="submit" onserverclick="GreetMe"
value="Save" runat="server">
4. Create a SCRIPT section for server -side code.
<SCRIPT language="VB" runat="server">
5. Create the GreetMe sub-procedure.
Sub GreetMe(s As Object, e As EventArgs)
label1.Text = "Hello " & txtName.Value & _
". I see your occupation is " & lstTitle.Value
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_Init
Page_Init
Page_Load
Page_Load
Textbox1_Changed
Textbox1_Changed
Button1_Click
Button1_Click
Page_Unload
Page_Unload
Page is disposed
*****************************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 Object, e As EventArgs)
txtName.Text = 'value from database
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_Unload(s As Object,e As EventArgs)
MyApp.LogPageComplete()
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
Sub Page_Load(s
Page_Load(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
If
Not
Page.IsPostBack
Then
If Not Page.IsPostBack Then
'executes
'executes only
only on
on initial
initial page
page load
load
End
End If
If
'Rest
'Rest of
of procedure
procedure executes
executes on
on every
every request
request
End
End Sub
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 Object,e As EventArgs)
If Not Page.IsPostBack Then
'executes only on initial page load
txtComment.Value = "initial value"
End If
'Rest of procedure executes on every request
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 Object, e As EventArgs)
txtName.Value = "Enter 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.
If Not Page.IsPostBack Then
txtName.Value = "Enter your name"
End If
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
Discussion: ASP vs. ASP.NET
*****************************illegal for non-trainer use******************************
35
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.
Note 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.
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.
Note 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 follow ing:
<script language="VB" runat="server">
</script>
å 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.
Module 1: Working with Microsoft ASP.NET
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:
<form id="WebForm1" method="post" runat="server">
Email:<br>
<input type="text" id="txtEmail" runat="server">
<br><br>
What kind of mail client do you use:<br>
<select id="selMailClient" runat="server">
</select>
<br><br>
Password:<br><input type="password" id="txtPassword"
runat="server"><br><br>
<input type="submit" value="Sign In Now"
runat="server">
<span id="spnInfo" runat="server"> </span>
</form>
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:
<select id="selMailClient" runat="server">
<option selected>Microsoft Outlook</option>
<option>Microsoft Outlook Express</option>
<option>Web-based</option>
</select>
39
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 cmdLogin_Click(s As Object, e As EventArgs)
spnInfo.innerHTML = spnInfo.innerHTML & _
"Your email: " & _
txtEmail.Value & _
"<br>Your mail client is: " & _
selMailClient.Value & _
"<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
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 Object, e As EventArgs)
spnInfo.innerHTML = spnInfo.innerHTML & _
"One more Page_Load event!<br>" & _
"Page.IsPostBack=" & _
Page.IsPostBack.ToString() & _
"<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.
41
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
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?
43
THIS PAGE INTENTIONALLY LEFT BLANK
Module 2: Using
Web Controls
Contents
Overview
1
What Are Web Controls?
2
Using Intrinsic Controls
4
Using Input Validation Controls
Selecting Controls for Applications
16
28
Lab 2: Using Web Controls
29
Review
40
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.
Note 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.
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:Button runat="server" />
Note 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.
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
What Are Intrinsic Controls?
n
Provide Standard Naming Convention, with
Standard Properties for Controls
<asp:RadioButton
<asp:RadioButton BackColor="red"
BackColor="red" Text="
Text=" "...
"... />
/>
<asp:CheckBox
<asp:CheckBox BackColor="red"
BackColor="red" Text="
Text=" "...
"... />
/>
n
Include Properties Specific to the Control
<asp:CheckBox
<asp:CheckBox Checked="True"
Checked="True" ...
... />
/>
n
Create Browser-Specific HTML
<span>
<span>
<input
<input type="checkbox"
type="checkbox" id="ctrl1"
id="ctrl1"
checked="true"
checked="true" name="ctrl1">
name="ctrl1">
<label
<label for="ctrl1">Standard</label>
for="ctrl1">Standard</label>
</span>
</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 runat="server" Text="Label1"></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.
<input type ="radio">
<input type ="checkbox">
<input type ="submit">
All of these controls are input controls; however, they all behave in different
ways.
5
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:RadioButton>
<asp:CheckBox>
<asp:Button>
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:textbox id="txtName" Text="Jane" BackColor="red"
runat="server" />
<asp:Button id="btnSubmit" Text="Submit" BackColor="cyan"
runat="server" />
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="True" Text="Standard" runat="server" />
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>
<input type="checkbox" id="ctrl1" checked="true" name="ctrl1">
<label for="ctrl1">Standard</label>
</span>
8
Module 2: Using Web Controls
List of Intrinsic Controls
n
List of Intrinsic Controls
<asp:textbox>
<asp:hyperlink>
<asp:image>
<asp:panel>
<asp:button> <asp:checkbox>
<asp:linkbutton> <asp:imagebutton>
<asp:label>
<asp:radiobutton>
<asp:table>
<asp:dropdownlist
<asp:dropdownlist id="favColor"
id="favColor" runat="server">
runat="server">
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Red</asp:listitem>
<asp:listitem>Red</asp:listitem>
<asp:listitem>Green</asp:listitem>
<asp:listitem>Green</asp:listitem>
</asp:dropdownlist>
</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:textbox>
<asp:button>
<asp:imagebutton>
<asp:checkbox>
<asp:radiobutton>
<asp:listbox>
<asp:dropdownlist>
<asp:hyperlink>
<asp:image>
<asp:label>
<asp:panel>
<asp:table>
<input type=text>
<input type=submit>
<input type=image>
<input type=checkbox>
<input type=radiobutton>
<select size="5"> </select>
<select> </select>
<a href="…"> </a>
<img src="…">
<span> </span>
<div> </div>
<table> </table>
Module 2: Using Web Controls
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:dropdownlist id="favColor" runat="server">
<asp:listitem>Blue</asp:listitem>
<asp:listitem>Red</asp:listitem>
<asp:listitem>Green</asp:listitem>
</asp:dropdownlist>
Label
You can add a label control to a form as follows:
<asp:Label runat="server" Text="Label1" FontItalic="true"></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 runat="server" Text="CheckBox1"
Checked="True"></asp:CheckBox>
For more information about the properties and events associated with the
intrinsic controls, see the .NET Framework SDK documentation.
9
10
Module 2: Using Web Controls
Handling Intrinsic Control Events
<asp:button
<asp:button id="btn"
id="btn" runat="server"
runat="server"
onclick="btn_Click"
onclick="btn_Click" />
/>
Sub
Sub btn_Click(s
btn_Click(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
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
*****************************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 control’s tag,
and then write the event procedure itself.
For example, you set up a click event for a button control as follows:
<asp:button id="btn" runat="server" onclick="btn_Click" />
Note The button Web control has only an OnClick event, not an
OnServerClick event.
You then write the event procedure as follows:
Sub btn_Click(s As Object, e As EventArgs)
End Sub
Module 2: Using Web Controls
11
For more information on the events available for intrinsic controls, see the
Microsoft .NET Framework SDK documentation.
Note 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:dropdownlist id="lstTitle" runat="server"
onSelectedIndexChanged="lst_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.
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
<asp:DropDownList
<asp:DropDownList id="lstLocation"
id="lstLocation"
autoPostBack="True"
autoPostBack="True" runat="server"
runat="server" >>
You
You selected:
selected: <asp:Label
<asp:Label id="SelectedValue"
id="SelectedValue"
Text="<%#
Text="<%# lstLocation.SelectedItem.Text
lstLocation.SelectedItem.Text %>"
%>"
runat="server"
runat="server" />
/>
n
Data Binding
Sub
Sub Page_Load
Page_Load (s
(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
SelectedValue.DataBind()
SelectedValue.DataBind()
End
End Sub
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 id="SelectedValue" runat="server"
Text="<%# lstLocation.SelectedItem.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.
<script language="VB" runat="server">
Sub Page_Load (Sender As Object, E As EventArgs)
SelectedValue.DataBind()
End Sub
</script>
<form runat="server">
<asp:DropDownList id="lstLocation"
autoPostBack="true" runat="server" >
<asp:listitem>Boston</asp:listitem>
<asp:listitem>New York</asp:listitem>
<asp:listitem>London</asp:listitem>
<asp:listitem>Amsterdam</asp:listitem>
</asp:dropdownlist>
<p>You selected: <asp:Label id="SelectedValue"
Text="<%# lstLocation.SelectedItem.Text %>"
runat="server" />
</p>
</form>
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:
SelectedValue.Text=lstLocation.SelectedItem.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
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:label id="lblListbox" runat="server"/>
3. Bind the label control to the list box by setting its Text attribute.
<asp:label id="lblListbox"
Text="<%# lstTitle.SelectedItem.Text %> " runat="server"/>
4. Create a Page_Load event and call lblListbox.DataBind()
Sub Page_Load(s As Object, e As EventArgs)
lblListbox.DataBind()
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.
15
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.
Note 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.
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:textbox
<asp:textbox id="txtName"
id="txtName" runat="server"
runat="server" />
/>
<asp:RequiredFieldValidator
<asp:RequiredFieldValidator id="txtNameValidator"
id="txtNameValidator"
runat="server"
runat="server"
controlToValidate="txtName"
controlToValidate="txtName"
errorMessage="You
errorMessage="You must
must enter
enter your
your name"
name"
display="dynamic">
display="dynamic">
</asp:RequiredFieldValidator>
</asp:RequiredFieldValidator>
*****************************illegal for non-trainer use******************************
The standard code used to add input validation controls to a form is as follows:
<asp:type_of_validator id="validator_id" runat="server"
controlToValidate="control_id"
errorMessage="error_message_for_summary"
display="static|dynamic|none">
</asp:type_of_validator>
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:textbox id="txtName" value="Enter your name"
runat="server" />
<asp:RequiredFieldValidator id="txtNameValidator"
runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
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
validation— MinimumValue, 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:textbox id="txtAge" value="Enter your age" runat="server"
/>
<asp:RangeValidator id="txtAgeValidator" runat="server"
controlToValidate="txtAge"
type="Integer"
minimumValue="18"
maximumValue="50"
errorMessage="Applicants must be between 18 and 50"
display="dynamic">
</asp:RangeValidator>
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
n
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.
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:textbox id="txtAge" runat="server" />
<asp:CompareValidator id="txtAgeCompareValidator"
runat="server"
ControlToValidate="txtAge"
ValueToCompare="0"
Type="Integer"
Operator="GreaterThanEqual"
ErrorMessage="Please enter a whole number zero or greater.">
</asp: CompareValidator >
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:textbox id="txtSSN" runat="SERVER" />
<asp:RegularExpressionValidator id="txtZIP_validation"
runat="server"
ControlToValidate="txtSSN"
ErrorMessage="Use the format 123-12-1234."
ValidationExpression="[0-9]{3}-[0-9]{2}-[0-9]{4}">
</asp:RegularExpressionValidator>
Module 2: Using Web Controls
Validating an Entire Page
n
Page.IsValid Property
Sub
Sub Submit_click
Submit_click (s
(s AA Object,
Object, ee As
As EventArgs)
EventArgs)
If
Page.IsValid
Then
If Page.IsValid Then
Message.Text
Message.Text == "Page
"Page is
is valid!"
valid!"
End
If
End If
End
End Sub
Sub
n
ValidationSummary Control
<asp:ValidationSummary
<asp:ValidationSummary id="valSummary"
id="valSummary"
runat="server"
runat="server"
headerText=
headerText= "These
"These errors
errors were
were found:"
found:"
showSummary="True"
showSummary="True"
displayMode="List"
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 Submit_click (s A Object, e As EventArgs)
If Page.IsValid Then
Message.Text = "Page is valid!"
End If
End Sub
Note The validation can be either client-side or server-side, depending on the
browser.
23
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:ValidationSummary id="valSummary" runat="server"
headerText="These errors were found:"
showSummary="True"
displayMode="List" />
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:RequiredFieldValidator id="txtNameValidator"
runat="server"
controlToValidate="txtName"
errorMessage="You must enter your name"
display="dynamic">
</asp:RequiredFieldValidator>
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 clientside 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:RangeValidator id="txtNameRngValidator" runat="server"
controlToValidate="txtName"
errorMessage="Please enter a name that begins with 'A'"
type="String"
minimumValue="A"
maximumValue="B"
display="dynamic">
</asp:RangeValidator>
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
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.
n
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.
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 clientside validation and behavior.
27
28
Module 2: Using Web Controls
Selecting Controls for Applications
Use Web Controls When:
Use HTML Controls When:
l
You prefer a Visual
Basic-like programming
model
l
You prefer an HTMLlike object model
l
You are writing a page
that might be used by a
variety of browsers
l
You are working with
existing HTML pages
and want to quickly add
Web Forms functionality
l
You need specific
functionality such as a
calendar or ad rotator
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
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.
29
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 reservation button -->
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:button
id="cmdOK"
Text="Reserve"
OnClick="cmdSubmit_Click"
runat="server"
/>
å To add a label
1. Locate the following comment:
<!-- TO DO: add a confirmation label -->
2. Create a label Web control.
•
Set the ID and Runat attributes.
Your code should look like the following:
<asp:Label
id="lblReservationConfirmation"
runat="server"
/>
32
Module 2: Using Web Controls
å To add a drop down list
1. Locate the following comment:
<!-- TO DO: add a second DropDownList -->
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:DropDownList
id="lstRoomType2"
runat="server">
<asp:ListItem selected="true">No Smoking</asp:ListItem>
<asp:ListItem>Smoking</asp:ListItem>
</asp:DropDownList>
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 calendar control for the ending date -->
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:Calendar id="calEndingDate" runat="server"
BackColor="#9FC89F" ForeColor="#313179"
BorderWidth="3"
BorderStyle="Solid" BorderColor="#313179"
CellSpacing="2" CellPadding="2"
ShowGridLines="true"
TitleStyle-BackColor="white"
TitleStyle-ForeColor="black"
/>
å To validate start and end date selections
1. Locate the following comment:
'TO DO: validate start and end date selections
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.
Note 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.
34
Module 2: Using Web Controls
Your code should look like the following:
' Test if the date range is valid
If calEndingDate.SelectedDate <= _
calStartingDate.SelectedDate Then
lblReservationConfirmation.Text = _
"The end date cannot be before the start date."
Else
lblReservationConfirmation.Text = _
"Congratulations. There is an available room " & _
"for you.<br>" & _
"Room type: " & _
lstRoomType1.SelectedItem.Text & ", " & _
lstRoomType2.SelectedItem.Text & "<br>" & _
"from: " & _
calStartingDate.SelectedDate.ToShortDateString() & _
" to " & _
calEndingDate.SelectedDate.ToShortDateString()
End If
å 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: validate txtFullName control-->
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:RequiredFieldValidator
id="valFullName"
runat="server"
controlToValidate="txtFullName"
errorMessage="Full Name is a required field."
initialValue=""
display="static">
*
</asp:RequiredFieldValidator>
36
Module 2: Using Web Controls
å To validate the e-mail text box
1. Locate the following comment:
<!-- TO DO: validate txtEmail control -->
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:RegularExpressionValidator
id="valEmailExpr"
runat="server"
validationExpression=".+@.+\..+"
controlToValidate="txtEmail"
errorMessage="E-mail syntax is incorrect."
display="dynamic">
*
</asp:RegularExpressionValidator>
Module 2: Using Web Controls
37
å To compare the values in the txtPassword and txtConfirmPassword
text boxes
1. Locate the following comment
<!-- TO DO: password comparison -->
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:CompareValidator
id="valComparePassword"
runat="server"
controlToValidate="txtConfirmPassword"
controlToCompare="txtPassword"
errorMessage="Password fields do not match."
Display="dynamic">
*
</asp:CompareValidator>
å 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: validation summary -->
2. Create a ValidationSummary control to summarize the validity of all
validation controls on the form.
Your code should look like the following:
<asp:validationsummary
id="valSummary"
runat="server" />
å 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: test if the page is valid
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:
If Page.IsValid Then
Response.Redirect("validOK.aspx")
End If
Module 2: Using Web Controls
å 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.
39
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
5. What validation control would you use to validate a phone number?
6. Why would you use the ValidationSummary control?
41
THIS PAGE INTENTIONALLY LEFT BLANK
Module 3: Using
Microsoft ADO.NET to
Access Data
Contents
Overview
Overview of ADO.NET
1
2
Connecting to a Data Source
11
Accessing Data with DataSets
Using Stored Procedures
13
28
Lab 3: Using ADO.NET to Access Data
37
Accessing Data with DataReaders
Binding to XML Data
46
53
Review
59
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizatio ns, 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
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 .
Note 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.
1
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 ADO’s 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
.ASPX Page
DataReader
Command
Company:
Company:
Northwind
Northwind Traders
Traders
Database
Database
Connection
DataAdapter
DataView
DataView
DataSet
.ASPX Page
List-Bound
List-Bound
Control
Control
*****************************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 DataView to
specify criteria for filtering and sorting a DataSet.
Note A DataSet is not a recordset. A DataView is more analogous to a
recordset.
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
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
*****************************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 JOIN query, 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
Using Namespaces
n
Use the Import Construct to Declare Namespaces
<%@
<%@
<%@
<%@
n
Import
Import Namespace="System.Data"
Namespace="System.Data" %>
%>
Import
Namespace="System.Data.SqlClient"
Import Namespace="System.Data.SqlClient" %>
%>
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
*****************************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.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
9
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
Dim
Dim strConn
strConn As
As String
String == __
"server=localhost;
"server=localhost; uid=sa;pwd=;
uid=sa;pwd=; database=northwind"
database=northwind"
Dim
Dim conn
conn As
As SqlConnection
SqlConnection == New
New SqlConnection(strConn)
SqlConnection(strConn)
n
Using OleDbConnection
Dim
Dim strConn
strConn As
As String
String == "Provider=
"Provider= SQLOLEDB.1;
SQLOLEDB.1; "" && __
"Data
"Data Source=localhost;
Source=localhost; uid=sa;
uid=sa; pwd=;
pwd=; "" && __
"InitialCatalog=northwind;"
"InitialCatalog=northwind;"
Dim
Dim conn
conn As
As OleDbConnection
OleDbConnection == __
New
OleDbConnection(strConn)
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 commadelimited 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.
Dim strConn As String = _
"server=localhost;uid=sa;pwd=;database=northwind"
Dim conn As SqlConnection = New SqlConnection(strConn)
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.
Dim strConn As String = "Provider=SQLOLEDB.1; " & _
"Data Source=localhost; uid=sa; pwd=; " & _
"Initial Catalog=northwind;"
Dim conn As OleDbConnection = New OleDbConnection(strConn)
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
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.
13
14
Module 3: Using Microsoft ADO.NET to Access Data
Using DataSets to Read Data
n
Create the Database Connection
n
Store the Query in a SqlDataAdapter
Dim
Dim cmdAuthors
cmdAuthors As
As SqlDataAdapter
SqlDataAdapter
cmdAuthors
=
New
cmdAuthors = New SqlDataAdapter
SqlDataAdapter __
("select
("select ** from
from Authors",
Authors", conn)
conn)
n
Create and Populate the DataSet with DataTables
Dim
Dim ds
ds As
As DataSet
DataSet
ds
=
New
ds = New DataSet()
DataSet()
cmdAuthors.Fill(ds,
cmdAuthors.Fill(ds, "Authors")
"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.
'Create a connection
Dim conn As SqlConnection = New SqlConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
'Create the DataAdapter
Dim cmdAuthors As SqlDataAdapter = New SqlDataAdapter _
("select * from Authors", conn)
'Create and populate the DataSet
Dim ds As DataSet
ds= New DataSet()
cmdAuthors.Fill(ds, "Authors")
16
Module 3: Using Microsoft ADO.NET to Access Data
Storing Multiple Tables in a DataSet
n
Add the First Table
command
command == New
New SqlDataAdapter
SqlDataAdapter __
("select
*
from
("select * from Authors",
Authors", conn)
conn)
command.Fill(ds,
command.Fill(ds, "Authors")
"Authors")
n
Add the Subsequent Table(s)
command.SelectCommand
command.SelectCommand == New
New SQLCommand
SQLCommand __
("select
("select ** from
from Titles",
Titles", conn)
conn)
command.Fill(ds,
command.Fill(ds, "Titles")
"Titles")
Books
DataSet
Authors
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.
Note 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 DataSet()
SQL = "Select * from Authors"
command = New SqlDataAdapter (SQL, conn)
command.Fill(ds, "Authors")
2. Reset the SelectCommand, InsertCommand, or DeleteCommand
property of the DataAdapter object to a new Command object with a new
SQL statement.
command.SelectCommand = New SqlCommand _
("select * from Titles", conn)
3. Call Fill again.
command.Fill(ds, "Titles")
Module 3: Using Microsoft ADO.NET to Access Data
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.
Dim
Dim
Dim
Dim
Dim
strConn As String
conn As SqlConnection
SQL As String
command As SqlDataAdapter
ds As DataSet
'create connection to database
strConn = "server=localhost;uid=sa;pwd=;database=pubs"
conn = New SqlConnection(strConn)
'fill DataSet with first set of data
SQL = "Select * from Authors"
command = New SqlDataAdapter (SQL, conn)
ds = New DataSet()
command.Fill(ds, "Authors")
'fill DataSet with second set of data
SQL = "select * from Titles"
command.SelectCommand = New SqlCommand(SQL, conn)
command.Fill(ds, "Titles")
17
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
Dim
Dim dv
dv as
as DataView
DataView
dv
dv == ds.Tables("Authors").DefaultView
ds.Tables("Authors").DefaultView
n
Setting Up a Different View of a DataSet
Dim
Dim dv
dv as
as DataView
DataView
dv
dv == New
New DataView
DataView (ds.Tables("Authors"))
(ds.Tables("Authors"))
dv.RowFilter
dv.RowFilter == "state
"state == 'CA'"
'CA'"
*****************************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 DataView that 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:
Dim dv As DataView
dv = ds.Tables("Authors").DefaultView
Note 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.
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"
For more information on the properties of the DataView object, see the
Microsoft .NET Framework SDK documentation.
Module 3: Using Microsoft ADO.NET to Access Data
19
Displaying Data in the DataGrid Control
n
Create the Control
<asp:DataGrid
<asp:DataGrid id="dgAuthors"
id="dgAuthors" runat="server"
runat="server" />
/>
n
Bind to a DataSet
dgAuthors.DataSource=ds
dgAuthors.DataSource=ds
dgAuthors.DataMember="Authors"
dgAuthors.DataMember="Authors"
dgAuthors.DataBind()
dgAuthors.DataBind()
*****************************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:DataGrid id="dgAuthors" runat="server" />
To bind a DataSet to a DataGrid control, you first need to set the DataSource
property of the DataGrid to a DataSet, DataTable, or DataVieweither the
DefaultView property of a DataSet or a custom DataView objectand 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
dgAuthors.DataSource = ds
dgAuthors.DataMember = "Authors"
dgAuthors.DataBind()
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:
dgAuthors.DataSource = ds.Tables("Authors")
dgAuthors.DataBind()
If you want to display a different view of data in the DataGrid control, create a
new DataView object 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
Dim dv as DataView
dv = New DataView (ds.Tables("Authors"))
dv.RowFilter = "state = 'CA'"
dgAuthors.DataSource = dv
dgAuthors.DataBind()
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 DefaultView of 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
HeaderTemplate
HeaderTemplate
ItemTemplate
ItemTemplate
SeparatorTemplate
SeparatorTemplate
AlternatingItem
AlternatingItem
Template
Template
FooterTemplate
FooterTemplate
*****************************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 runat="server"
Text="<%#Container.DataItem.LstName %>"
/>
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 Templated Elements
<asp:Repeater
<asp:Repeater id="repList"
id="repList" runat="server">
runat="server">
<ItemTemplate>
<ItemTemplate>
<%#
<%# Container.DataItem("au_lname")
Container.DataItem("au_lname") %>
%>
</ItemTemplate>
</ItemTemplate>
</asp:Repeater>
</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:
replist.DataSource= ds
Replist.DataMember= "Authors"
replist.DataBind()
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:Repeater id="repList" runat="server">
<ItemTemplate>
<%# Container.DataItem("au_lname") %><BR>
</ItemTemplate>
</asp:Repeater>
Module 3: Using Microsoft ADO.NET to Access Data
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:Repeater id="repList" runat="server">
<HeaderTemplate>
<table>
<tr>
<td>Lastname</td>
<td>Firstname</td>
<td>State</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Container.DataItem("au_lname") %></td>
<td><%# Container.DataItem("au_fname") %></td>
<td><%# Container.DataItem("state") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
The following illustration shows the table created by the above sample code:
25
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.
<AlternatingItemTemplate>
<tr>
<td style="background-color: green">
<%# Container.DataItem("au_lname") %></td>
<td style="background-color: green">
<%# Container.DataItem("au_fname") %></td>
<td style="background-color: green">
<%# Container.DataItem("state") %></td>
</tr>
</AlternatingItemTemplate>
The following illustration shows the table with the AlternatingItemTemplate :
Module 3: Using Microsoft ADO.NET to Access Data
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 Repeater control, 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.
27
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
Dim
Dim cmd
cmd as
as SqlDataAdapter
SqlDataAdapter
cmd
=
New
cmd = New SqlDataAdapter()
SqlDataAdapter()
cmd.SelectCommand
cmd.SelectCommand == New
New SqlCommand()
SqlCommand()
With
With cmd.SelectCommand
cmd.SelectCommand
.Connection
.Connection == conn
conn
.CommandText
.CommandText == "ProductCategoryList"
"ProductCategoryList"
.CommandType
.CommandType == CommandType.StoredProcedure
CommandType.StoredProcedure
End
End With
With
n
Run the Stored Procedure and Store Returned Records
cmd.Fill
cmd.Fill (ds,
(ds, "Categories")
"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.
Procedure ProductCategoryList
As
SELECT CategoryID,CategoryName
FROM Categories
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:
Dim cmd as SqlDataAdapter
cmd = New SqlDataAdapter()
cmd.SelectCommand = New SqlCommand()
With cmd.SelectCommand
.Connection = conn
.CommandText = "ProductCategoryList"
.CommandType = CommandType.StoredProcedure
End With
Note You can directly set the connection and command text when creating the
SqlDataAdapter object:
cmd = New SqlDataAdapter("ProductCategoryList", 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.Fill(ds, "Categories")
After you have filled a DataTa ble with the results of a Select stored procedure,
you can bind it to a list-bound control to display the data.
Module 3: Using Microsoft ADO.NET to Access Data
31
Passing Parameters
n
Create Parameter, Set Direction and Value, Add to the
Parameters Collection
workParam
workParam == New
New SqlParameter("@CategoryID",
SqlParameter("@CategoryID", __
SQLDbType.Int)
SQLDbType.Int)
workParam.Direction
workParam.Direction == ParameterDirection.Input
ParameterDirection.Input
workParam.Value
workParam.Value == CInt(txtCatID.Text)
CInt(txtCatID.Text)
cmd.SelectCommand.Parameters.Add(workParam)
cmd.SelectCommand.Parameters.Add(workParam)
n
Run Stored Procedure
ds
ds == new
new DataSet()
DataSet()
cmd.Fill(ds,
cmd.Fill(ds, "Products")
"Products")
*****************************illegal for n o n-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:
Procedure ProductsByCategory (
@CategoryID int )
As
SELECT ProductID, ModelName, UnitCost, ProductImage,
Chairman
FROM Products
WHERE CategoryID=@CategoryID
To call the ProductsByCategory stored procedure, create an input parameter
named @CategoryID and set its value to the value of a text box.
Dim cmd as SqlDataAdapter
cmd = New SqlDataAdapter ()
cmd.SelectCommand = New SqlCommand()
With cmd.SelectCommand
.Connection = conn
.CommandText = "ProductCategoryList"
.CommandType = CommandType.StoredProcedure
End With
Dim workParam as SqlParameter
workParam = New SqlParameter("@CategoryID", SqlDbType.Int)
workParam.Direction = ParameterDirection.Input
workParam.Value = CInt(txtCatID.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.SelectCommand.Parameters.Add(workParam)
Use the Fill method to run the stored procedure and retrieve the records.
ds = new DataSet()
cmd.Fill(ds, "Products")
Module 3: Using Microsoft ADO.NET to Access Data
33
Calling Action Stored Procedures
n
Use SQLCommand Object
Dim
Dim myCmd
myCmd As
As SqlCommand
SqlCommand == New
New SqlCommand
SqlCommand __
("OrdersCount",
conn)
("OrdersCount", conn)
n
Call the ExecuteNonQuery Method
conn.Open()
conn.Open()
myCmd.ExecuteNonQuery()
myCmd.ExecuteNonQuery()
conn.Close()
conn.Close()
n
Retrieve Output Parameters
curSales
curSales == myCmd.Parameters("@ItemCount").Value
myCmd.Parameters("@ItemCount").Value
*****************************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 customer’s ID and returns the
number of outstanding orders that customer has:
Procedure OrdersCount (
@CustomerID int,
@ItemCount int OUTPUT )
As
SELECT @ItemCount=COUNT(OrderID)
FROM Orders
WHERE CustomerID=@CustomerID
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:
Dim myCmd As SqlCommand = New SqlCommand("OrdersCount", conn)
myCmd.CommandType = CommandType.StoredProcedure
'add an input parameter
workParam = New SqlParameter("@CustomerID", SqlDbType.Int)
workParam.Direction = ParameterDirection.Input
workParam.Value = CInt(txtCustID.Text)
myCmd.Parameters.Add (workParam)
'add an output parameter
workParam = New SqlParameter("@ItemCount", SqlDbType.Int)
workParam.Direction = ParameterDirection.Output
myCmd.Parameters.Add ( workParam)
'execute the stored procedure
conn.Open()
myCmd.ExecuteNonQuery()
conn.Close()
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:
curSales = myCmd.Parameters("@ItemCount").Value
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 lin e 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: read data from database
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:
Dim strConn As String
Dim conn As SqlConnection
strConn = _
"server=localhost;uid=sa;pwd=1Aspnet;database=Conf"
conn = New SqlConnection(strConn)
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:
Dim cmdProducts As SqlDataAdapter
cmdProducts = _
New SqlDataAdapter("ProductsByCategory", conn)
cmdProducts.SelectCommand.CommandType = _
CommandType.StoredProcedure
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:
Dim paramCategoryID As SqlParameter
paramCategoryID = _
new SqlParameter("@CategoryID", SqlDbType.Int, 4)
paramCategoryID.Value = categoryID
cmdProducts.SelectCommand.Parameters.Add(paramCategoryID)
å 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:
Dim dsProducts As New DataSet
cmdProducts.Fill(dsProducts, "Products")
å 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:
repList.DataSource = _
dsProducts.Tables("Products").DefaultView
repList.DataBind()
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
Note 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.
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.
<AlternatingItemTemplate>
</AlternatingItemTemplate>
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:
<td class="BackgroundColor6">
The AlternatingItemTemplate template should look like the following:
<AlternatingItemTemplate>
<tr>
<td class="BackgroundColor6">
<%# Container.DataItem("Chairman") %>
</td>
<td class="BackgroundColor5">
<a href='ProductDetails.aspx?productID=
<%# Container.DataItem("ProductID") %>'>
<%# Container.DataItem ("ModelName") %><br>
</a>
</td>
<td class="BackgroundColor6">
<b>Price: </b>
<%# System.String.Format("{0:c}", _
Container.DataItem("UnitCost")) %>
<br>
</td>
<td class="BackgroundColor5">
<a href='AddToCart.aspx?productID=
<%# Container.DataItem("ProductID") %>'>
<b>Add To Cart</b>
</a>
</td>
</tr>
</AlternatingItemTemplate>
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=14
Your page should now look like the following illustration.
3. Click on a subject link.
4. Click on an Add to Cart link.
43
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.
Note 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:DataList id="lstMenu" width="145" runat="server">
</asp:DataList>
3. Between the <asp:DataList> and </asp:DataList> tags, create an
ItemTemplate template that displays data in an asp:HyperLink control.
<ItemTemplate>
<asp:HyperLink id="HyperLink1" CssClass="MenuUnselected"
Text='<%# Container.DataItem("CategoryName") %>'
NavigateUrl='<%# "productslist.aspx?Categor yID=" & _
Container.DataItem("CategoryID") %>'
runat="server" />
</ItemTemplate>
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:
Dim dvMenuItems As DataView
Dim products As New Conference.ProductsDB
dvMenuItems = products.GetProductCategories(). _
Tables(0).DefaultView
'Bind the DataView of menu items to the list
lstMenu.DataSource = dvMenuItems
lstMenu.DataBind()
Module 3: Using Microsoft ADO.NET to Access Data
å 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.
45
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
Dim
Dim conn
conn As
As SqlConnection
SqlConnection == New
New SqlConnection
SqlConnection __
("server=localhost;uid=sa;pwd=;database=pubs")
("server=localhost;uid=sa;pwd=;database=pubs")
conn.Open()
conn.Open()
n
Create the DataReader From a Command Object
Dim
Dim cmdAuthors
cmdAuthors As
As SqlCommand
SqlCommand == New
New SqlCommand
SqlCommand __
("select
("select ** from
from Authors",
Authors", conn)
conn)
Dim
Dim dr
dr As
As SqlDataReader
SqlDataReader
dr
dr == cmdAuthors.ExecuteReader()
cmdAuthors.ExecuteReader()
n
Close the Connection
*****************************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 ExecuteReader method that
takes a SqlDataReader as a parameter. Note that you must explicitly open and
close the SqlConnection when you use a SQLCommand.
Dim conn As SqlConnection = New SqlConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
conn.Open()
Dim cmdAuthors As SqlCommand = New SqlCommand _
("select * from Authors", conn)
Dim dr As SqlDataReader
dr = cmdAuthors.ExecuteReader()
...
dr.close()
conn.Close()
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.
Try
conn.Open()
dr = cmdAuthors.ExecuteReader()
'use the returned data in the datareader
Catch e As Exception
Console.WriteLine(e.ToString)
Finally
dr.Close()
conn.Close()
End Try
Module 3: Using Microsoft ADO.NET to Access Data
49
Reading Data from a DataReader
n
Call Read for Each Record
l
n
Call Get for Each Field
l
n
Returns false when there are no more records
Parameter is the ordinal position of the field
Call Close to Free Up the Connection
myReader.Read()
myReader.Read()
lblName.Text
lblName.Text == myReader.GetString(1)
myReader.GetString(1) ++ ",
", "" ++ __
myReader.GetString(2)
myReader.GetString(2)
myReader.Close()
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()
lblName.Text = myReader.GetString(1) + ", " + _
myReader.GetString(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_fname").ToString()
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:
While myReader.Read()
'do something with the data
End While
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.Close()
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 OleDbCommand objects.
4. Set up a new DataView for the
desired table.
4. Populate a DataReader from the
Command by 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 DataRe ader.
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>
<employee>
<name>Jake</name>
<name>Jake</name>
<salary>25000</salary>
<salary>25000</salary>
<region>Ohio</region>
<region>Ohio</region>
</employee>
</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:
<employee>
<name>Jake</name>
<salary>25000</salary>
<region>Ohio</region>
</employee>
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
fs
fs == New
New FileStream
FileStream __
(Server.MapPath("schemadata.xml"),
(Server.MapPath("schemadata.xml"), __
FileMode.Open,
FileMode.Open, FileAccess.Read)
FileAccess.Read)
n
Read the Contents of the File Stream
Reader
Reader == New
New StreamReader(fs)
StreamReader(fs)
n
Read Data from the StreamReader into a DataSet
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.
Note You can’t 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:
<DocumentElement>
<TableName>
<ColumnName1>column
<ColumnName2>column
<ColumnName3>column
</TableName>
<TableName>
<ColumnName1>column
<ColumnName2>column
<ColumnName3>column
</TableName>
</DocumentElement>
value</ColumnName1>
value</ColumnName2>
value</ColumnName3>
value</ColumnName1>
value</ColumnName2>
value</ColumnName3>
Each TableName section corresponds to a single row in the table.
Module 3: Using Microsoft ADO.NET to Access Data
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 data— the DataGrid binds to it in the same way.
å To read XML data and display it in a DataGrid
1. First, open the XML file:
Dim fs As FileStream
fs = New FileStream _
(Server.MapPath("schemadata.xml"), _
FileMode.Open,FileAccess.Read)
2. Next, attach a StreamReader to the FileStream.
Dim Reader As StreamReader
Reader = New StreamReader(fs)
3. Finally, read the XML data from the StreamReader into the DataSet.
Dim ds As New DataSet
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:
Dim ds As New DataSet
Dim fs As FileStream
Dim Reader As StreamReader
'Read the XML data into a DataSet
fs = New FileStream _
(Server.MapPath("schemadata.xml"), _
FileMode.Open,FileAccess.Read)
Reader = New StreamReader(fs)
ds.ReadXml(Reader)
fs.Close()
'Bind the DataSet to a DataGrid
Dim Source As DataView
Source = new DataView(ds.Tables(0))
MyDataGrid.DataSource = Source
MyDataGrid.DataBind()
57
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
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?
59
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?
Module 4: Separating
Code from Content
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
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 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
n
n
By using code-behind files that are pre-compiled modules written in any of
the Microsoft .NET run-time-compliant languages.
By creating user controlsfrequently used control sets and their logic and
using them as you would use controls in your ASP.NET pages.
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
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.
3
4
Module 4: Separating Code from Content
Understanding How Code-Behind Pages Work
Create Separate Files for User
Interface and Interface Logic
n Use Page Directive to Link
the Two Files
n
Page.aspx
<%@ Page
Inherits="myDemo"
Src= "demo.vb" %>
<%@
<%@ Page
Page Inherits="myDemo"
Inherits="myDemo"
Src="demo.vb"%>
Src="demo.vb"%>
demo.vb
Public
Public Class
ClassmyDemo
myDemo
Public
Public Function
Function getData()
getData()
……
End
End Function
Function
End
EndClass
Class
n
Call Procedures in the CodeBehind Page
ds
ds == getData()
getData()
*****************************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" Inherits="myDemo" Src="demo.vb" %>
Note 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.
Module 4: Separating Code from Content
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).
Public Sub Page_Load (Src As Object, E As EventArgs)
Dim ds As DataSet
ds = getData()
dgAuthors.DataSource=ds
dgAuthors.DataMember="Authors"
dgAuthors.DataBind()
End Sub
5
6
Module 4: Separating Code from Content
Creating a Class File in Visual Basic
n
Class File
Public
Public Class
Class myDemo
myDemo
Public
Public Function
Function getData()
getData() As
As DataSet
DataSet
……
End
End Function
Function
End
End Class
Class
n
Using Objects from the ASP.NET Environment
Imports
Imports System
System
Imports
Imports System.Web
System.Web
n
Inheriting from the ASP.NET Page Class
Public
Public Class
Class myDemo
myDemo
Inherits
Inherits System.Web.UI.Page
System.Web.UI.Page
……
End
End Class
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:
Public Class class_name
Public variable_name As variable_type
Public Function function_name(parameters) As return_type
…
End Function
Public Sub sub_name(parameters)
…
End Sub
End Class
Note 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.
Module 4: Separating Code from Content
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:
Imports System
Imports System.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.
Public Class class_name
Inherits System.Web.UI.Page
…
End Class
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.
Imports
Imports
Imports
Imports
System
System.Web
System.Data
System.Data.SqlClient
Public Class myDemo
Inherits System.Web.UI.Page
Public
Dim
Dim
Dim
Function getData() As DataSet
ds As DataSet
conn As SqlConnection
cmdAuthors As SqlDataAdapter
conn = New SqlConnection _
("server=localhost;uid=sa;pwd=;database=pubs")
cmdAuthors = New SqlDataAdapter _
("select * from Authors", conn)
ds = new DataSet()
cmdAuthors.Fill(ds, "Authors")
return (ds)
End Function
End Class
7
8
Module 4: Separating Code from Content
Demonstration: Creating a Code-Behind Page
*****************************illegal for n o n-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.
Important 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.
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.
Public Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
5. Add code to change the Text property of the label control.
Label1.Text = "clicked"
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
Imports
Imports System.Web.UI.WebControls
System.Web.UI.WebControls
Imports
Imports System.Web.UI.HtmlControls
System.Web.UI.HtmlControls
n
Declare Variables with Same Name as Controls
Dim
Dim lbl
lbl As
As Label
Label
Dim
txt
As
Dim txt As TextBox
TextBox
n
Reference Properties of Controls
Public
Public Sub
Sub btn_Click
btn_Click (s
(s as
as Object,
Object, ee As
As EventArgs)
EventArgs)
lbl.Text
lbl.Text == "You
"You are
are searching
searching for
for "" && txt.Text
txt.Text
End
End Function
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:
<form runat=server>
<asp:textbox id="txt" runat="server" />
<asp:button id="btn" onclick="btn_click"
text="Click Me" runat="server"/>
<P><asp:label id="lbl" runat="server"/>
</form>
Module 4: Separating Code from Content
The code-behind page can include the event procedure and reference the
controls on the page, as shown in the following example:
Imports System
Imports System.Web
Imports System.Web.UI.WebControls
Public Class myDemo
Inherits System.Web.UI.Page
Public lbl As Label
Public txt As TextBox
Public Sub btn_click(s As Object, e As EventArgs)
lbl.Text = txt.Text
End sub
End Class
11
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 codebehind 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
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
Public Properties and Methods are Promoted to
Properties and Methods of the Control in the Host Page
Public
Public Property
Property pNum
pNum As
As Integer
Integer
Get
Get
Return
Return CInt(txtNum.Text)
CInt(txtNum.Text)
End
Get
End Get
End
End Property
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 control’s 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:
<%@ Control Language="vb" %>
<asp:textbox id="txtNum" runat="server" />
<asp:RequiredFieldValidator id="txtNumValidator"
runat="server"
controlToValidate="txtNum"
errorMessage="You must enter a value"
display="dynamic">
</asp:RequiredFieldValidator>
<asp:RangeValidator id="txtNumRngValidator" runat="server"
controlToValidate="txtNum"
errorMessage="Please enter a number between 0 and 99"
type="Integer"
minimumValue="0"
maximumValue="99"
display="dynamic">
</asp:RangeValidator>
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:
<SCRIPT language="VB" runat="Server">
Public Property pNum As Integer
Get
Return CInt(txtNum.Text)
End Get
Set
txtNum.Text = Value.ToString()
End Set
End Property
</SCRIPT>
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
@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.
<%@ Control attribute=value [attribute=value … ]%>
For example, to reference a code-behind page for a user control, you use the
following line of code:
<%@ Control Inherits="myDemo" src="demo.vb"%>
Note 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.
15
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
<%@
<%@ Register
Register TagPrefix="conference"
TagPrefix="conference"
TagName="validNum"
TagName="validNum" Src="numberBox.ascx"
Src="numberBox.ascx" %>
%>
n
Insert the User Control Like a Server Control
<conference:validNum
<conference:validNum id="num1"
id="num1"
runat="server"/>
runat="server"/>
n
Set Properties of the User Control
num1.pNum
num1.pNum == 55
*****************************illegal for non-trainer use******************************
User controls are included in an ASP.NET page by using the @Register
directive:
<%@ Register TagPrefix="conference" TagName="validnum"
Src="numberbox.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).
<conference:validNum id="num1" runat="server"/>
<conference:validNum id="num2" runat="server"/>
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:
lblSum.Text = (num1.pNum + num2.pNum).ToString()
Module 4: Separating Code from Content
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.
<%@ Register TagPrefix="demos" TagName="validNum"
Src="numberbox.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:validNum id="txtNum1" runat="server" />
Num2: <demos:validNum id="txtNum2" runat="server" />
17
18
Module 4: Separating Code from Content
6. Change the Submit event procedure to read values from the user controls.
Sub submit(s As Object, e As EventArgs)
If Page.IsValid Then
lblSum.Text = _
CStr(Convert.ToInt32(txtNum1.pNum) + _
Convert.ToInt32(txtNum2.pNum))
End If
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
n
No Server Restart Required
l
l
n
Components may be deployed by simply copying to the /bin dir or
performing an FTP file transfer
The Web server does not require a restart when you change your
application
New requests immediately begin execution against the changed file
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
n
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.
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
Imports
Imports System.Data.SQL
System.Data.SQL
Namespace
Namespace myComponent
myComponent
Public
Public Class
Class ConferenceDB
ConferenceDB
Public
Public Function
Function getCategories(...)
getCategories(...)
……
End
End Class
Class
End
End Namespace
Namespace
n
Compiling the Class
vbc
vbc /t:library
/t:library /out:component.dll
/out:component.dll component.vb
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" Inherits="myDemo" Src="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
<%@ Import 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
Public Class ConferenceDB
. . .
End Class
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.
Imports System.Data
Imports System.Data.SqlClient
Example
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.
Imports System.Data
Imports System.Data.SqlClient
Namespace myComponent
Public Class ConferenceDB
Public Function getCategories _
(conn As SqlConnection) As DataSet
'Retrieve a list of categories from the database
End Function
End Class
End Namespace
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:library /out:component.dll 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:library /out:component.dll /r:System.Data.dll
component.vb
Finally, after compiling the component, move it to the \bin folder in the root of
the virtual directory for your Web site.
Important You must define a virtual directory for your Web site.
The component is now available for use in an ASP.NET page.
24
Module 4: Separating Code from Content
Using Components in an ASP.NET Page
component.dll
Namespace myComponent
Class ConferenceDB
End Class
End Namespace
n
Adding a Component
<%@
<%@ Import
Import Namespace="myComponent"
Namespace="myComponent" %>
%>
n
Using the Component
Dim
Dim xx As
As New
New ConferenceDB
ConferenceDB
ds
ds == x.getCategories(conn)
x.getCategories(conn)
*****************************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:
<%@ Import Namespace="myComponent" %>
You can then instantiate an object of the class by referencing the class name
directly, as shown in the following example.
Dim x As New ConferenceDB
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:
Dim x As New myComponent.ConferenceDB
Note 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:
<%@ Import Namespace="demos.myComponent" %>
or
Dim x As New demos.myComponent.ConferenceDB
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.getCategories(conn)
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:
<%@ Import Namespace="projectname.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
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.
27
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
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.
<%@ Control Language="vb" %>
5. Save the page as _Menu.ascx (overwrite the existing _Menu.ascx file).
29
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:
<%@ Register TagPrefix="Conference" TagName="Header"
Src="_Header.ascx" %>
<%@ Register TagPrefix="Conference" TagName="Menu"
Src="_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:
<table width="100%" border=0>
<tr><td>
<!-- _Header.ascx user control -->
</td></tr>
<tr><td>
<table border=0>
<tr><td valign="top">
<!-- _Menu.ascx user control -->
</td>
<td>
<!-- Existing contents of the page -->
<!-- between <body> and </body> tags -->
</td>
</tr>
</table>
</td></tr>
</table>
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:
<table width="100%" border=0>
<tr><td>
<!-- _Header.ascx user control -->
<Conference:Header runat="server"/>
</td></tr>
<tr><td>
<table border=0>
<tr><td valign="top">
<!-- _Menu.ascx user control -->
<Conference:Menu runat="server"/>
</td>
<td>
<!-- Existing contents of the page -->
<!-- between <body> and </body> tags -->
</td>
</tr>
</table>
</td></tr>
</table>
å 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
Note CategoryID=15 corresponds to the Conference Trackscategory in
the Categories table of the database.
Notice the header and menu user controls.
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:
Imports System.Data
Imports System.Data.SqlClient
3. Create a new namespace named db2063.
4. Create a public class named Products.
Your code should look like the following:
Namespace db2063
Public Class Products
End Class
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.
Public Function GetProducts(categoryID As Integer) As _
DataSet
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(Source As Object, E As EventArgs)
'Obtain CategoryID from QueryString
Dim categoryID As Integer = _
CInt(Request.Params("CategoryID"))
' Bind to the control
repList.DataSource = dsProducts.Tables(0).DefaultView
repList.DataBind()
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
6. Add a return statement to return the Dataset at the end of the function.
Your function should look like the following:
Public Function GetProducts(categoryID As Integer) As _
DataSet
Dim conn
As SqlConnection
Dim strConn
As String
Dim cmdProducts
As SqlDataAdapter
Dim paramCategoryID
As SqlParameter
Dim dsProducts
As New DataSet
' Create the connection
strConn = _
"server=localhost;uid=sa;pwd=1Aspnet;database=Conf"
conn = New SqlConnection(strConn)
' Call the ProductsByCategory stored procedure
cmdProducts = _
New SqlDataAdapter("ProductsByCategory", conn)
cmdProducts.SelectCommand.CommandType = _
CommandType.StoredProcedure
' Add Parameters
paramCategoryID = _
New SqlParameter("@CategoryID", SqlDbType.Int, 4)
paramCategoryID.Value = categoryID
cmdProducts.SelectCommand.Parameters.Add(paramCategoryID)
' Fill the DataSet
cmdProducts.Fill(dsProducts, "Products")
' Return the DataSet
return dsProducts
End Function
Note 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.
35
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:library /out:..\bin\db2063.dll /r:System.dll
/r:System.Web.dll /r:System.Xml.dll /r:System.Data.dll
GetProducts.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
ProductList.aspx
Middle-tier
components
GetProducts.vb
Data
ProductsByCategory Stored Procedure
å 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.
Note 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:
Dim productCatalog As New db2063.Products
If you used Visual Studio .NET to compile the component, your code
should look like the following:
Dim productCatalog As New ASPNET.db2063.Products
4. Declare a DataSet variable named dsProducts.
5. After the code that reads the categoryID parameter 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:
Dim dsProducts As New DataSet
dsProducts = productCatalog.GetProducts(CategoryID)
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
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 codebehind class file?
39
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?
Module 5: Using Trace
in Microsoft ASP.NET
Pages
Contents
Overview
1
Overview of Tracing
2
Trace Information
3
Page -Level Trace
Application-Level Trace
4
10
Lab 5: Adding Trace to an ASP.NET Page
16
Review
21
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
oth erwise), 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
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 w herever 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.
1
2
Module 5: Using Trace in Microsoft ASP.NET Pages
Overview of Tracing
n
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
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
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.
3
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
<%@
<%@ Page
Page Language="VB"
Language="VB" Trace="true"%>
Trace="true"%>
n
Sorting Output by Category
<%@
<%@ Page
Page Language="VB"
Language="VB" Trace="true"
Trace="true"
TraceMode="SortByCategory"%>
TraceMode="SortByCategory"%>
n
Inserting Trace Messages
Trace.Write("category",
Trace.Write("category", "message")
"message")
n
Conditional Execution with Trace.IsEnabled
If
If Trace.IsEnabled
Trace.IsEnabled
strTrace
strTrace == 'create
'create trace
trace string
string here
here
End
If
End If
Trace.Write(strTrace)
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" Trace="true" %>
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 Trace="true" TraceMode="SortByCategory" %>
TraceMode is of the type TraceModeEnum, and has two possible values:
n
SortByTime
n
Trace messages are output in order of chronological occurrence. This is the
default setting.
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:
Trace.Write("category", "message")
Trace.Warn("category", "message")
The category argument is used to organize messages. For example:
Trace.Write("Custom Trace","Beginning User Code...")
Trace.Warn("Custom Trace","Array count is null!")
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.
If Trace.IsEnabled
strTrace = "create a trace string here"
End If
Trace.Write(strTrace)
Module 5: Using Trace in Microsoft ASP.NET Pages
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" Trace="True"%>
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.
Trace.Write ("add Page_Load", "txtNum1 = " &
Cstr(txtNum1.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.
7
8
Module 5: Using Trace in Microsoft ASP.NET Pages
Tracing into a Component
n
Import the System.Web Library
Imports
Imports System.Web
System.Web
n
Enable Tracing in Class Constructor
HttpContext.Current.Trace.IsEnabled
HttpContext.Current.Trace.IsEnabled == True
True
n
Add Trace Statements to Method
HttpContext.Current.Trace.Write
HttpContext.Current.Trace.Write __
("component",
("component", "this
"this is
is my
my trace
trace statement")
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.
Imports System.Web
2. In the constructor of the class to which you want to add trace statements,
enable tracing with the following statement:
HttpContext.Current.Trace.IsEnabled = True
In the preceding code, HttpContext.Current gets the Context object for
the current request.
3. Next, in the method, use the following:
HttpContext.Current.Trace.Write _
("component", "this is my trace statement")
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
<trace enabled="true"
enabled="true"
traceMode="SortByCategory"
traceMode="SortByCategory"
requestLimit="40"
requestLimit="40"
pageOutput="true"/>
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 application’s configuration file.
Enabling Tracing
With ASP.NET, there is a configuratio n 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 application’s root folder.
<trace enabled="true"/>
12
Module 5: Using Trace in Microsoft ASP.NET Pages
By using the above configuration, each page in the application will output pagelevel trace statements to the file trace.axd in the application’s 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.
<trace enabled="true" pageOutput="true"/>
Note The trace section in the configuration file is contained in a <system.web>
section inside the <configuration> section.
<configuration>
<system.web>
<trace enabled="true"/>
</system.web>
</configuration>
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:
<trace enabled="true" traceMode="sortByCategory"
requestLimit="40" pageOutput="false"/>
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:
<trace enabled="true"/>
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.
Note 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.
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" trace="true" %>
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:
Trace.Write("Product List", "Beginning 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:
Imports System.Web
3. In the GetProducts method, enable tracing by setting the
HttpContext.Current.Trace.IsEnbled property to True.
Your code should look like the following:
HttpContext.Current.Trace.IsEnabled = true
Note 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:
HttpContext.Current.Trace.Write _
("DB2063.Products Component", _
"Beginning of GetProducts")
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 .
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:library /out:..\bin\db2063.dll /r:System.dll
/r:System.Web.dll /r:System.Xml.dll /r:System.Data.dll
GetProducts.vb
b. To compile the component by using Visual Studio .NET, click Build on
the Build menu.
Note 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.
Dim productCatalog As New ASPNET.db2063.Products
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.
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?
Module 6: Using Web
Services
Contents
Overview
What Is a Web Service?
1
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
Review
35
47
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 today’s 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 user’s
preferences, a credit-card processing service, a sales tax service, packagetracking services from each shipping company, an in-house catalog service that
connects to the company’s 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
Web Services Execution Model
*****************************illegal for non-trainer use******************************
The Web services execution model involves two entities: the client and the
service provider.
Note 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 :
<%@ WebService Language="VB" Class="MathService" %>
Imports System.Web.Services
Imports System
Class MathService
<WebMethod()> Public Function Add(int1 As Integer, _
int2 As Integer) As Integer
return(int1 + int2)
End Function
End Class
5
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.
Note 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.
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
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
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 programmer’s
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
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
9
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 S ervices
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
http://server/vroot/webservice.asmx/method?param=value
http://server/vroot/webservice.asmx/method?param=value
n
Return Value Is in XML Format
*****************************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 version="1.0"?>
<double xmlns="http://tempuri.org/">200</double>
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.
Note You will first learn how to create a Web service manually, and then learn
how to create it by using Microsoft Visual Studio® .NET.
16
Module 6: Using Web Services
Compiling an .asmx File into a Proxy
n
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
Creating a Proxy Class from an .asmx File
wsdl
wsdl /l:vb
/l:vb /n:myNameSpace
/n:myNameSpace
http://location/service.asmx?wsdl
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.
Syntax
wsdl [options] {URL | path}
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).
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:myStore
http://localhost/Store/Store.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
vbc
vbc /out:..\bin\proxyclassname.dll
/out:..\bin\proxyclassname.dll
/t:library
/t:library
/r:System.Web.Services.dll
/r:System.Web.Services.dll proxyclassname.vb
proxyclassname.vb
n
The .dll File Is Published in the /bin Folder
*****************************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:..\bin\proxyclassname.dll /t:library
/r:System.Web.Services.dll proxyclassname.vb
In the preceding code’s 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.
Example
If you want to compile the Store.vb class into a DLL, you could use the
following code:
vbc /out:..\bin\Store.dll /t:library
/r:System.Web.Services.dll store.vb
Note that in the preceding code’s 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).
20
Module 6: Using Web Services
Calling Web Service Methods
n
Creating an Instance of the Proxy
Dim
Dim myStoreProxy
myStoreProxy As
As myStore.Store
myStore.Store
myStoreProxy
myStoreProxy == New
New myStore.Store()
myStore.Store()
n
Calling Methods
Dim
Dim ds
ds As
As DataSet
DataSet
ds
ds == myStoreProxy.products()
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:
Dim myStoreProxy As myStore.Store
myStoreProxy = New myStore.Store()
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:
Dim ds As DataSet
ds = myStoreProxy.products()
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
<%@
<%@ WebService
WebService Language="VB"
Language="VB" Class=
Class= "MyStore"
"MyStore" %>
%>
n
Importing the Namespaces
Imports
Imports System
System
Imports
Imports System.Web.Services
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.
<%@ WebService Language="VB" Class="MyStore" %>
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.
Imports System
Imports System.Web.Services
24
Module 6: Using Web Services
Writing a Web Service (continued)
n
Defining a Class with WebMethods
Public
Public Class
Class MyStore
MyStore
<WebMethod()>
<WebMethod()> Public
Public Function
Function __
Price()
Price() As
As String
String
Price
Price == "The
"The item
item costs
costs $10."
$10."
End
Function
End Function
End
End Class
Class
n
Save the File with an .asmx Extension
*****************************illegal f o r n o n-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 w ill not be exposed
from the service. The following code has the MyStore class and the Price
method:
Public Class MyStore
<WebMethod()> Public Function Price() As String
Price = "The item costs $10."
End Function
End Class
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.
Note You can change the default name of the Web service file
(Service1.asmx) and the default name of the class (Service1).
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:
<WebMethod()> Public Function GetRating(Ticker As String) _
As String
If Ticker ="ACME" Then
Return "Buy"
Else
Return "Sell"
End If
End Function
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
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 Button1_Click(s As Object, e As EventArgs)
Dim service As New GetStocks.localhost.service1()
lblResults.Text = service.GetRating("ACME")
End Sub
Note 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.
33
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.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim service As New GetStocks.localhost.service1()
Label1.Text= service.GetRating(TextBox1.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.
<WebMethod()>public Function Reserve (
strRoomType1 As String, strRoomType2 As String,
dtmStartDate As Date, dtmEndDate As Date) As Boolean
n
Price returns a double value that is the price of the hotel for one night.
<WebMethod()>public Function Price(
strRoomType1 As String) As Double
n
Description returns a string that describes the hotel.
<WebMethod()>public Function Description() As String
n
Room returns a string that describes the rooms of the hotel.
<WebMethod()>public Function Room() As String
n
Food returns a string that describes the food available at the hotel.
<WebMethod()>public Function Food() As String
å 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:
Dim hotel_FullProxy As ASPNET.localhost.hotel_Full
hotel_FullProxy = New ASPNET.localhost.hotel_Full()
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.
Note 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:
Dim hotel_FullProxy As myHotel_Full.hotel_Full
hotel_FullProxy = New myHotel_Full.hotel_Full()
c. Call the Description, Room, and Food methods of the Full hotel’s 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:
lblDescription.Text = hotel_FullProxy.Description()
lblRoom.Text = hotel_FullProxy.Room()
lblFood.Text = hotel_FullProxy.Food()
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:
<%@ WebService Language="VB" Class="hotel_New" %>
Imports System.Web.Services
Imports System
Class hotel_New
End Class
2. If you are using Visual Studio .NET, create a new Web service project
named hotel_New.
Note 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:myHotel_New
http://localhost/ASPNET/hotel_New.asmx? wsdl
vbc /out:.\bin\hotel_New.dll /t:library /r:System.dll
/r:System.Xml.dll /r:System.Web.Services.dll
hotel_New.vb
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.
Note Refer to Exercise 1 of this lab for detailed instructions on how to call
a Web service from the hotel_reservation.aspx page.
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:
Dim intHotelID As Integer
intHotelID = CInt(Request.Params("HotelID"))
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:
Dim intHotelID As Integer
intHotelID = CInt(Request.Params("HotelID"))
' Initialize the reservation confirmation message
lblReservationConfirmation.Text = ""
' Which hotel is it?
Select Case intHotelID
Case 1
' Create a proxy for the Full hotel
Dim hotel_FullProxy As myHotel_Full.hotel_Full
hotel_FullProxy = New myHotel_Full.hotel_Full()
' Get the general, room and food descriptions
lblDescription.Text = hotel_FullProxy.Description()
lblRoom.Text = hotel_FullProxy.Room()
lblFood.Text = hotel_FullProxy.Food()
Case 2
' create a proxy for the Empty hotel
Dim hotel_EmptyProxy As myHotel_Empty.hotel_Empty
hotel_EmptyProxy = New myHotel_Empty.hotel_Empty()
' Get the general, room and food descriptions
lblDescription.Text = hotel_EmptyProxy.Description()
lblRoom.Text = hotel_EmptyProxy.Room()
lblFood.Text = hotel_EmptyProxy.Food()
End Select
å 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 button’s click event procedure (cmdSubmit_Click), after
the test for the calendar dates, add code to retrieve the HotelID variable
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 nonsmoking.
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:
Dim intHotelID As Integer
Dim blnRoomFree As Boolean = False
Dim dblPrice As Double = 0.00
' Obtain HotelID from QueryString
intHotelID = CInt(Request.Params("HotelID"))
' Ask the hotel service if there is an available room
Select Case intHotelID
Case 1
' Create a proxy for the Full hotel
Dim hotel_FullProxy As myHotel_Full.hotel_Full
hotel_FullProxy = new myHotel_Full.hotel_Full()
' Get the availability of the selected type of room
' for the specified dates
blnRoomFree = hotel_FullProxy.Reserve _
(lstRoomType1.SelectedItem.Text, _
lstRoomType2.SelectedItem.Text, _
calStartingDate.SelectedDate, _
calEndingDate.SelectedDate)
' Get the price
dblPrice = hotel_FullProxy.Price _
(lstRoomType1.SelectedItem.Text)
Case 2
' Create a proxy for the Empty hotel
Dim hotel_EmptyProxy As myHotel_Empty.hotel_Empty
hotel_EmptyProxy = new myHotel_Empty.hotel_Empty()
' Get the availability of the selected type of room
' for the specified dates
blnRoomFree = hotel_EmptyProxy.Reserve _
(lstRoomType1.SelectedItem.Text, _
lstRoomType2.SelectedItem.Text, _
calStartingDate.SelectedDate, _
calEndingDate.SelectedDate)
' Get the price
dblPrice = hotel_EmptyProxy.Price _
(lstRoomType1.SelectedItem.Text)
End Select
' code continued on next page
46
Module 6: Using Web Services
' code continued from previous page
' Build the confirmation message
If blnRoomFree Then
lblReservationConfirmation.Text = _
"Room available. " & _
"<br><br> Your selection was:<br>" & _
lstRoomType1.SelectedItem.Text & ", " & _
lstRoomType2.SelectedItem.Text & "<br>" & _
"from " & _
calStartingDate.SelectedDate.ToShortDateString() _
& " to " & _
calEndingDate.SelectedDate.ToShortDateString() _
& "<br><br>" & "The price will be: " & _
System.String.Format("{0:c}", dblPrice)
Else
lblReservationConfirmation.Text = _
"No room available."
End If
å 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
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?
47
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?
Module 7: Creating a
Microsoft ASP.NET
Web Application
Contents
Overview
1
Requirements of a Web Application
2
What Is New in ASP.NET?
3
Sharing Information Between Pages
Securing an ASP.NET Application
13
24
Lab 7: Creating an ASP.NET Web
Application
38
Review
50
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 subdirectories 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
n
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.
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
n
All Web applications should be built with high performance and scalability
in mind. Caching is an extremely important technique for building highperformance, scalable Web server applications.
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
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.
3
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
n
Default mechanism for storing SessionIDs
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
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:
<sessionState cookieless="true"/>
5
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>
<configuration>
<system.web>
<system.web>
<trace
<trace enabled="true"
enabled="true"
requestlimit="40"
requestlimit="40" pageoutput="true"/>
pageoutput="true"/>
</system.web>
</system.web>
</configuration>
</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 serverfor
example, Inetpub\wwwrootthe 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:
<configuration>
<system.web>
<trace enabled="true"
requestlimit="40" pageoutput="true"/>
</system.web>
</configuration>
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:
n
l
cookieless
l
mode
l
timeout
l
sqlConnectionString
Setting Up Cookie-less Session
<sessionState
<sessionState cookieless="true“
cookieless="true“ />
/>
*****************************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:
<sessionstate timeout="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:
<sessionstate cookieless="true" />
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 ASP’s global.asa, but has numerous new events that are not supported
by global.asa.
Note In ASP.NET, global.asax can be used as an .asax file or as a component
that can be deployed in the application’s /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 Application_BeginRequest(s As Object, e As EventArgs)
...
End Sub
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
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
Setting the Cache Timeout
<%@
<%@ OutputCache
OutputCache Duration=
Duration= "900"
"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:
<%@OutputCache Duration="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).
Note 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.
Module 7: Creating a Microsoft ASP.NET Web Application
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.
13
14
Module 7: Creating a Microsoft ASP.NET Web Application
Using ASP.NET Cache
n
ASP.NET Cache:
l
n
Stores objects and values for reuse in an application
Placing Objects in ASP.NET Cache
Cache.Insert("mykey",
Cache.Insert("mykey", myValue,
myValue, __
Nothing,
Nothing, DateTime.Now.AddHours(1),
DateTime.Now.AddHours(1), __
TimeSpan.Zero)
TimeSpan.Zero)
n
Retrieving Objects From ASP.NET Cache
myValue
myValue == Cache("mykey")
Cache("mykey")
If
If myValue
myValue <>
<> Nothing
Nothing Then
Then
DisplayData(myValue)
DisplayData(myValue)
End
End If
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") = myValue
Retrieving this data is equally simple:
myValue = Cache("mykey")
If myValue <> Nothing Then
DisplayData(myValue)
End If
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.Insert ( key As String, _
value As Object, _
dependencies As CacheDependency, _
absoluteExpiration As DateTime, _
slidingExpiration As TimeSpan )
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.
Dim dvMenuItems As DataView
dvMenuItems = Cache("dvMenuItems")
If (dvMenuItems = Nothing) Then
Dim products As New Conference.ProductsDB
dvMenuItems = products.GetProductCategories(). _
Tables(0).DefaultView
Cache.Insert("dvMenuItems", dvMenuItems, Nothing, _
DateTime.Now.AddHours(1), TimeSpan.Zero)
End If
MyList.DataSource = dvMenuItems
MyList.DataBind()
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.Insert("dvMenuItems", dvMenuItems, Nothing, _
DateTime.Now, TimeSpan.FromHours(1))
16
Module 7: Creating a Microsoft ASP.NET Web Application
Using web.config Variables
n
Store Application Variables in web.config
<configuration>
<configuration>
<appsettings>
<appsettings>
<add
<add key="pubs"
key="pubs" value=
value=
"server=localhost;uid=sa;pwd=;database=pubs"/>
"server=localhost;uid=sa;pwd=;database=pubs"/>
</appsettings>
</appsettings>
</configuration>
</configuration>
n
Retrieve in an .aspx File
Dim
Dim appSetting
appSetting As
As NameValueCollection
NameValueCollection
Dim
strConn
As
String
Dim strConn As String
appSetting
appSetting == CType(Context.GetConfig
CType(Context.GetConfig __
("appsettings"),
("appsettings"), NameValueCollection
NameValueCollection ))
strConn
=
appSetting("pubs").ToString()
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:
<configuration>
<appsettings>
<add key="pubs"
value="server=localhost;uid=sa;pwd=;database=pubs" />
<add key="northwind"
value="server=localhost;uid=sa;pwd=;database=northwind"
/>
</appsettings>
</configuration>
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
For example, the following sample code reads the value of the pubs key from
the <appSettings> section.
Dim appSetting As NameValueCollection
Dim strConn As String
appSetting = CType(Context.GetConfig("appsettings"), _
NameValueCollection)
strConn = appSetting("pubs").ToString()
You can also use the GetConfig method of the HttpContext object to access
configuration information from a component. The syntax for this is:
appSetting = _
CType(HttpContext.Current.GetConfig("appsettings"), _
NameValueCollection)
17
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:
<configuration>
<appSettings>
<add key="intNumberInConfig" value="9" />
</appSettings>
</configuration>
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
Using Session and Application Variables
n
Session Object Stores Information for a Particular User
Session
Sub
Sub Session_Start(s
Session_Start(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
Session("BackColor")
Session("BackColor") == "beige"
"beige"
Session("ForeColor")
Session("ForeColor") == "black"
"black"
End
End Sub
Sub
n
Application Object Shares Information Among All Users
of a Web Application
Sub
Sub Application_Start(s
Application_Start(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
Application("NumberofVisitors")
Application("NumberofVisitors") == 00
End
End Sub
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. Va riables 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.
<script language="VB" runat="server">
Sub Session_Start(S As Object, E As EventArgs)
Session("BackColor") = "beige"
Session("ForeColor") = "black"
Session("FontName") = "verdana"
End Sub
</script>
19
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 Application_Start(s As Object, e As EventArgs)
Application("NumberofVisitors") = 0
End Sub
Note 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.
Session("BackColor")
Session("ForeColor")
Session("FontName")
Application("NumberofVisitors")
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:
Session("intNumber")=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
n
Because all state is stored externally from an individual worker process, it
will not be lost if the process crashes or is forcibly restarted.
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
Discussion: Different Ways of Sharing Information
*****************************illegal for non-trainer use**************** **************
23
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
n
Authentication
l
Accept credentials from a user
l
Validate the credentials
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.
n
For more information on Windows authentication, see the Microsoft .NET
Framework SDK documentation.
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
ASP.NET
Authentication
Not
Authenticated
Client requests page
Access Denied
û
Not
Authenticated
Cookie
û
Login Page
(Users enter
their credentials)
Authenticated
Authorized
Authenticated
Authorized
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.
Tip 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 user’
s 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 request’s authorization cookie to the
authorization settings in the application’
s 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 application’s configuration
file), where the user enters the required credentials, usually a name and
password.
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
<system.web>
<system.web>
<authentication
<authentication mode="Forms">
mode="Forms">
<forms
<forms name="name"
name="name" loginurl="login.aspx"/>
loginurl="login.aspx"/>
</authentication>
</authentication>
</system.web>
</system.web>
n
Setting Up Authorization
<location
<location path="ShoppingCart.aspx">
path="ShoppingCart.aspx">
<system.web>
<system.web>
<authorization>
<authorization>
<deny
<deny users="?"/>
users="?"/>
<allow
<allow users="Mary"/>
users="Mary"/>
</authorization>
</authorization>
</system.web>
</system.web>
</location>
</location>
*****************************illegal for non-trainer use******************************
Security for ASP.NET applications is set up in the application’s web.config file.
The security settings in web.config are included in the <authentication>,
<authorization>, and <identity> sections.
Note 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.
<configuration>
<system.web>
<authentication mode="authmode">
</authentication>
</system.web>
</configuration>
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".
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:
<system.web>
<authentication mode="Forms">
<forms name=".namesuffix" loginurl="login.aspx" />
</authentication>
</system.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:
<system.web>
<authentication mode="Forms">
<forms name=".aspxauth"
loginurl="login.aspx" />
<authorization>
</authorization>
</authentication>
</system.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:
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
</authorization>
</system.web>
</location>
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.
<authorization>
<deny users="?"/>
</authorization>
The following code allows the user “Mary”access to a page:
<authorization>
<allow users="Mary"/>
</authorization>
The following example denies all anonymous users access to the
ShoppingCart.aspx page.
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
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
Sub
Sub cmdLogin_Click(s
cmdLogin_Click(s As
As Object,
Object, ee As
As EventArgs)
EventArgs)
If
If (login(txtEmail.Value,
(login(txtEmail.Value, txtPassword.Value))
txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage
FormsAuthentication.RedirectFromLoginPage __
(txtEmail.Value,
(txtEmail.Value, False)
False)
End
If
End If
End
End Sub
Sub
n
Reading User Credentials from Cookie
l
User.Identity.Name returns the value saved by
CookieAuthentication.RedirectFromLoginPage
*****************************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 user’s 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:
<form runat=server>
Email:<input id="txtEmail" type="text" runat=server/>
<BR>
Password<input id="txtPassword" type="password"
runat="server"/>
<BR>
<asp:button text="Login" OnClick="Login_Click"
runat="server" />
<asp:label id="lblMsg" runat="server"/>
</form>
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:
<script language="VB" runat=server>
Sub cmdLogin_Click(Sender As Object, E As EventArgs)
Dim strCustomerId As String
'Validate User Credentials
strCustomerId = Login(txtEmail.Value, txtPassword.Value)
If (strCustomerId <> "") Then
FormsAuthentication.RedirectFromLoginPage _
(strCustomerId, False)
Else
lblMsg.Text = "Invalid Credentials: Please try again"
End If
End Sub
</script>
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 user’
s 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:
<system.web>
<authentication mode="Forms">
<forms loginurl="democode/Mod07/LoginDemo.aspx">
<credentials passwordFormat="Clear">
<user name="ruth" password="password"/>
<user name="bob" passw ord="password"/>
</credentials>
</forms>
</authentication>
</system.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 cmdLogin_Click(S As Object, E As EventArgs)
If (FormsAuthentication.Authenticate _
(txtEmail.value, txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage _
(txtEmail.Value, False)
Else
lblMsg.Text = "Invalid Credentials: Please try again"
End If
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:
dvMenuItems = Cache("dvMenuItems")
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 DataView in the cache. Create the cache such that it will be
stored for one hour.
Your code should look like the following:
If (dvMenuItems Is Nothing) Then
Response.Write ("Getting items from the database.<P>")
Dim products As New Conference.ProductsDB
dvMenuItems = products.GetProductCategories(). _
Tables(0).DefaultView
Cache.Insert("dvMenuItems", dvMenuItems, Nothing, _
DateTime.Now.AddHours(1), TimeSpan.Zero)
Else
Response.Write ("Got items from the cache.<P>")
End If
å 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 user’s 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.
Note 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.
Public Function GetShoppingCartId() As String
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.
Public Sub Procedure MigrateCart(oldCartId As String,
NewCartId As String)
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.
Public Function Login(email As String, password As String)
As String
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:
strCustomerId = _
accountSystem.Login(txtEmail.Value, txtPassword.Value)
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:
If (strCustomerId <> "") Then
' Get the old Shopping Cart ID
strTempCartID = shoppingCart.GetShoppingCartId()
' Migrate existing shopping cart into
'permanent shopping cart
shoppingCart.MigrateCart(strTempCartID, strCustomerId)
' Redirect browser back to originating page
FormsAuthentication.RedirectFromLoginPage( _
strCustomerId, false)
Else ' Login failed
spnInfo.innerHTML = "Login Failed"
End If
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 [email protected] 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.
Note The e-mail name and password pair
[email protected]/password is already in the database.
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.
Note 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 the customer ID
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.
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:
If User.Identity.Name <> "" Then
Response.write("Customer ID from authentication " & _
"cookie:<br>")
Response.write(User.Identity.Name)
Else
If Request.Cookies("Conference_CartID") Is Nothing Then
Response.write("Customer not authenticated " & _
"and has not accessed the shopping cart yet")
Else
Response.write("Temporary Customer ID stored " & _
"in a cookie:<br>")
Response.write( _
Request.Cookies("Conference_CartID").Value)
End If
End If
å 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 [email protected] 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 customer’s
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.
Public Function AddCustomer(fullName As String, email As
String, password As String) As String
å 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.Redirect("validOK.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:
strCustomerId = _
accountSystem.AddCustomer(txtFullName.Text, _
txtEmail.Text, txtPassword.Text)
Note Use the Text property of these controls because they are Web
controls.
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:
If (strCustomerId <> "") Then
' Set the user's authentication name to the customerId
FormsAuthentication.SetAuthCookie(strCustomerId, False)
' Migrate any existing shopping cart items into
' the permanent shopping cart
shoppingCart.MigrateCart(strTempCartID, strCustomerId)
' Redirect browser back to shopping cart page
Response.Redirect("ShoppingCart.aspx")
End If
å 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
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?
51
THIS PAGE INTENTIONALLY LEFT BLANK