Académique Documents
Professionnel Documents
Culture Documents
Released: 09/2001
Workbook
Introduction to Microsoft
ASP.NET
Part Number: X08-50211
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Course Number: 2063B
Part Number: X08-50211
Released: 09/2001
Introduction to Microsoft ASP.NET iii
Contents
Introduction
Course Materials ......................................................................................... 2
Prerequisites ............................................................................................... 3
Course Objectives........................................................................................ 4
Course Outline ................................ ................................ ............................ 5
Setup ......................................................................................................... 7
Lab Overview............................................................................................. 8
Lab Demonstration .................................................................................... 11
Microsoft Certified Professional Program..................................................... 13
Facilities................................................................................................... 15
Module 1: Working with Microsoft ASP.NET
Overview................................ ................................ ................................ .... 1
Introducing ASP.NET .................................................................................. 2
Creating Web Forms................................ ................................ .................. 11
Adding ASP.NET Code to a Page ................................................................ 23
Handling Page Events ................................................................................ 30
Discussion: ASP vs. ASP.NET.................................................................... 35
Lab 1: Using ASP.NET to Output Text......................................................... 36
Review..................................................................................................... 42
Module 2: Using Web Controls
Overview................................ ................................ ................................ .... 1
What Are Web Controls?.............................................................................. 2
Using Intrinsic Controls................................................................................ 4
Using Input Validation Controls ................................ ................................ .. 16
Selecting Controls for Applications .............................................................. 28
Lab 2: Using Web Controls ......................................................................... 29
Review..................................................................................................... 40
Module 3: Using Microsoft ADO.NET to Access Data
Overview................................ ................................ ................................ .... 1
Overview of ADO.NET................................................................................ 2
Connecting to a Data Source....................................................................... 11
Accessing Data with DataSets..................................................................... 13
Using Stored Procedures............................................................................. 28
Lab 3: Using ADO.NET to Access Data....................................................... 37
Accessing Data with DataReaders................................................................ 46
Binding to XML Data ................................................................................ 53
Review..................................................................................................... 59
Module 4: Separating Code from Content
Overview................................ ................................ ................................ .... 1
Advantages of Partitioning an ASP.NET Page................................................. 2
Creating and Using Code-Behind Pages.......................................................... 3
Creating and Using User Controls................................................................ 12
Creating and Using Components................................ ................................ .. 19
Lab 4: Separating Code from Content........................................................... 27
Review..................................................................................................... 39
iv Introduction to Microsoft ASP.NET
Module 5: Using Trace in Microsoft ASP.NET Pages
Overview................................ ................................ ................................ .... 1
Overview of Tracing................................ ................................ .................... 2
Trace Information........................................................................................ 3
Page-Level Trace......................................................................................... 4
Application-Level Trace............................................................................. 10
Lab 5: Adding Trace to an ASP.NET Page.................................................... 16
Review..................................................................................................... 21
Module 6: Using Web Services
Overview................................ ................................ ................................ .... 1
What Is a Web Service?................................................................................ 2
Calling a Web Service from a Browser ......................................................... 12
Calling a Web Service by Using a Proxy ...................................................... 15
Creating a Simple Web Service by Using Visual Basic ................................... 22
Creating and Calling a Web Service by Using Visual Studio .NET................... 26
Lab 6: Using Web Services ......................................................................... 35
Review..................................................................................................... 47
Module 7: Creating a Microsoft ASP.NET Web Application
Overview................................ ................................ ................................ .... 1
Requirements of a Web Application............................................................... 2
What Is New in ASP.NET?........................................................................... 3
Sharing Information Between Pages............................................................. 13
Securing an ASP.NET Application .............................................................. 24
Lab 7: Creating an ASP.NET Web Application ............................................. 38
Review..................................................................................................... 53
Introduction to Microsoft ASP.NET v
About This Course
This section provides you with a brief description of the course, audience,
suggested prerequisites, and course objectives.
Description
This three-day, instructor-led course exposes students to the features of
Microsoft ASP.NET and gives them hands-on experience (practices and labs)
in using and applying these features in their own Web applications.
Audience
This course is intended for Active Server Pages (ASP) Web developers. The
course assumes that students are familiar with Hypertext Markup Language
(HTML), client-side and server-side scripting, and Microsoft ActiveX Data
Objects (ADO).
Student Prerequisites
This course requires that students be able to do the following:
n Create forms and tables in HTML
n Write Microsoft Visual Basic or Visual Basic Scripting Edition
(VBScript code)
n Create an ASP page
n Retrieve data from a relational database by using ADO
The completion of the following courses will prepare the student to attend this
course:
n 1912A, Introduction to Web Development Technologies
n 1017A, Mastering Web Application Development Using Microsoft Visual
InterDev 6
Course Objectives
After completing this course, students will be able to:
n Create a Web form with server controls.
n Separate page code from content with code-behind pages, page controls, and
components.
n Display dynamic data from a data source by using ADO.NET and data
binding.
n Debug ASP.NET pages by using trace.
n Use a Web service to enhance a Web application.
n Add configuration, authentication, and state management to an ASP.NET
Web application.
vi Introduction to Microsoft ASP.NET
Student Materials Compact Disc Contents
The Student Materials compact disc contains the following files and folders:
n Autorun.exe. When the CD is inserted into the CD-ROM drive, or when you
double-click the autorun.exe file, this file opens the CD and allows you to
browse the Student Materials CD or install Internet Explorer.
n Default.htm. This file opens the Student Materials Web page. It provides
you with resources pertaining to this course, including additional reading,
review and lab answers, lab files, multimedia presentations, and course-
related Web sites.
n Readme.txt. This file contains a description of the compact disc contents and
setup instructions in ASCII format (that is, in plain text; not as a Microsoft
Word document).
n 2063B_ms.doc. This file is the Classroom Setup Guide. It contains a
description of classroom requirements, classroom setup instructions, and the
classroom configuration.
n AddRead. This folder contains additional reading pertaining to this course.
If there are no additional reading files, this folder does not appear.
n Appendix. This folder contains appendix files for this course. If there are no
appendix files, this folder does not appear.
n Democode. This folder contains demonstration code. If there is no
demonstration code, the Democode folder does not appear.
n Flash. This folder contains the installer for the Macromedia Flash 5.0
browser plug-in. If there are no Flash animations in the course, this folder
does not appear.
n Fonts. This folder contains fonts that are required to view the Microsoft
PowerPoint presentation and Web-based materials.
n Labs. This folder contains files that are used in the hands-on labs. These
files may be used to prepare the student computers for the hands-on labs.
n Media. This folder contains files that are used in multimedia presentations
for this course. If this course does not include any multimedia presentations,
this folder does not appear.
n Menu. This folder contains elements for autorun.exe.
n Mplayer. This folder contains files that are required to install Microsoft
Windows Media Player.
n Practices. This folder contains files that are used in the hands-on practices.
If there are no practices, the Practices folder does not appear.
n Sampapps. This folder contains the sample applications associated with this
course. If there are no associated sample applications, the Sampapps folder
does not appear.
n Sampcode. This folder contains sample code that is accessible through the
Web pages on the Student Materials CD. If there is no sample code, the
Sampcode folder does not appear.
n Sampsite. This folder contains files that create the sample site associated
with this course. If there is no sample site, the Sampsite folder does not
appear.
Introduction to Microsoft ASP.NET vii
n Webfiles. This folder contains the files that are required to view the course
Web page. To open the Web page, open Windows Explorer, and in the root
directory of the compact disc, double-click Default.htm or Autorun.exe.
n Wordview. This folder contains the Word Viewer that is used to view any
Word document (.doc) files that are included on the compact disc. If no
Word documents are included, this folder does not appear.
viii Introduction to Microsoft ASP.NET
Document Conventions
The following conventions are used in course materials to distinguish elements
of the text.
Convention Use
u Indicates an introductory page. This symbol appears next to a
topic heading when additional information on the topic is covered
on the page or pages that follow it.
bold Represents commands, command options, and syntax that must be
typed exactly as shown. It also indicates commands on menus and
buttons, dialog box titles and options, and icon and menu names.
italic In syntax statements or descriptive text, indicates argument names
or placeholders for variable information. Italic is also used for
introducing new terms, for book titles, and for emphasis in the
text.
Title Capitals Indicate domain names, user names, computer names, directory
names, and folder and file names, except when specifically
referring to case-sensitive names. Unless otherwise indicated, you
can use lowercase letters when you type a directory name or file
name in a dialog box or at a command prompt.
ALL CAPITALS Indicate the names of keys, key sequences, and key combinations
for example, ALT+SPACEBAR.
monospace Represents code samples or examples of screen text.
[ ] In syntax statements, enclose optional items. For example,
[filename] in command syntax indicates that you can choose to
type a file name with the command. Type only the information
within the brackets, not the brackets themselves.
{ } In syntax statements , enclose required items. Type only the
information within the braces, not the braces themselves.
| In syntax statements, separates an either/or choice.
Indicates a procedure with sequential steps.
... In syntax statements, specifies that the preceding item may be
repeated.
.
.
.
Represents an omitted portion of a code sample.
Contents
Introduction 1
Course Materials 2
Prerequisites 3
Course Objectives 4
Course Outline 5
Setup 7
Lab Overview 8
Lab Demonstration 11
Microsoft Certified Professional Program 13
Facilities 15
Introduction
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Introduction 1
Introduction
n Name
n Company Affiliation
n Title/Function
n Job Responsibility
n HTML, Visual Basic Programming, ASP, ADO, and
Database Experience
n Expectations for the Course
*****************************illegal for non-trainer use******************************
2 Introduction
Course Materials
n Name Card
n Student Workbook
n Student Materials Compact Disc
n Visual Studio .NET Beta 2 Compact Disc
n Course Evaluation
************** ***************illegal for non-trainer use******************************
The following materials are included with your kit:
n Name card. Write your name on both sides of the name card.
n Student workbook. The student workbook contains the material covered in
class, in addition to the hands-on lab exercises.
n Student Materials compact disc. The Student Materials compact disc
contains the Web page that provides you with links to resources pertaining
to this course, including additional readings, review and lab answers, lab
files, multimedia presentations, and course-related Web sites.
To open the Web page, insert the Student Materials compact disc into
the CD-ROM drive. Then, in the root directory of the compact disc, double -
click Autorun.exe or Default.htm.
n Visual Studio .NET Beta 2 compact disc. The course is being shipped with
the Visual Studio .NET Beta 2 compact disc because the courses
executable elements are compatible only with the Beta 2 version. The labs
and demonstrations in the course will not run with the final version of
ASP.NET.
n Course evaluation. At the conclusion of this course, please complete the
course evaluation to provide feedback about the instructor, course, and
software product. Your comments will help us improve future courses.
To provide additional comments or inquire about the Microsoft Certified
Professional program, send e-mail to mcp@msprograms.com.
Note
Introduction 3
Prerequisites
n Create forms and tables in HTML
n Write Visual Basic or VBScript code
n Create an Active Server Page
n Retrieve data from a relational database using ADO
*****************************illegal for non-trainer use******************************
This course requires that you meet the following prerequisites:
n Create forms and tables in Hypertext Markup Language (HTML)
n Write Microsoft Visual Basic or Visual Basic Scripting Edition
(VBScript code)
n Create an Active Server Page (ASP)
n Retrieve data from a relational database by using Microsoft ActiveX Data
Objects (ADO)
4 Introduction
Course Objectives
n Create a Web form with server controls
n Separate page code from content with code-behind
pages, user controls, and components
n Display dynamic data from a data source using
Microsoft ADO.NET and data binding
n Debug ASP.NET pages using trace
n Use a Web service to enhance a Web application
n Add configuration, authentication, and state
management to an ASP.NET Web application
*********************** ******illegal for non-trainer use******************************
After completing this course, students will be able to:
n Create a Web form with server controls.
n Separate page code from content with code-behind pages, user controls, and
components.
n Display dynamic data from a data source by using Microsoft ADO.NET and
data binding.
n Debug ASP.NET pages using trace.
n Use a Web service to enhance a Web application.
n Add configuration, authentication, and state management to an ASP.NET
Web application.
Introduction 5
Course Outline
n Module 1: Working with Microsoft ASP.NET
n Module 2: Using Web Controls
n Module 3: Using Microsoft ADO.NET to Access Data
n Module 4: Separating Code from Content
n Module 5: Using Trace in Microsoft ASP.NET Pages
n Module 6: Using Web Services
n Module 7: Creating a Microsoft ASP.NET Web
Application
*****************************illegal for non-trainer use******************************
Module 1, Working with Microsoft ASP.NET, introduces the ASP.NET
language. It provides an overview of the features of ASP.NET and introduces
the execution model of ASP.NET. The module also shows how to add server-
side code to the controls on a page. After completing this module, you will be
able to add server controls and code to an ASP.NET page.
Module 2, Using Web Controls, introduces the Web controls that are new
with ASP.NET. You will learn what a Web control is, how to add it to an
ASP.NET page, and how to access its properties, methods, and events. You will
learn how to use input validation controls and the DataGrid control. After
completing this module, you will be able to use Web controls in an ASP.NET
page.
Module 3, Using Microsoft ADO.NET to Access Data, describes how to
access data in an ASP.NET page by using ADO.NET. This module starts with
an overview and then moves into the specifics of how to use ADO.NET. After
completing this module, you will be able to access dynamic data from a data
source by using ADO.NET.
Module 4, Separating Code from Content, describes how to partition an
ASP.NET page to separate out the code. You learn about the various methods
that can be used to separate code from content, such as code-behind pages, user
controls, and components. After completing this module, you will be able to
create a code-behind page to hold code in an ASP.NET page.
Module 5, Using Trace in Microsoft ASP.NET Pages, demonstrates how to
use the trace feature of ASP.NET to debug ASP.NET pages. Both page-level
and application- level tracing are covered in the module. After completing this
module, you will be able to debug ASP.NET pages by using the trace feature.
6 Introduction
Module 6, Using Web Services, describes Web services and explains how
they expand a Web developers toolbox. You will learn how to use a Web
service and the code to create a simple Web service. After completing this
module, you will be able to use a Web service to enhance your Web application.
Module 7, Creating a Microsoft ASP.NET Web Application, describes the
technologies in ASP.NET that are necessary for creating real-world Web
applications, such maintaining state, global files, configuration and deployment,
and security. After completing this module, you will be able to create an
ASP.NET Web application by integrating ASP.NET pages.
Introduction 7
Setup
n Microsoft Windows 2000 Server
l Internet Information Services 5.0
n Microsoft SQL Server 2000, Standard Edition
n Microsoft Internet Explorer 5.5
n Microsoft Visual Studio .NET, Beta 2
n Microsoft .NET Framework SDK, Beta 2
n Lab and Demonstration Course Files
*****************************illegal for non-trainer use******************************
The following software and resource materials will be used in the classroom:
n Microsoft Windows 2000 Server
n Internet Information Services 5.0
n Microsoft SQL Server 2000, Standard Edition
n Microsoft Internet Explorer 5.5
n Microsoft Visual Studio .NET, Beta 2
n Microsoft .NET Framework software development kit (SDK), Beta 2
n Macromedia Flash player
n Lab and Demonstration Course files
Course Files
There are starter and solution files associated with the labs in this course. The
starter files are located in the folder <install folder>\Labs\Lab0x\Starter and the
solution files for this lab are in the folder <install folder>\Labs\Lab0x\Solution,
where Lab0x corresponds with the current lab.
There are files associated with the demonstrations in this course. These files are
located in the folder <install folder>\DemoCode\Mod0x, where Mod0x
corresponds with the current module.
If you performed a default installation of the course files,
<install folder> will be c:\Program Files\Msdntrain\2063.
Note
8 Introduction
Lab Overview
n Conference registration Web site
l View pre-conference tutorials
l View the conference tracks and sessions in each track
l View the conference proceedings
l Register for the conference
l Reserve a hotel room
*****************************illegal for non -trainer use******************************
The labs for this course build upon one another to create a complete application.
The lab application is a Conference Web site. On the Web site, users can view
the pre-conference tutorials and the sessions being offered in the different
tracks of the conference. They can choose from these offerings and then register
for the conference. They can also make a reservation at a hotel for the duration
of the conference.
The lab application uses a SQL Server database named Conf. For an illustration
of the Conf database schema, see Appendix B in Course 2063B, Introduction to
Microsoft ASP.NET.
Lab Application Files
The following is a list of all the files that are used by the lab application and
their purpose.
File name
Purpose
Lab file
is used in
_header.ascx User control that contains a heading for
each page of the Web site.
Multiple
_menu.ascx User control that contains a menu for the
Web site and is placed on each page of
the Web site.
Labs 3 and 4
AddToCart.aspx Adds a product to the shopping cart, then
redirects to the shopping cart page.
Multiple
CheckOut.aspx Allows users to view the information in
the shopping cart and then select the hotel
they want to stay in.
Lab 7
Conference.css Style sheet for the user interface. Multiple
Conflogo.swf Flash animation embedded in
Default.aspx page.
Multiple
Introduction 9
(continued)
File name
Purpose
Lab file
is used in
Web.config Configuration information. Lab 7
Default.aspx Home page for the Web application. Multiple
Errorpage.aspx Redirection page in case of any error. Multiple
Hotel_reservation.aspx Allows users to reserve a hotel room by
specifying the type of room and the dates
for which the room is needed.
Labs 2 and 6
Login.aspx Allows users to sign in to the conference
system by supplying their e-mail names
and passwords.
Labs 1 and 7
ProductDetails.aspx Outputs detailed information about pre-
conference tutorial, track, or proceedings.
Multiple
ProductsList.aspx Displays the different products (tutorials,
tracks, and proceedings) available in the
conference.
Labs 3, 4, and 5
Register.aspx Allows new users to register for the
conference.
Labs 2 and 7
SearchResults.aspx Outputs products based on search criteria. Multiple
ShoppingCart.aspx All code to manage the user interface (UI)
of the shopping cart.
Multiple
Component Files
The following is a list of all the files in the conference.dll component.
File name
Purpose
Lab file
is used in
ConferenceDB.vb Programmatic access to the database
connection string.
Multiple
CustomersDB.vb Programmatic access to the Customer
table in the database.
Multiple
GetProducts.vb Programmatic access to the
GetProductsByCategory stored
procedure.
Lab 4
mk.bat Makefile to create the component. Multiple
OrdersDB.vb Programmatic access to the Orders table
in the database.
Multiple
ProductsDB.vb Programmatic access to the Products
table in the database.
Multiple
10 Introduction
Web Services
The following is a list of all the Web Service files used by the lab application.
File name
Purpose
Lab file
is used in
Hotel_empty.asmx Web service for a hotel named Empty. Multiple
Hotel_full.asmx Web service for a hotel named Full. Lab 6
mkServices.bat Makefile to create a proxy for the Web
Services.
Lab 6
Introduction 11
Lab Demonstration
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how a user would use the Conference Web
application to register for a conference and reserve a room in a hotel.
To run the demonstration
1. Start Internet Explorer and enter the Uniform Resource Locator (URL) for
the lab solution Web site, http://localhost/labsolution. This displays the
home page default.aspx, which contains the two user controls: _header.ascx
and _menu.ascx.
2. On the home page, click Pre-Conference Tutorials to view the details of
all the tutorials that are offered on the ProductsList.aspx page.
3. Click on one of the subjects to obtain further details, such as the venue and
time for the tutorials, on the ProductDetails.aspx page.
4. Click Add to Cart to purchase the tutorial that you are viewing. This goes
to the ShoppingCart.aspx page.
You can also add an item to the shopping cart from the
ProductsList.aspx page.
5. On the ShoppingCart.aspx page, change the quantity of an item or delete it
from the cart, then click Update your Shopping Cart to see the changes.
6. Repeat steps 2-5 for the Conference Tracks and Conference Proceedings
links.
7. Enter a phrase in the Search text box and click Go! This calls the
SearchResults.aspx page and displays all conference items related to the
search string. You can also add items to the shopping cart from this page.
8. Click the Shopping Cart icon to jump to the ShoppingCart.aspx page.
Note
12 Introduction
9. Click Final Checkout to buy the items in the shopping cart.
10. If you have not already logged in to the application, you will need to log in
on the login.aspx page. Because you are new to the application, click Click
here! to enter your information into the database on the Register.aspx page.
A valid user name and password that you can use on the login.aspx
page is: someone@microsoft.com, password.
11. On the Register.aspx page, enter the requested information, and then click
Submit. This returns you to the ShoppingCart.aspx page.
12. On the ShoppingCart.aspx page, click Final Checkout again. This calls the
Checkout.aspx page.
13. Review the items in your order, and then click Submit for a final checkout.
14. Select a hotel to stay at. Click either Hotel Full or Hotel Empty. This calls
the hotel_reservation.aspx page.
15. In the hotel_reservation.aspx page, select a type of room, and then select the
dates for your stay. Next, click Submit.
Hotel Full will never have a room available; Hotel Empty will always
have a room available.
16. Click the Shopping Cart icon again to show that the shopping cart is now
empty.
Note
Note
Introduction 13
Microsoft Certified Professional Program
http://www.microsoft.com/trainingandservices/
*****************************illegal for non-trainer use******************************
The Microsoft Certified Professional program includes the following
certifications:
n Microsoft Certified Systems Engineer + Internet (MCSE + Internet)
n Microsoft Certified Systems Engineer (MCSE)
n Microsoft Certified Database Administrator (MCDBA)
n Microsoft Certified Solution Developer (MCSD)
n Microsoft Certified Professional + Site Building (MCP + Site Building)
n Microsoft Certified Professional + Internet (MCP + Internet)
n Microsoft Certified Professional (MCP)
n Microsoft Certified Trainer (MCT)
See the Certification section of the Web page provided
on the compact disc or the Microsoft Training and Certification Web site at
http://www.microsoft.com/trainingandservices/
You can also send e-mail to mcp@msprograms.com if you have specific
certification questions.
For More Information
14 Introduction
Exam Preparation Guides
To help prepare for the MCP exams, you can use the preparation guides that are
available for each exam. Each Exam Preparation Guide contains exam-specific
information, such as a list of the topics on which you will be tested. These
guides are available on the Microsoft Certified Professional Web site at
http://www.microsoft.com/trainingandservices/
MSDN Training curriculum helps you to prepare for Microsoft
Certified Professional (MCP) exams. However, no one-to-one correlation exists
between MSDN Training courses and MCP exams. Passing MCP exams
requires real-world experience with the productsMSDN Training courses
help get you started.
Important
Introduction 15
Facilities
Building Hours
Parking
Rest Rooms
Meals
Phones
Messages
Smoking
Recycling
Class Hours
*****************************illegal for non-trainer use******************************
THIS PAGE INTENTIONALLY LEFT BLANK
Contents
Overview 1
Introducing ASP.NET 2
Creating Web Forms 11
Adding ASP.NET Code to a Page 23
Handling Page Events 30
Discussion: ASP vs. ASP.NET 35
Lab 1: Using ASP.NET to Output Text 36
Review 42
Module 1: Working with
Microsoft ASP.NET
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 1: Working with Microsoft ASP.NET 1
Overview
n Introducing ASP.NET
n Creating Web Forms
n Adding ASP.NET Code to a Page
n Handling Page Events
n Discussion: ASP vs. ASP.NET
*****************************illegal for non-trainer use******************************
Microsoft Active Server Pages (ASP) technology is widely used to create
dynamic Web sites and applications. However, ASP has several limitations,
such as the need for redundant and lengthy coding to accomplish simple goals.
To overcome these limitations of ASP, Microsoft has developed a new
technology called Microsoft ASP.NET, which is a part of the Microsoft .NET
strategy for Web development. ASP.NET is a unified Web development
platform that provides the services necessary for developers to build enterprise-
class Web applications.
In this module, you will learn about the main features of ASP.NET and
discover the differences between ASP and ASP.NET. You will also learn about
server controls and see how to add server -side script to an ASP.NET page.
After completing this module, you will be able to:
n Identify the main features of ASP.NET.
n Identify the differences between ASP and ASP.NET.
n Describe the working model of ASP.NET.
n Describe the architecture of server controls.
n Add a Hypertext Markup Language (HTML) server control to a page.
n Access the properties and methods of server controls in code.
n Add event handlers for page events.
n Use the IsPostback property to handle postback forms.
2 Module 1: Working with Microsoft ASP.NET
u Introducing ASP.NET
n The Microsoft .NET Framework
n ASP.NET Features
n Animation: ASP.NET Execution Model
*****************************illegal for non-trainer use**************************** **
In this section, you will read an overview of the Microsoft .NET Framework
and see how ASP.NET fits in. Next, you will learn about the various features of
ASP.NET and see a working model. You will also learn about the main
differences between ASP and ASP.NET.
Module 1: Working with Microsoft ASP.NET 3
The Microsoft .NET Framework
.NET .NET
Framework Framework
Internet Internet
COM+ COM+
Orchestration Orchestration
Windows
.NET
Enterprise
Servers
Building Building
Block Block
Services Services
Visual Studio.NET
Base Class Library Base Class Library
ADO.NET: Data & XML ADO.NET: Data & XML
User User
Interface Interface
Common Language Runtime Common Language Runtime
Web Web
Services Services
*****************************illegal for non-trainer use******************************
The Microsoft .NET Platform provides all of the tools and technologies that are
needed to build distributed Web applications. It exposes a consistent, language-
independent programming model across all tiers of an application, while
providing seamless interoperability with and easy migration from existing
technologies.
The Microsoft .NET Platform is composed of several core technologies:
n The Microsoft .NET Framework
n The Microsoft .NET Building Block Services
n The Microsoft .NET Enterprise Servers
n Microsoft Visual Studio .NET
n Microsoft Windows. NET
The Microsoft .NET Framework is a set of technologies that is integral to the
Microsoft .NET Platform. It provides the basic building blocks for developing
Web applications and services. The Microsoft .NET Framework includes the
following components:
n Common Language Runtime
n Base class library
n Data
n Web forms and Web services
n WinForms
4 Module 1: Working with Microsoft ASP.NET
Common Language Runtime
The Common Language Runtime provides the programming interface between
the Microsoft .NET Framework and the programming languages available for
the Microsoft .NET Platform. It simplifies application development, provides a
robust and secure execution environment, supports multiple languages, and
simplifies application deployment and management. The run time loads and
runs code written in any run time-aware programming language. Code that
targets the run time is called managed code. Managed code simply means that
there is a defined contract of cooperation between natively executing code and
the run time itself. Responsibility for tasks like creating objects, making method
calls, and so on is delegated to the run time, which enables the run time to
provide additional services to the executing code.
Base Classes and Libraries
The Microsoft .NET Framework includes classes that encapsulate data
structures, perform Input/Output (I/O), provide access to information about a
loaded class, and provide a way to invoke security checks. It also includes
classes that encapsulate exceptions and other helpful functionality such as data
access, server-side user interface (UI) projections, and rich graphical user
interface (GUI) generation. The Microsoft .NET Framework provides both
abstract base classes and class implementations derived from those base classes.
You can use these derived classes as is or derive your own classes from them.
The Microsoft .NET Framework classes are named using a dot-syntax naming
scheme that connotes a naming hierarchy. This technique is used to group
related classes logically together so that they can be searched and referenced
more easily. A grouping of classes is called a namespace. For example, a
program can use classes in the System.Data.SqlClient namespace to read data
from a SQL Server database.
The root namespace for the Microsoft .NET Framework is the System
namespace.
Data
Microsoft ADO.NET is the next generation of ActiveX Data Object (ADO)
technology. ADO.NET provides improved support for the disconnected
programming model and also provides rich Extensible Markup Language
(XML) support. ADO was created to provide data services to traditional client
applications that were tightly coupled to the database; consequently it was not
effective for Web applications. ADO.NET was created with the characteristics
of Web applications in mind.
Web Forms and Web Services
ASP.NET is a programming framework built on the Common Language
Runtime that can be used on a server to build powerful Web applications.
ASP.NET Web forms provide an easy and powerful way to build dynamic user
interfaces. ASP.NET Web services provide the building blocks for constructing
distributed Web-based applications. Web services are based on the Simple
Object Access Protocol (SOAP) specification.
Module 1: Working with Microsoft ASP.NET 5
Win Forms
For applications that are based on Microsoft Windows, the Microsoft .NET
Framework provides the System.Windows.Forms namespace to create the user
interface. You can use System.Windows.Forms to do rapid application design
(RAD). It provides inheritance in the same client user interface library. You can
build components by using inheritance and then aggregate them by using a form
designer such as Microsoft Visual Basic .
6 Module 1: Working with Microsoft ASP.NET
ASP.NET Features
n Multiple Language Support
n Increased Performance
l Compiled code
l Cache
n Classes and Namespaces
n Server Controls
n Web Services
*****************************illegal for non-trainer use******************************
ASP.NET is more than just the next version of ASP. It is a totally re-architected
technology for creating dynamic, Web-based applications. ASP pages use
the .asp extension and ASP.NET pages use the extension .aspx.
Both ASP and ASP.NET pages can be used on the same Web site.
Existing ASP pages will still work along with new ASP.NET pages; they do not
need to be converted into ASP.NET pages.
ASP.NET, with a host of new features, allows developers to write cleaner code
that is easy to reuse and share. ASP.NET boosts performance and scalability by
offering access to compiled languages. Some of the main features of ASP.NET
are described below.
Multiple Language Support
ASP.NET provides a true language-neutral execution framework for Web
applications.
You can currently use over 20 languages to build .NET applications. Microsoft
has compilers for Visual Basic, Microsoft Visual C#
. When you run the Web form, the code-behind class file
runs and dynamically produces the output for your page.
In this section, you will learn how code-behind pages work. You will also learn
how to create a code-behind class file in Visual Basic.
4 Module 4: Separating Code from Content
Understanding How Code-Behind Pages Work
n Use Page Directive to Link
the Two Files
n Call Procedures in the Code-
Behind Page
n Create Separate Files for User
Interface and Interface Logic
<%@ Page Inherits="myDemo"
Src="demo.vb"%>
<%@ Page Inherits="myDemo"
Src="demo.vb"%>
ds = getData()
ds = getData()
Public Class myDemo
Public Function getData()
End Function
End Class
Public Class myDemo
Public Function getData()
End Function
End Class
demo.vb
<%@Page
Inherits="myDemo"
Src= "demo.vb" %>
Page.aspx
*****************************illegal for non-trainer use******************************
Creating code-behind pages is relatively simple. It involves creating two
separate files, one for the user interface and the other for the user interface logic.
The interconnectivity between these two files is provided through the @Page
directive, which is used to specify optional settings at the page level.
Creating a User Interface File
First, you create the HTML for the interface. The interface file is an ASP.NET
page (that uses the .aspx extension). The first line of the interface ASP.NET
page is an @Page directive that specifies the name of the code-behind file and
the actual class name inside the code-behind file that will be used.
In the following example, the ASP.NET page is linked to the demo.vb class file.
The Inherits attribute specifies the class file to be used and the Src attribute
indicates the path to the class file itself.
<%@Page Language=" vb" I nher i t s=" myDemo" Sr c=" demo. vb" %>
Specifying the path to the class file is optional. If the path is omitted,
ASP.NET looks for the class file in the /bin directory of the application.
Creating a Code-Behind File
Next, you create a separate class file, in any of the supported languages, that
provides the functionality required for the user interface page. A code-behind
class file is identical to any other class file that you create in a particular
language.
In Visual Basic, the class file has a .vb extension. In Visual C#, the code-behind
page has a .cs extension. This ensures that the code-behind file is passed to the
correct compiler when the page is first executed.
Note
Module 4: Separating Code from Content 5
Using Code-Behind Procedures
To call a function or sub-procedure in a code-behind page, preface the name of
the procedure with the name of the code-behind page. For example, in the class
myDemo, in the code-behind page demo.vb, a function named getData returns
a DataSet object. The following sample code calls the getData function and
then displays the returned DataSet (ds) in the DataGrid control (dgAuthors).
Publ i c Sub Page_Load ( Sr c As Obj ect , E As Event Ar gs)
Di mds As Dat aSet
ds = get Dat a( )
dgAut hor s. Dat aSour ce=ds
dgAut hor s. Dat aMember =" Aut hor s"
dgAut hor s. Dat aBi nd( )
End Sub
6 Module 4: Separating Code from Content
Creating a Class File in Visual Basic
n Class File
n Using Objects from the ASP.NET Environment
n Inheriting from the ASP.NET Page Class
Public Class myDemo
Public Function getData() As DataSet
End Function
End Class
Public Class myDemo
Public Function getData() As DataSet
End Function
End Class
Imports System
Imports System.Web
Imports System
Imports System.Web
Public Class myDemo
Inherits System.Web.UI.Page
End Class
Public Class myDemo
Inherits System.Web.UI.Page
End Class
*****************************illegal for non-trainer use********************** ********
A code-behind class file is identical to any other class file that you might create
in your chosen programming language. The basic structure of a Visual Basic
class file looks like the following:
Publ i c Cl ass cl ass_name
Publ i c var i abl e_name As var i abl e_t ype
Publ i c Funct i on f unct i on_name( par amet er s) As r et ur n_ t ype
End Funct i on
Publ i c Sub sub_name( par amet er s)
End Sub
End Cl ass
Notice that, in the above class declaration, the functions, sub-procedures,
and the class are all public. Public procedures are used to invoke code-behind
pages from the user interface page.
Note
Module 4: Separating Code from Content 7
To convert the preceding class file structure into a code-behind class file, you
need to perform two steps:
1. Use the objects from the ASP.NET environment.
You need to import the objects from the ASP.NET environment that you
need to use in a class file. By default, all objects in an ASPX page import
the objects from the ASP.NET environment. However, this is not true for a
class file. Therefore, a class file, at the minimum, needs to import the
System and Web libraries from the ASP.NET environment. This is done as
follows:
I mpor t s Syst em
I mpor t s Syst em. Web
2. Inherit from the ASP.NET Page class.
Your class must inherit from the ASP.NET Page class so that it can be
integrated into the ASP.NET page in which it is used. This is done with the
Inherits statement.
Publ i c Cl ass cl ass_name
I nher i t s Syst em. Web. UI . Page
End Cl ass
The following is a code-behind page with one class named myDemo, and one
public function named getData. The function reads data from a database and
returns it to the user interface page as a DataSet object.
I mpor t s Syst em
I mpor t s Syst em. Web
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent
Publ i c Cl ass myDemo
I nher i t s Syst em. Web. UI . Page
Publ i c Funct i on get Dat a( ) As Dat aSet
Di mds As Dat aSet
Di mconn As Sql Connect i on
Di mcmdAut hor s As Sql Dat aAdapt er
conn = New Sql Connect i on _
( " ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs" )
cmdAut hor s = New Sql Dat aAdapt er _
( " sel ect * f r omAut hor s" , conn)
ds = new Dat aSet ( )
cmdAut hor s. Fi l l ( ds, " Aut hor s" )
r et ur n ( ds)
End Funct i on
End Cl ass
8 Module 4: Separating Code from Content
Demonstration: Creating a Code-Behind Page
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create a code-behind page and use it
from an ASP.NET page.
To run the demonstration
1. Edit the page <install folder>\Democode\Mod04\beforeCodeBehind.aspx
using Notepad.
This page has both code and content.
2. Open the files codeBehindDemo.vb and codeBehind.aspx in the folder
<install folder>\Democode\Mod04.
The file codebehind.aspx cannot be opened in Visual
Studio .NET. You must use Notepad or another text editor.
These files perform the same function as the beforeCodeBehind.aspx page,
but use a code-behind page.
3. View the page codeBehind.aspx in Microsoft Internet Explorer.
Important
Module 4: Separating Code from Content 9
To demonstrate using code-behind pages in Microsoft
Visual Studio .NET
Visual Studio .NET uses code-behind pages by default.
1. Add a new Web form to a Visual Studio .NET project.
2. Add a label Web control and a button Web control from the toolbox to the
page.
3. View the HTML for the page and notice the attributes of the @Page
directive.
4. Return to Design view and double-click the button Web control.
This opens the code-behind page, and creates a click event procedure for the
button.
Publ i c Sub But t on1_Cl i ck( ByVal sender As Syst em. Obj ect , _
ByVal e As Syst em. Event Ar gs) Handl es But t on1. Cl i ck
End Sub
5. Add code to change the Text property of the label control.
Label 1. Text = " cl i cked"
6. Build the project.
In Visual Studio .NET, the code-behind pages are compiled into an
assembly. You need to build the project before they will be accessible.
7. View the page in Internet Explorer.
10 Module 4: Separating Code from Content
Accessing Controls in a Code-Behind Page
n Import Namespaces for Controls
n Declare Variables with Same Name as Controls
n Reference Properties of Controls
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Dim lbl As Label
Dim txt As TextBox
Dim lbl As Label
Dim txt As TextBox
Public Sub btn_Click (s as Object, e As EventArgs)
lbl.Text = "You are searching for " & txt.Text
End Function
Public Sub btn_Click (s as Object, e As EventArgs)
lbl.Text = "You are searching for " & txt.Text
End Function
*****************************illegal for non-trainer use******************************
You can create event procedures for the controls on a form in a code-behind
page. In this way, you can transfer most of the code from the user interface
page to a code-behind page.
To do this, you need to import the namespace for the controls you are using,
either System.Web.UI.WebControls or System.Web.UI.HtmlControls. You
then need to declare public variables for the controls on the ASPX page.
For example, the following is a form on the ASPX page with three controls:
<f or m r unat =ser ver >
<asp: t ext box i d="t xt " r unat ="ser ver " / >
<asp: but t on i d=" bt n" oncl i ck=" bt n_cl i ck"
t ext =" Cl i ck Me" r unat =" ser ver " / >
<P><asp: l abel i d=" l bl " r unat =" ser ver " / >
</ f or m>
Module 4: Separating Code from Content 11
The code-behind page can include the event procedure and reference the
controls on the page, as shown in the following example:
I mpor t s Syst em
I mpor t s Syst em. Web
I mpor t s Syst em. Web. UI . WebCont r ol s
Publ i c Cl ass myDemo
I nher i t s Syst em. Web. UI . Page
Publ i c l bl As Label
Publ i c t xt As Text Box
Publ i c Sub bt n_cl i ck( s As Obj ect , e As Event Ar gs)
l bl . Text = t xt . Text
End sub
End Cl ass
12 Module 4: Separating Code from Content
u Creating and Using User Controls
n Creating a User Control
n Using a User Control in an ASP.NET Page
n Demonstration: Creating a User Control
*****************************illegal for non-trainer use******************************
A user control is an ASP.NET page that is imported as a server control by
another ASP.NET page. User controls provide an easy way to partition and
reuse simple and common user interface (UI) functionality across a Web
application. User controls are not pre-compiled. However, because all
ASP.NET pages are compiled as soon as they are requested, user controls are
compiled on demand and cached in server memory.
User controls have many advantages:
n User controls are self-contained. They provide separate variable namespaces,
which means that none of the methods and variables of the user control
conflict with any existing methods and variables of the hosting page.
n User controls can be used more than once within a hosting page without
causing variable and method conflicts.
n User controls can be written in a different language from the main hosting
page.
The main difference between code-behind pages and user controls is that code-
behind pages mainly involve inheriting code classes into a page and user
controls also allow you to generate parts of the user interface.
Module 4: Separating Code from Content 13
Creating a User Control
n User-Defined Server Control with an . ascx Extension
l <%@ Control Language="vb" %>
l Contains HTML but not <HTML>, <BODY>, or <FORM>
l Contains code to handle its own events
n Public Properties and Methods are Promoted to
Properties and Methods of the Control in the Host Page
Public Property pNum As Integer
Get
Return CInt(txtNum.Text)
End Get
End Property
Public Property pNum As Integer
Get
Return CInt(txtNum.Text)
End Get
End Property
*****************************illegal for non-trainer use******************************
User controls are ASP.NET pages used as server controls. User controls have
an .ascx extension. This file extension ensures that the user controls page
cannot be executed as a stand-alone ASP.NET page. User controls largely
replace include files. They are used to address the same problems that were
solved by using include files, such as dealing with headers, navigation bar,
repeating blocks of code, and so on.
A user control consists of HTML and code, but because user controls are
included in existing pages, they do not contain <head>, <body>, or <form> tags.
Those tags are included in the host ASP.NET page. User controls participate in
the complete execution life cycle of every request and can handle their own
events, encapsulating some of the page logic from the containing ASP.NET
page. For example, a user control can handle its own postback in its
Page_Load event procedure.
14 Module 4: Separating Code from Content
The following code is the HTML part of a user control that combines a text box
and two input validation controls:
<%@Cont r ol Language=" vb" %>
<asp: t ext box i d=" t xt Num" r unat =" ser ver " / >
<asp: Requi r edFi el dVal i dat or i d=" t xt NumVal i dat or "
r unat ="ser ver "
cont r ol ToVal i dat e=" t xt Num"
er r or Message="You must ent er a val ue"
di spl ay="dynami c">
</ asp: Requi r edFi el dVal i dat or >
<asp: RangeVal i dat or i d=" t xt NumRngVal i dat or " r unat =" ser ver "
cont r ol ToVal i dat e=" t xt Num"
er r or Message=" Pl ease ent er a number bet ween 0 and 99"
t ype="I nt eger "
mi ni mumVal ue="0"
maxi mumVal ue="99"
di spl ay="dynami c">
</ asp: RangeVal i dat or >
To expose values of controls to the containing page, create public properties.
For example, the following code creates a property named pNum that is the
Text property of the text box control in the user control:
<SCRI PT l anguage=" VB" r unat =" Ser ver " >
Publ i c Pr oper t y pNumAs I nt eger
Get
Ret ur n CI nt ( t xt Num. Text )
End Get
Set
t xt Num. Text = Val ue. ToSt r i ng( )
End Set
End Pr oper t y
</ SCRI PT>
All public variables, properties, and methods of a user control are promoted to
properties (that is, tag attributes) and methods of the control in the containing
page.
Module 4: Separating Code from Content 15
@Control directive
You can also have code-behind pages for user controls. The @Control
directive is used to reference a user control from a code-behind page. It also
defines user-control-specific attributes used by the ASP.NET page parser and
compiler. This directive can only be used with user controls.
<%@Cont r ol at t r i but e=val ue [ at t r i but e=val ue ] %>
For example, to reference a code-behind page for a user control, you use the
following line of code:
<%@Cont r ol I nher i t s=" myDemo" sr c=" demo. vb" %>
The @Control directive supports the same attributes as the @Page
directive, except the AspCompat and Trace attributes. To enable tracing, you
must add the Trace attribute to an @Page directive in the ASPX page that
contains the user control. You can only include one @Control directive
per .ascx file.
Note
16 Module 4: Separating Code from Content
Using a User Control in an ASP.NET Page
n Include User Controls in Another ASP.NET Page Using
the Register Directive
n Insert the User Control Like a Server Control
n Set Properties of the User Control
<%@ Register TagPrefix="conference"
TagName="validNum" Src="numberBox.ascx" %>
<%@ Register TagPrefix="conference"
TagName="validNum" Src="numberBox.ascx" %>
<conference:validNum id="num1"
runat="server"/>
<conference:validNum id="num1"
runat="server"/>
num1.pNum = 5
num1.pNum = 5
*****************************illegal for non-trainer use******************************
User controls are included in an ASP.NET page by using the @Register
directive:
<%@Regi st er TagPr ef i x=" conf er ence" TagName=" val i dnum"
Sr c=" number box. ascx" %>
The TagPrefix attribute determines a unique namespace for the user control so
that multiple user controls with the same name can be differentiated from each
other. The TagName attribute is the unique name for the user control. The Src
attribute is the virtual path to the user control file. After registering the user
control with the @Register directive, you can place the user control tag in the
ASP.NET page just as you would an ordinary server control (including the
runat="server" attribute).
<conf er ence: val i dNumi d=" num1" r unat =" ser ver " / >
<conf er ence: val i dNumi d=" num2" r unat =" ser ver " / >
When the main ASP.NET page is loaded, the run-time framework compiles the
user control file and makes it available to the page.
After the user control is available to the page, you can access its properties as
follows:
l bl Sum. Text = ( num1. pNum+ num2. pNum) . ToSt r i ng( )
Module 4: Separating Code from Content 17
Demonstration: Creating a User Control
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create and use a user control.
The files numberbox.ascx and add.aspx in the folder
<install folder>\Democode\Mod04 contain the completed code for this
demonstration.
To run the demonstration
1. Open the page <install folder>\Democode\Mod04\beforeuser.aspx.
This page has all controls and logic in one file.
2. Open the page numberbox.ascx in the folder
<install folder>\Democode\Mod04.
Numberbox.ascx is a user control that performs the same function as each
text box on the page beforeuser.asps.
3. Add the @Register directive to the beforeuser.aspx page to use the
numberbox.ascx user control.
<%@Regi st er TagPr ef i x=" demos" TagName=" val i dNum"
Sr c=" number box. ascx" %>
4. Delete the four input validation controls from the beforeuser.aspx page.
5. Change the two text box controls to be <demos:validNum> controls. Use
the same ID values.
Num1: <demos: val i dNumi d=" t xt Num1" r unat =" ser ver " / >
Num2: <demos: val i dNumi d=" t xt Num2" r unat =" ser ver " / >
18 Module 4: Separating Code from Content
6. Change the Submit event procedure to read values from the user controls.
Sub submi t ( s As Obj ect , e As Event Ar gs)
I f Page. I sVal i d Then
l bl Sum. Text = _
CSt r ( Conver t . ToI nt 32( t xt Num1. pNum) + _
Conver t . ToI nt 32( t xt Num2. pNum) )
End I f
End Sub
7. View the beforeuser.aspx page in Internet Explorer.
8. View the HTML source in Internet Explorer.
Module 4: Separating Code from Content 19
u Creating and Using Components
n Deploying Components
n Creating Components
n Using Components in an ASP.NET Page
n Demonstration: Creating and Using a Component
*****************************illegal for non-trainer use******************************
In ASP.NET, business objects are the building blocks for multi-tiered Web
applications, such as those with a layer for data access or common application
rules. In this section, you will learn how to write some simple components and
include them in your ASP.NET pages.
The classic use for an external component is in a two-tier scenario to perform
data access. This simplifies the code in your page, improving readability and
separating your UI logic from the back-end functionality.
The three-tiered application model extends the two-tiered scenario to include
business rules between the UI and data access logic. The three-tiered model
allows UI developers to work with a higher level of abstraction rather than
directly manipulating data through low-level data access component application
programming interfaces (APIs). The middle business component typically
enforces business rules and ensures that the relationships and primary key
restraints of the database are enforced.
20 Module 4: Separating Code from Content
Deploying Components
n No Registration Required
l Components may be deployed by simply copying to the /bin dir or
performing an FTP file transfer
n No Server Restart Required
l The Web server does not require a restart when you change your
application
l New requests immediately begin execution against the changed file
n No Namespace Conflicts
l Each assembly loaded from /bin is limited in scope to the application
in which it is running
*****************************illegal for non -trainer use******************************
A problem with using the classic Component Object Model (COM) model for
Web application components is that the components must be registered on the
server before they can be used from a traditional ASP application. Remote
administration of these components is often not possible, because the
registration utility must be run locally on the server. In addition, these
components remain locked on disk after they are loaded by an application and
the entire Web server must be stopped before these components can be replaced
or removed.
ASP.NET solves these problems by allowing components to be placed in a
well-known directory that is automatically found at run time. This directory is
named /bin, and is located immediately under the root directory for the
application.
Following are the advantages of storing components in the /bin directory:
n No registration required
No registration is required to make components available to the ASP.NET
application. Components may be deployed by simply copying a file to the
/bin directory or performing a File Transfer Protocol (FTP) file transfer.
n No server restart required
When the component is changed by replacing a .dll in the /bin directory,
new requests by ASP.NET applications immediately begin execution
against the changed file(s). ASP.NET allows currently executing requests to
complete before the old application is replaced with the updated
component(s). The Web server does not require a restart when you change
components.
n No namespace conflicts
Each component loaded from /bin is limited in scope to the application in
which it is running. This means that many applications could potentially use
different components with the same class or namespace names, without
conflict.
Module 4: Separating Code from Content 21
Creating Components
n A Component Is Basically a Class
n Creating a Component
n Compiling the Class
Imports System.Data.SQL
Namespace myComponent
Public Class ConferenceDB
Public Function getCategories(...)
End Class
End Namespace
Imports System.Data.SQL
Namespace myComponent
Public Class ConferenceDB
Public Function getCategories(...)
End Class
End Namespace
vbc /t:library /out:component.dll component.vb
vbc /t:library /out:component.dll component.vb
*****************************illegal for non-trainer use******************************
A component at its most basic level is simply a class. The component can be
instantiated from an ASP.NET page that imports the component.
Code-Behind vs. Components
A code-behind page is an uncompiled class file. It does not define a namespace
that can be used by many applications. Instead, it defines a class that the .aspx
page inherits from. Therefore, the .aspx page can immediately call methods and
use properties of the code-behind page; you do not need to instantiate an object.
An .aspx page uses a code-behind page by adding the following to the @Page
directive:
Code-Behind Example
<%@Page Language=" vb" I nher i t s=" myDemo" Sr c=" demo. vb" %>
A component is always compiled into a dynamic-link library (DLL). Any page
can access the DLL. You need to instantiate an object of the class before calling
its methods. An ASPX page uses a component by adding the following code:
Component Example
<%@I mpor t Namespace=" myComponent " %>
22 Module 4: Separating Code from Content
Creating a Component
A component class file includes a namespace declaration and class declarations.
Namespace myComponent
Publ i c Cl ass Conf er enceDB
. . .
End Cl ass
End Namespace
Namespaces are used as an organizational system. They provide a way to
present program components that are exposed to other programs and
applications. Namespaces are always Public; however, the classes within the
namespace may have Public, Friend, or Private access.
Just as you would with code-behind pages, you need to import any libraries that
you use in the page.
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent
The following code is an example of a simple class called the ConferenceDB
class. This class has a function that retrieves a list of categories from the
database.
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent
Namespace myComponent
Publ i c Cl ass Conf er enceDB
Publ i c Funct i on get Cat egor i es _
( conn As Sql Connect i on) As Dat aSet
' Ret r i eve a l i st of cat egor i es f r omt he dat abase
End Funct i on
End Cl ass
End Namespace
Example
Module 4: Separating Code from Content 23
Compiling the Component
To compile this class, you can either click Build on the Build menu in Visual
Studio .NET or run the compiler from the MS-DOS command prompt. The /t
option tells the compiler that you want to build a library (.dll), and the /out
option tells the compiler where to place the resulting assembly. An assembly is
a collection of resources that are built to work together to deliver a cohesive set
of functionality. An assembly carries all the rules necessary to ensure cohesion
of functionalities. It is the unit of access to the resources in the Common
Language Runtime (CLR).
vbc / t : l i br ar y / out : component . dl l component . vb
If the component imports other libraries, you must reference them in the
compile statement. For example, if you are using the System.Data namespace,
include the System.Data.dll library, as shown in the following example:
vbc / t : l i br ar y / out : component . dl l / r : Syst em. Dat a. dl l
component . vb
Finally, after compiling the component, move it to the \bin folder in the root of
the virtual directory for your Web site.
You must define a virtual directory for your Web site.
The component is now available for use in an ASP.NET page.
Important
24 Module 4: Separating Code from Content
Using Components in an ASP.NET Page
n Adding a Component
n Using the Component
<%@ Import Namespace="myComponent" %>
<%@ Import Namespace="myComponent" %>
Dim x As New ConferenceDB
ds = x.getCategories(conn)
Dim x As New ConferenceDB
ds = x.getCategories(conn)
component.dll
Namespace myComponent
Class ConferenceDB
End Class
End Namespace
*****************************illegal for non-trainer use******************************
By default, ASP.NET loads all assemblies from the /bin directory when the
application is started. The assemblies to load are specified through the
configuration system. Additional assemblies may also be imported into an
application by using the configuration file.
Because the assembly is pre-loaded by the ASP.NET run time, only a simple
namespace import or variable declaration is required to make the component
available.
There are two ways to use the classes defined in a component. You can either
import the namespace by using an @Import directive, or reference the
namespace when declaring a variable.
Using the @Import directive
To include any component in an ASP.NET page, you need to add the @Import
directive that specifies the namespace to include at the top of the page. For
example, to include the myComponent component, you add the following
directive at the top of the page:
<%@I mpor t Namespace=" myComponent " %>
You can then instantiate an object of the class by referencing the class name
directly, as shown in the following example.
Di mx As New Conf er enceDB
Module 4: Separating Code from Content 25
Referencing Namespace when Declaring a Variable
You can also declare a variable directly from a component, without adding the
@Import directive to the page, by referencing the namespace in the declaration.
For example, to declare a variable from the myComponent component, use the
following code:
Di mx As New myComponent . Conf er enceDB
If you create and compile the component in Visual Studio .NET, you will
need to preface the namespace with the name of the Visual Studio .NET project.
For example, if the component.vb file is located in a Visual Studio .NET project
named demos, you would use the following Imports statement or variable
declaration to reference it:
<%@I mpor t Namespace=" demos. myComponent " %>
or
Di mx As New demos. myComponent . Conf er enceDB
Calling Component Methods
After you have instantiated an object from the class, you can access its
properties and methods. The following example shows how to call the
getCategories method of the ConferenceDB class.
ds = x. get Cat egor i es( conn)
Note
26 Module 4: Separating Code from Content
Demonstration: Creating and Using a Component
*****************************illegal for non-trainer use******************************
In this demonstration, you will see a simple component and how to use it in an
ASP.NET page.
To run the demonstration
1. Open the file component.vb from the folder
<install folder>\DemoCode\Mod04.
2. Compile the file (manually, or using Visual Studio .NET).
a. If you use the batch file mkdemos.bat to compile the component, you
need to create a \bin folder in the <install folder> folder, which is the
root of the 2063 virtual directory, and move the component.dll file into it.
b. If you build in Visual Studio .NET, the assembly is automatically moved
to the \bin folder of the project, but you will need to change the
@Import directive in the displaycomponent.aspx page to:
<%@I mpor t Namespace=" pr oj ect name. myComponent " %>
3. Open the displaycomponent.aspx page.
The @Import directive imports the namespace from the component. The
getCategories function is called in the Page_Load event procedure.
4. View the displaycomponent.aspx page in Internet Explorer. View the source
HTML of the page.
The code from the component was not added to the file.
Module 4: Separating Code from Content 27
Lab 4: Separating Code from Content
*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Create a user control.
n Insert a user control into an .aspx page.
n Create and use components.
Prerequisite
Before working on this lab, you must know how to use Web controls in an
ASP.NET page.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab04\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab04\Solution.
The ASPNET Web application uses classes in the Conference component.
There are five files in this component: ConferenceDB.vb, CustomersDB.vb,
ProductsDB.vb, ShoppingCartDB.vb, and OrdersDB.vb. These files are in the
Components folder of the ASPNET Web application. If, for any reason, you
need to rebuild the Conference component, run the mk.bat batch file from a
command prompt. The mk.bat batch file creates the conference.dll component
and then puts it in the bin folder of the ASPNET Web application.
28 Module 4: Separating Code from Content
Scenario
All the Web pages in the ASPNET Web site have the same controls at the top
and down the left side of the page. These controls can be put into user controls
and then easily added to the pages. In Exercise 1, you will create a user control
and in Exercise 2, you will add the user control to the ProductsList.aspx page.
Also, many of the pages in the ASPNET Web site use data obtained from the
Conference database. In Exercise 3, you will create a component to isolate and
reuse the data access code. In Exercise 4, you will call methods on your
component from the ProductsList.aspx page.
Estimated time to complete this lab: 60 minutes
Module 4: Separating Code from Content 29
Exercise 1
Creating a Menu User Control
In this exercise, you will convert an .aspx page into a user control. The page
Menu.aspx reads categories of data from the database and displays them in a
DataList Web control. In this exercise, you will convert the Menu.aspx page
into a user control.
To create the user control file
1. Open the file named Menu.aspx from the ASPNET Web site.
2. Remove the HTML tags.
3. Remove the BODY tags.
4. Change the @Page directive into an @Control directive.
<%@Cont r ol Language=" vb" %>
5. Save the page as _Menu.ascx (overwrite the existing _Menu.ascx file).
30 Module 4: Separating Code from Content
Exercise 2
Using User Controls
In this exercise, you will add two user controls to the ProductsList.aspx page.
One control will be located along the top of the page and can be found in the
file _header.ascx. The other will be located at the left side of the page and can
be found in the file _menu.ascx that you just created in Exercise 1.
When you are finished with this exercise, the page ProductsList.aspx should
look like the following illustration.
To add the header and menu user controls
1. Open the page ProductsList.aspx in the ASPNET Web site.
2. Include the header and menu user controls at the beginning of the page by
using the @Register directive. Set the attributes for the controls as shown in
the following table.
TagPrefix TagName Src
Conference Header _Header.ascx
Conference Menu _Menu.ascx
Your code should look like the following:
<%@Regi st er TagPr ef i x=" Conf er ence" TagName=" Header "
Sr c=" _Header . ascx" %>
<%@Regi st er TagPr ef i x=" Conf er ence" TagName=" Menu"
Sr c=" _Menu. ascx" %>
Module 4: Separating Code from Content 31
3. Create an HTML table in the body of the page to hold the two user controls
and the contents of the original page. You will need to build the table
around the existing contents of the page.
HEADER
M
E
N
U
CONTENT
Your HTML code should look like the following:
<t abl e wi dt h=" 100%" bor der =0>
<t r ><t d>
<!- - _Header . ascx user cont r ol - - >
</ t d></ t r >
<t r ><t d>
<t abl e bor der =0>
<t r ><t d val i gn=" t op" >
<! - - _Menu. ascx user cont r ol - - >
</ t d>
<t d>
<! - - Exi st i ng cont ent s of t he page - - >
<! - - bet ween <body> and </ body> t ags - - >
</ t d>
</ t r >
</ t abl e>
</ t d></ t r >
</ t abl e>
32 Module 4: Separating Code from Content
4. Add the header and menu user controls to the correct position in the table.
Your HTML code should look like the following:
<t abl e wi dt h=" 100%" bor der =0>
<t r ><t d>
<!- - _Header . ascx user cont r ol - - >
<Conf er ence: Header r unat =" ser ver " / >
</ t d></ t r >
<t r ><t d>
<t abl e bor der =0>
<t r ><t d val i gn=" t op" >
<! - - _Menu. ascx user cont r ol - - >
<Conf er ence: Menu r unat =" ser ver " / >
</ t d>
<t d>
<! - - Exi st i ng cont ent s of t he page - - >
<! - - bet ween <body> and </ body> t ags - - >
</ t d>
</ t r >
</ t abl e>
</ t d></ t r >
</ t abl e>
To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer, go to the ProductsList page of the ASPNET Web
site by viewing:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
CategoryID=15 corresponds to the Conference Trackscategory in
the Categories table of the database.
Notice the header and menu user controls.
Note
Module 4: Separating Code from Content 33
Exercise 3
Building a Component
Currently, the page ProductsList.aspx reads data from the database and displays
it in a Repeater control. In this exercise, you will build a component,
GetProducts.vb, to read the data from the database. Then, in Exercise 4, you
will use that component in the ProductsList.aspx page.
To create the GetProducts.vb component
1. Create a new file named GetProducts.vb in the Components folder of the
ASPNET Web site.
If you are using Visual Studio .NET, do the following:
a. Right-click on the Components folder in the ASPNET project in the
Solution Explorer window, click Add, and then click Add Component.
b. In the Add New Item dialog box, click Component Class, type
GetProducts.vb in the Name field, and then click Open to generate and
open the new file.
2. Add the following code to import namespaces:
I mpor t s Syst em. Dat a
I mpor t s Syst em. Dat a. Sql Cl i ent
3. Create a new namespace named db2063.
4. Create a public class named Products.
Your code should look like the following:
Namespace db2063
Publ i c Cl ass Pr oduct s
End Cl ass
End Namespace
34 Module 4: Separating Code from Content
To add a method to the Products class
1. Create a new function named GetProducts that takes an Integer parameter
named categoryID and returns a DataSet.
Publ i c Funct i on Get Pr oduct s( cat egor yI D As I nt eger ) As _
Dat aSet
2. Open the ProductsList.aspx page.
3. Cut the content of the Page_Load event procedure, except for the first
instruction that reads the CategoryID query string parameter and the last
two instructions that set the DataSource of the Repeater controls. The
Page_Load event procedure code should look like the following after you
have cut the instructions as specified above:
Sub Page_Load( Sour ce As Obj ect , E As Event Ar gs)
' Obt ai n Cat egor yI D f r omQuer ySt r i ng
Di mcat egor yI D As I nt eger = _
CI nt ( Request . Par ams( " Cat egor yI D" ) )
' Bi nd t o t he cont r ol
r epLi st . Dat aSour ce = dsPr oduct s. Tabl es( 0) . Def aul t Vi ew
r epLi st . Dat aBi nd( )
End Sub
4. Save the changes to ProductsList.aspx.
5. Paste this code into the GetProducts function in the GetProducts.vb
component.
Module 4: Separating Code from Content 35
6. Add a return statement to return the Dataset at the end of the function.
Your function should look like the following:
Publ i c Funct i on Get Pr oduct s( cat egor yI D As I nt eger ) As _
Dat aSet
Di mconn As Sql Connect i on
Di mst r Conn As St r i ng
Di mcmdPr oduct s As Sql Dat aAdapt er
Di mpar amCat egor yI D As Sql Par amet er
Di mdsPr oduct s As New Dat aSet
' Cr eat e t he connect i on
st r Conn = _
" ser ver =l ocal host ; ui d=sa; pwd=1Aspnet ; dat abase=Conf "
conn = New Sql Connect i on( st r Conn)
' Cal l t he Pr oduct sByCat egor y st or ed pr ocedur e
cmdPr oduct s = _
New Sql Dat aAdapt er ( " Pr oduct sByCat egor y" , conn)
cmdPr oduct s. Sel ect Command. CommandType = _
CommandType. St or edPr ocedur e
' Add Par amet er s
par amCat egor yI D = _
New Sql Par amet er ( " @Cat egor yI D" , Sql DbType. I nt , 4)
par amCat egor yI D. Val ue = cat egor yI D
cmdPr oduct s. Sel ect Command. Par amet er s. Add( par amCat egor yI D)
' Fi l l t he Dat aSet
cmdPr oduct s. Fi l l ( dsPr oduct s, " Pr oduct s" )
' Ret ur n t he Dat aSet
r et ur n dsPr oduct s
End Funct i on
Visual Studio .NET Beta 2 may insert parentheses at the end of your
function declaration or elsewhere. Be sure to compare your code with the
preceding example and remove any extra parentheses before continuing.
7. Save your changes to GetProducts.vb.
Note
36 Module 4: Separating Code from Content
To compile the component
There are two ways to compile the component: in an MS-DOS command
prompt, or in Visual Studio .NET.
1. To compile the component in an MS-DOS command prompt:
a. Open an MS-DOS command prompt.
b. Navigate to the folder InetPub\wwwroot\ASPNET\components.
c. Run the following command:
vbc / t : l i br ar y / out : . . \ bi n\ db2063. dl l / r : Syst em. dl l
/ r : Syst em. Web. dl l / r : Syst em. Xml . dl l / r : Syst em. Dat a. dl l
Get Pr oduct s. vb
The compiler generates a file named db2063.dll in the ASPNET\bin
directory.
2. To compile the component in Visual Studio .NET, on the Build menu, click
Build.
The compiler adds the new class to the project assembly named
ASPNET.dll in the ASPNET\bin directory.
Module 4: Separating Code from Content 37
Exercise 4
Calling a Component
In this exercise, you will call the component that you built in Exercise 3 to get a
DataSet of products that you will display on the ProductsList.aspx page.
Client
Middle-tier
components
Data
GetProducts.vb ProductsByCategory Stored Procedure
ProductList.aspx
To call the component from the ProductsList.aspx page
1. Open the page ProductsList.aspx from the ASPNET Web site.
2. Edit the Page_Load event procedure.
3. Declare a variable named productCatalog that is an instance of the
Products class in the db2063 namespace.
If you used Visual Studio .NET to compile the component, you must
preface the namespace of the component with the root namespace (the
project name) of the project.
If you used a command prompt to compile the component, your code should
look like the following:
Di mpr oduct Cat al og As New db2063. Pr oduct s
If you used Visual Studio .NET to compile the component, your code
should look like the following:
Di mpr oduct Cat al og As New ASPNET. db2063. Pr oduct s
4. Declare a DataSet variable named dsProducts.
5. After the code that reads the categoryIDparameter from the QueryString
object, call the GetProducts method of the component and save the result in
the dsProducts variable.
Your code should look like the following:
Di mdsPr oduct s As New Dat aSet
dsPr oduct s = pr oduct Cat al og. Get Pr oduct s( Cat egor yI D)
Note
38 Module 4: Separating Code from Content
To save and test your work
1. Save your changes to ProductsList.aspx.
2. Using Internet Explorer, go to the ProductsList page of the ASPNET Web
site by viewing:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
The page should display the table of conference tracks.
Module 4: Separating Code from Content 39
Review
n Advantages of Partitioning an ASP.NET Page
n Creating and Using Code-Behind Pages
n Creating and Using User Controls
n Creating and Using Components
*****************************illegal for non -trainer use******************************
1. List some of the advantages of separating code from content.
2. How do you link the user interface page to its code-behind file?
3. What are the ASP.NET namespaces that you need to import in a code-
behind class file?
40 Module 4: Separating Code from Content
4. What are some of the differences between a regular ASP.NET page and a
user control?
5. What is the biggest advantage that ASP.NET offers for using external
components?
6. How do you use a user control from an ASP.NET page?
7. How do you use a component from an ASP.NET page?
Contents
Overview 1
Overview of Tracing 2
Trace Information 3
Page-Level Trace 4
Application-Level Trace 10
Lab 5: Adding Trace to an ASP.NET Page 16
Review 21
Module 5: Using Trace
in Microsoft ASP.NET
Pages
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 5: Using Trace in Microsoft ASP.NET Pages 1
Overview
n Overview of Tracing
n Trace Information
n Page-Level Trace
n Application-Level Trace
*****************************illegal for non-trainer use******************************
In earlier versions of Active Server Pages (ASP), code tracing was
accomplished by inserting Response.Write statements wherever required. A
drawback of this technique was the removal of the excess code that was added
when the application was deployed, and the resulting inability to use the output
from the Response.Write statements in a production environment. Microsoft
ASP.NET overcomes such drawbacks by introducing an automatic tracing
mechanism. This tracing mechanism can be enabled and disabled either on a
page-by-page basis or for an entire application, and it can be configured in the
web.config file.
After completing this module, you will be able to:
n Describe page-level and application- level tracing.
n Enable and disable tracing for an ASP.NET page.
n Add custom trace information.
2 Module 5: Using Trace in Microsoft ASP.NET Pages
Overview of Tracing
n With Tracing You Can:
l Output variables or structures
l Assert whether a condition is met
l Trace through the execution path of the application
n Can Be Enabled and Disabled, Either on a Page-By-Page
Basis or for an Entire Application
*****************************illegal for non-trainer use******************************
The tracing feature in ASP.NET enables you to insert debugging print
statements into your code. These statements allow you to output variables or
structures, assert whether a condition is met, or trace through the execution path
of the application.
All of this information is output to an .aspx page or saved to a log, depending
on settings in the web.config file.
You can also use the Debug object to output debugging information. By using
methods in the Debug object to print debugging information and check your
logic with assertions, you can make your code more robust without impacting
your shipping product's performance and code size.
While you are debugging an application during development, both your trace
and debug output statements go to the Output window in Microsoft
Visual Studio .NET. However, with trace statements, you can debug a
production Web site simply by changing a setting in the web.config file and
having the trace statements output on the page.
In this course, we will focus only on the trace feature of ASP.NET.
Module 5: Using Trace in Microsoft ASP.NET Pages 3
Trace Information
*****************************illegal for non -trainer use******************************
Tracing provides plenty of information to the developer of an ASP.NET
application. The trace output screen contains the following categories of
information.
Category Description
Control Tree List of all items on the page.
Cookies Collection List of cookies being used.
Form Collection List of controls and their values on the form being posted.
Headers Collection List of items in the Hypertext Transfer Protocol (HTTP)
header.
Request Details Information about the request: session ID, time of request,
type of request, and request status.
Server Variables List of all server variables and their values.
Trace Information Output from standard and custom trace statements.
4 Module 5: Using Trace in Microsoft ASP.NET Pages
u Page-Level Trace
n How Does Page-Level Trace Work?
n Demonstration: Adding Page-Level Trace Statements
n Tracing into a Component
*****************************illegal for non-trainer use******************************
You can use page-level tracing to write debugging statements directly to the
output of a page and to conditionally execute debugging code when tracing is
enabled. The performance data and the developer-specified messages (if any)
are injected into the Hypertext Markup Language (HTML) output stream to the
client to help clarify precisely what occurs when the framework processes a
page request.
In this section, you will learn how the page-level trace mechanism works.
Module 5: Using Trace in Microsoft ASP.NET Pages 5
How Does Page-Level Trace Work?
n Enabling Tracing for a Page
n Sorting Output by Category
n Inserting Trace Messages
n Conditional Execution with Trace.IsEnabled
<%@ Page Language="VB" Trace="true"%>
<%@ Page Language="VB" Trace="true"%>
<%@ Page Language="VB" Trace="true"
TraceMode="SortByCategory"%>
<%@ Page Language="VB" Trace="true"
TraceMode="SortByCategory"%>
Trace.Write("category", "message")
Trace.Write("category", "message")
If Trace.IsEnabled
strTrace = 'create trace string here
End If
Trace.Write(strTrace)
If Trace.IsEnabled
strTrace = 'create trace string here
End If
Trace.Write(strTrace)
*****************************illegal for non -trainer use******************************
The page-level trace mechanism performs two functions when it is enabled:
n It automatically appends a table of performance data to the end of the page.
n It allows developers to insert custom diagnostic messages throughout their
code.
Enabling Tracing for a Page
The trace capability must be enabled prior to use. To enable tracing for a page,
include the following directive at the top of the page code:
<%@Page Language=" VB" Tr ace=" t r ue" %>
The page exposes the Trace property of the type TraceContext, which can be
used to output debugging statements to the page output. The default value of the
Trace attribute is set to False.
Sorting Trace Messages
The TraceContext class contains the TraceMode property that defines how
trace messages are sorted in the page output.
<%@Page Tr ace=" t r ue" Tr aceMode=" Sor t ByCat egor y" %>
TraceMode is of the type TraceModeEnum, and has two possible values:
n SortByTime
Trace messages are output in order of chronological occurrence. This is the
default setting.
n SortByCategory
Trace messages are sorted alphabetically by the category argument to the
Trace.Write and Trace.Warn methods.
6 Module 5: Using Trace in Microsoft ASP.NET Pages
Inserting and Organizing Trace Messages
You can use the Trace object to write debugging statements. You can use two
methods to insert custom messages: Trace.Write and Trace.Warn.
Trace.Write is used to display messages. Trace.Warn is used to display
warnings. Trace.Write and Trace.Warn are easy to distinguish because
Trace.Warn uses a red font color for its output, whereas Trace.Write uses the
default font color.
In their simplest forms, each method takes two string arguments:
Tr ace. Wr i t e( " cat egor y" , " message" )
Tr ace. War n( " cat egor y" , " message" )
The category argument is used to organize messages. For example:
Tr ace. Wr i t e( " Cust omTr ace" , " Begi nni ng User Code. . . " )
Tr ace. War n( " Cust omTr ace" , " Ar r ay count i s nul l ! " )
Conditional Execution with Trace.IsEnabled
Often, you will need to execute additional code to construct the statements to
pass to the Trace.Write or Trace.Warn methods . The code should execute
only if tracing is enabled for the page. To support this, the page exposes a
Boolean property, Trace.IsEnabled, that returns True only if tracing is
enabled for the page. You should first check the Trace.IsEnabled property to
guarantee that your debugging code will execute only when tracing is enabled.
I f Tr ace. I sEnabl ed
st r Tr ace = " cr eat e a t r ace st r i ng her e"
End I f
Tr ace. Wr i t e( st r Tr ace)
Module 5: Using Trace in Microsoft ASP.NET Pages 7
Demonstration: Adding Page-Level Trace Statements
*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to use trace at the page level.
To run the demonstration
1. Edit the file add.aspx in the folder <install folder>\Democode\Mod05.
2. Enable tracing by adding the Trace="True" attribute to the @Page
directive.
<%@Page Language=" vb" Tr ace=" Tr ue" %>
3. View the page in Microsoft Internet Explorer.
Trace messages are shown on the page.
4. Add a custom trace message to the Page_Load event.
Tr ace. Wr i t e ( "add Page_Load", "t xt Num1 = " &
Cst r ( t xt Num1. pNum) )
5. View the page again.
6. Disable tracing, and then view the page again.
No trace messages are shown on the page.
7. Add a trace message to the numberbox.ascx user control.
8. Enable tracing in add.aspx, and view the page in Internet Explorer.
8 Module 5: Using Trace in Microsoft ASP.NET Pages
Tracing into a Component
n Import the System.Web Library
n Enable Tracing in Class Constructor
n Add Trace Statements to Method
Imports System.Web
Imports System.Web
HttpContext.Current.Trace.IsEnabled = True
HttpContext.Current.Trace.IsEnabled = True
HttpContext.Current.Trace.Write _
("component", "this is my trace statement")
HttpContext.Current.Trace.Write _
("component", "this is my trace statement")
*****************************illegal for non -trainer use******************************
If you have a component that is called from an ASP.NET page, you can also
add trace statements to the component.
To add trace to a component
1. At the top of the component, import the System.Web library.
I mpor t s Syst em. Web
2. In the constructor of the class to which you want to add trace statements,
enable tracing with the following statement:
Ht t pCont ext . Cur r ent . Tr ace. I sEnabl ed = Tr ue
In the preceding code, HttpContext.Current gets the Context object for
the current request.
3. Next, in the method, use the following:
Ht t pCont ext . Cur r ent . Tr ace. Wr i t e _
( "component ", "t hi s i s my t r ace st at ement ")
Module 5: Using Trace in Microsoft ASP.NET Pages 9
The following table lists some useful information about the results of enabling
trace on a page or component.
Case Result
If you enable trace in the constructor
of the component.
All pages that access the component will have
trace enabled even if the page does not have it
enabled.
If you enable trace in a component
method.
Only the page that accesses the method of the
component will have trace enabled, even if the
page does not have trace enabled.
If you disable trace in the constructor
of the component.
All pages that access the component will have
trace disabled even if the page has trace
enabled.
If you do not explicitly enable or
disable trace for a component, but the
page that calls the component has
trace enabled.
Trace in the component will be enabled for that
specific page.
10 Module 5: Using Trace in Microsoft ASP.NET Pages
u Application-Level Trace
n How Does Application-Level Trace Work?
n Demonstration: Adding Application-Level Trace
Statements
*****************************illegal for non-trainer use******************************
ASP.NET also provides a way to enable tracing for the entire application, rather
than just a single page of the application. An ASP.NET application is the
collection of files and folders in a virtual root of Internet Information Services
(IIS).
In this section, you will learn how an application-level trace works.
Module 5: Using Trace in Microsoft ASP.NET Pages 11
How Does Application-Level Trace Work?
n Application-Level Trace Collects Additional Statistics
from a Request in the trace.axd File
n Enabling Application-Level Trace in web.config
<trace enabled="true"
traceMode="SortByCategory"
requestLimit="40"
pageOutput="true"/>
<trace enabled="true"
traceMode="SortByCategory"
requestLimit="40"
pageOutput="true"/>
*****************************illegal for non-trainer use******************************
In addition to the page-level trace functionality, ASP.NET provides a way to
enable trace output for an entire application. Enabling trace at the application
level has the effect of enabling page- level trace for every page within that
application, provided that there is no page-level directive to explicitly disable
trace. When application- level tracing is enabled, the ASP.NET runtime also
collects several additional statistics, such as the state of the control hierarchy,
the contents of session and application state, the form and query string input
values, and so on. These statistics are collected for a specified number of
requests as determined by the applications configuration file.
Enabling Tracing
With ASP.NET, there is a configuration file that you can use to configure
certain application attributes. This file is named web.config and is located in the
root folder of the application. You will learn more about the web.config file in
Module 7, Creating a Microsoft ASP.NET Web Application, in Course
2063B, Introduction to Microsoft ASP.NET.
The web.config file is in Extensible Markup Language (XML) format; therefore,
all section and attribute names are case-sensitive.
To enable tracing for an application, place the following code in the web.config
file in the applications root folder.
<t r ace enabl ed=" t r ue" / >
12 Module 5: Using Trace in Microsoft ASP.NET Pages
By using the above configuration, each page in the application will output page-
level trace statements to the file trace.axd in the applications root folder, as
shown in the following illustration.
If you want trace messages to be displayed on the individual pages of your
application, set the PageOutput attribute of the trace element to True.
<t r ace enabl ed=" t r ue" pageOut put =" t r ue" / >
The trace section in the configuration file is contained in a <system.web>
section inside the <configuration> section.
<conf i gur at i on>
<syst em. web>
<t r ace enabl ed=" t r ue" / >
</ syst em. web>
</ conf i gur at i on>
Note
Module 5: Using Trace in Microsoft ASP.NET Pages 13
Setting Trace Attributes
The trace section of the configuration file also supports an attribute for
controlling whether trace statements are output to the client browser or are
available only from trace.axd. The attributes supported in the trace
configuration section are listed in the following table.
Value Description
enabled Set to True or False. Indicates whether tracing is enabled for the
application or not. Default is True.
pageOutput Indicates whether trace information should be rendered at the end of
each page, or accessible only through the trace.axd utility. Default is
False (trace information is only accessible through trace.axd).
requestLimit Number of trace requests to store on the server. Default is 10.
traceMode Set to sortByTime or sortByCategory. Indicates the display order
for trace messages. Default is sortByTime.
The following example shows how you can set trace attributes. The following
configuration collects trace information for up to 40 requests and prevents trace
statements from being output to the requesting browser:
<t r ace enabl ed=" t r ue" t r aceMode=" sor t ByCat egor y"
r equest Li mi t =" 40" pageOut put =" f al se" / >
14 Module 5: Using Trace in Microsoft ASP.NET Pages
Demonstration: Adding Application-Level Trace Statements
*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to use trace at the application level.
To run the demonstration
1. Copy the web.config file from the folder
<install folder>\DemoCode\Mod05 to the <install folder>, which is the
virtual root of the 2063 Web site.
2. Edit the web.config file and enable application-level tracing by adding the
following line of code to the file:
<t r ace enabl ed=" t r ue" / >
3. View the page http://localhost/2063/DemoCode/Mod05/postback.aspx in
Internet Explorer.
You will not see any trace output in the page.
4. View the page http://localhost/2063/trace.axd in Internet Explorer and look
at the details for the postback.aspx request.
You may need to click Refresh to see the latest entries in the
trace.axd page.
This is where the details are shown. Scroll down to show the values sent to
the form.
Note
Module 5: Using Trace in Microsoft ASP.NET Pages 15
5. Change web.config to display the trace messages on the page by adding the
pageOutput="true" attribute to the trace element.
6. View the page http://localhost//2063/DemoCode/Mod05/postback.aspx in
Internet Explorer again.
Now the trace messages are displayed on the page.
7. When you are done with this demonstration, delete the web.config file in the
root of the 2063 virtual directory so that tracing will be turned off for future
demonstrations.
16 Module 5: Using Trace in Microsoft ASP.NET Pages
Lab 5: Adding Trace to an ASP.NET Page
***************** ************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Enable and disable tracing for an ASP.NET page.
n Add custom trace messages to an ASP.NET page and a middle-tier
component.
Prerequisite
Before working on this lab, you must know how to compile a component.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab05\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab05\Solution.
Estimated time to complete this lab: 30 minutes
Module 5: Using Trace in Mi crosoft ASP.NET Pages 17
Exercise 1
Enabling Tracing
In this exercise, you will enable and disable tracing and add custom messages to
the trace stream.
To enable tracing in a page
1. Open the file ProductsList.aspx in the folder InetPub\wwwRoot\ASPNET.
2. At the beginning of the code, modify the existing @Page directive, add the
trace attribute, and set its value to True, as shown in the following code:
<%@Page Language=" vb" t r ace=" t r ue" %>
3. Save your changes to the ProductsList.aspx page.
4. View the page in Internet Explorer.
You should see the trace information at the bottom of the page.
To add custom trace messages
1. Go to the beginning of the Page_Load event procedure of the
ProductsList.aspx page and add a trace message that displays Beginning of
Page_Load in a category named Product List.
Your code should look like the following:
Tr ace. Wr i t e( " Pr oduct Li st " , " Begi nni ng of Page_Load" )
2. Add another trace message to the end of the Page_Load event procedure
that displays End of Page_Load.
3. Add a third trace message that displays the value of the variable categoryID
after reading it from the QueryString.
4. Save your changes to ProductsList.aspx.
18 Module 5: Using Trace in Microsoft ASP.NET Pages
5. View ProductsList.aspx in Internet Explorer, passing the CategoryID=15:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
You should see your custom messages in the Trace Information section, as
shown in the following illustration.
Module 5: Using Trace in Microsoft ASP.NET Pages 19
Exercise 2
Tracing into a Component
In this exercise, you will add trace statements to the DB2063 component that is
called from the ProductsList.aspx page.
To enable tracing in the DB2063 component
1. Open the file GetProducts.vb in the folder
InetPub\wwwRoot\ASPNET\Components.
2. Import the System.Web library.
Your import statement should look like the following:
I mpor t s Syst em. Web
3. In the GetProducts method, enable tracing by setting the
HttpContext.Current.Trace.IsEnbledproperty to True.
Your code should look like the following:
Ht t pCont ext . Cur r ent . Tr ace. I sEnabl ed = t r ue
You can also put this command in the constructor of the class if you need
to use tracing in the whole component.
To add custom trace messages
1. Go to the beginning of the GetProducts method and add a custom trace
message that displays Beginning of GetProducts in a category named
DB2063.Products Component.
Your additional instruction should look like the following:
Ht t pCont ext . Cur r ent . Tr ace. Wr i t e _
( "DB2063. Pr oduct s Component ", _
" Begi nni ng of Get Pr oduct s" )
2. Add another trace message at the end of the procedure, before the Return
command that displays End of GetProducts.
3. Add a third trace message to the GetProducts method that displays the
value of the categoryID parameter .
Note
20 Module 5: Using Trace in Microsoft ASP.NET Pages
To save and test
1. Save your changes to GetProducts.vb.
2. Compile the component.
a. To compile the component by using an MS-DOS command prompt,
open an MS-DOS command prompt, navigate to the folder
InetPub\wwwroot\ASPNET\components, and run the following
command:
vbc / t : l i br ar y / out : . . \ bi n\ db2063. dl l / r : Syst em. dl l
/ r : Syst em. Web. dl l / r : Syst em. Xml . dl l / r : Syst em. Dat a. dl l
Get Pr oduct s. vb
b. To compile the component by using Visual Studio .NET, click Build on
the Build menu.
If you compile the component by using Visual Studio .NET, you will
need to change the Page_Load event procedure in the ProductsList.aspx
page to instantiate the Products object from the newly built DB2063
component in the ASPNET project.
Di mpr oduct Cat al og As New ASPNET. db2063. Pr oduct s
3. View the ProductsList.aspx page in Internet Explorer, again passing the
categoryID=15:
http://localhost/ASPNET/ProductsList.aspx?CategoryID=15
You should see your custom messages from the page and from the
component in the Trace Information section, as shown in the following
illustration.
Note
Module 5: Using Trace in Microsoft ASP.NET Pages 21
Review
n Overview of Tracing
n Trace Information
n Page-Level Trace
n Application-Level Trace
*****************************illegal for non-trainer use******************************
1. How do you enable page-level tracing?
2. What is the difference between the Trace.Write and Trace.Warn methods?
3. What property is used to sort trace messages in a page?
4. How do you enable application- level trace?
22 Module 5: Using Trace in Micros oft ASP.NET Pages
5. If you have trace enabled in a component, but disabled in the page that calls
the component, will the trace messages be displayed?
6. If you have trace enabled for a page, but neither enabled nor disabled in a
component called by the page, will the trace messages from the component
be displayed?
Contents
Overview 1
What Is a Web Service? 2
Calling a Web Service from a Browser 12
Calling a Web Service by Using a Proxy 15
Creating a Simple Web Service by Using
Visual Basic 22
Creating and Calling a Web Service by
Using Visual Studio .NET 26
Lab 6: Using Web Services 35
Review 47
Module 6: Using Web
Services
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, FrontPage, IntelliSense, Jscript, Outlook,
PowerPoint, Visual Basic, Visual InterDev, Visual C++, Visual C#, Visual Studio, and Windows
Media are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 6: Using Web Services 1
Overview
n What Is a Web Service?
n Calling a Web Service from a Browser
n Calling a Web Service by Using a Proxy
n Creating a Simple Web Service by Using Visual Basic
n Creating and Calling a Web Service by Using
Visual Studio .NET
*****************************illegal for non-trainer use******************************
The Web has helped to facilitate better communication within and between
companies by providing fast access to information. For many organizations,
however, browsing data-driven pages does not adequately satisfy their business
needs. Programmable Web sites that directly link organizations, applications,
services, and devices with one another would better meet these needs.
Web services provide a simple, flexible, standards-based model for binding
applications together over the Internet, and taking advantage of existing
infrastructure and applications. Web applications can easily be assembled by
using locally developed services and existing services, regardless of which
platforms, development languages, or object models have been used to
implement the constituent services or applications.
After completing this module, you will be able to:
n Explain the goal of Web services and how they fit into the Web architecture.
n Describe the Web services execution model.
n Call a Web service from a browser.
n Call a Web service by using a proxy.
n Use the data returned by a Web service.
n Create a simple Web service by using Microsoft Visual Basic.
2 Module 6: Using Web Services
u What Is a Web Service?
n Features of Web Services
n Web Services Execution Model
n Finding Existing Web Services
n Examples of Existing Web Services
n Demonstration: Calling a Web Service from the Browser
*****************************illegal for non-trainer use**************************** **
Web services provide a simple, flexible, standards-based model for binding
applications together over the Internet and taking advantage of the existing
infrastructure and applications. In this section, you will learn about the need for
Web services and about their architecture. You will also learn about existing
Web services and how to find them.
Module 6: Using Web Services 3
Features of Web Services
n Allow Applications to Communicate Across the Internet
n Language Independent
n Protocol Independent
n Platform Independent
n Stateless Architecture
*****************************illegal for non-train er use******************************
One of todays most pressing challenges for developers is application
integration. Application integration is the process of taking a group of
applications and turning them into easy-to-use Web applications, even if they
run on different operating systems, were created with different programming
languages, and were built with different object models.
Like components, Web services represent black-box functionality that
developers can reuse without worrying about how to implement the service.
Web services provide well-defined interfaces (called contracts) that describe the
services they represent.
Developers can assemble applications by using a combination of remote
services, local services, and custom code. For example, a company might
assemble an online store that uses the Microsoft Passport service to authenticate
users, a third-party personalization service to adapt Web pages to each users
preferences, a credit-card processing service, a sales tax service, package-
tracking services from each shipping company, an in-house catalog service that
connects to the companys internal inventory management applications, and
custom code to individualize the interface and make it unique.
Unlike current component technologies, however, Web services do not use
protocols that are specific to certain object models, such as the Distributed
Component Object Model (DCOM), which requires specific, homogeneous
infrastructures on the computers that run the client and the server. Web services
communicate by using standard Web protocols and data formats, such as
Hypertext Transfer Protocol (HTTP), Extensible Markup Language (XML), and
Simple Object Access Protocol (SOAP). Any system that supports these Web
standards can support Web services.
A Web service can be used internally by a single application, or it can be used
externally by many applications that access it through the Internet. Because it is
accessible through a standard interface, a Web service allows disparate systems
to work together. The Web services model is independent of languages,
platforms, and object models.
4 Module 6: Using Web Services
The Web service model is supported by Microsoft ASP.NET, which is a unified
Web development platform that has grown from Active Server Pages (ASP)
technology. The ASP.NET Web services model assumes a stateless service
architecture. Stateless architectures are generally more scalable than stateful
architectures. Each time a service request is received, a new object is created.
There is a request for the method call, the method call is returned, and then the
object is destroyed. Services can use the ASP.NET State Management services
to maintain a state between requests.
Module 6: Using Web Services 5
Web Services Execution Model
*****************************illegal for non-trainer use******************************
The Web services execution model involves two entities: the client and the
service provider.
The term client is often misinterpreted. In this sense, a client is a Web
browser that views the results of calling a Web service.
The preceding slide illustration shows how Web services are used between a
client and the Web server. Each component has a specific role in the execution
model.
Web Service Model
In the Web service model, the Web service developer:
1. Creates the .asmx file that includes the namespace, classes, properties, and
methods.
2. Declares methods as Web methods that can be accessed over the Internet.
The following is an example of a simple .asmx file :
<%@WebSer vi ce Language=" VB" Cl ass=" Mat hSer vi ce" %>
I mpor t s Syst em. Web. Ser vi ces
I mpor t s Syst em
Cl ass Mat hSer vi ce
<WebMet hod( ) > Publ i c Funct i on Add( i nt 1 As I nt eger , _
i nt 2 As I nt eger ) As I nt eger
r et ur n( i nt 1 + i nt 2)
End Funct i on
End Cl ass
Note
6 Module 6: Using Web Services
Client
In the Web service model, the client:
1. Calls the Web service from the browser to determine which methods are
available.
When you call a Web service from a browser, you access the description
page, which lists the methods that are included in the Web service. The
protocol that is used in this case is HTTP, and the data is returned as XML.
2. Calls a method of the Web service from the browser.
When you call a method of a Web service from a browser, the protocol that
is used is HTTP, and the data is returned as XML.
Web Server
You can also call methods of the Web service by using code on an ASP.NET
page. To call a Web service from an ASP.NET page, the developer must:
1. Find out which Web services are available. This involves finding the
Uniform Resource Locator (URL) for the Web service.
2. Compile the .asmx file (Web service) into a proxy by using the Wsdl.exe
utility. This creates a .vb or .cs file that contains source code for the proxy.
You will learn about proxy files and how to compile an .asmx file into a
proxy in the next section of this module.
3. Compile the proxy (the .vb or .cs file you created in the previous step) into
a .dll file in the /bin directory of the Web site.
4. Open the ASP.NET Web page.
a. Create an instance of the proxy.
b. Call the methods of the Web service.
c. Use the data returned by the Web service.
As the preceding slide illustration shows, the proxy resides on the same
server as the Web page (.aspx) that calls it. An advantage of using a proxy is
that it translates the returned data from the server into a data type that the .aspx
page can use. If you call a Web service method directly from an .aspx page
without using a proxy, you will receive the data in XML form, which must be
parsed in another step.
Note
Module 6: Using Web Services 7
To learn more about the Web services execution model, view the Web Services
Execution Model animation. Open the file 2063B_06A001.swf from the
Media folder.
8 Module 6: Using Web Services
Finding Existing Web Services
n UDDI
l Defines a way to publish and discover information about
Web services
l Relies on a distributed registry of businesses and their
service descriptions implemented in a common XML
format
n Businesses Individually Register Information About the
Web Services by Using UDDI Business Registration
http://www.uddi.org
http://uddi.microsoft.com
*****************************illegal for non -trainer use******************************
Getting information about which business partners have Web services and
finding specific information about the available Web services is very difficult
for companies today. The Universal Description, Discovery and Integration
(UDDI) specification defines a way to publish and discover information about
Web services.
UDDI relies on a distributed registry that has been implemented in a common
XML format. This registry is a list of businesses, along with descriptions of
their available services. The UDDI specification consists of several related
documents and an XML schema that defines a SOAP-based programming
protocol for registering and discovering Web services.
The core component of UDDI is the UDDI business registration, an XML file
that is used to describe a business entity and its Web services. Conceptually, the
information provided in a UDDI business registration consists of three
components: White Pages, which include address, contact, and known
identifiers; Yellow Pages, which include industrial categorizations based on
standard taxonomies; and Green Pages, which include the technical information
about the services that are exposed by the organization. Green Pages include
references to specifications for Web services, as well as any support that may
be required for pointers to file and URL-based discovery mechanisms.
Businesses individually register information about the Web services that they
expose for other businesses to use. This information can be added to the UDDI
business registry through a Web site, or by using tools that use the
programmatic service interfaces described in the UDDI programmers
application programming interface (API) specification. The UDDI business
registry is a logically centralized, physically distributed service with multiple
root nodes that replicate data with each other regularly. When a business
registers with a single instance of the business registry service, the service
shares the data automatically with other UDDI root nodes. After the data has
been distributed, it becomes freely available to anyone who needs to discover
which Web services are exposed by a particular business.
Module 6: Using Web Services 9
For more information about UDDI, go to the UDDI Web site at
http://www.uddi.org/ or the Microsoft UDDI Project Web site at
http://uddi.microsoft.com
10 Module 6: Using Web Services
Examples of Existing Web Services
n Find Web Services at:
l http://www.xmethods.net
l http://www.gotdotnet.com
l http://dotnet.microsoft.com
*****************************illegal for non-trainer use******************************
You can find existing Web services at the following Web sites:
n http://www.xmethods.net
n http://www.gotdotnet.com
n http://dotnet.microsoft.com
Some examples of Web services that can be found at these sites include:
n FedEx Tracker
Provides acc ess to FedEx Tracking information.
n Weather-temperature
Gives the current temperature in a given United States zip code region.
n Barnes and Noble Price Quote
Returns the price of a book at barnesandnoble.com when you provide an
International Standard Book Number (ISBN).
Module 6: Using Web Services 11
Demonstration: Calling a Web Service from the Browser
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to call a Web Service.
To run the demonstration
1. View the description page for the MathService Web service at
http://localhost/2063/Democode/Mod06/mathservice.asmx
2. Click the Add link.
3. Fill in parameters for the Add method, and then click Invoke.
4. Return to the mathservice.asmx page and view the Web Service Description
Language (WSDL) contract.
12 Module 6: Using Web Services
Calling a Web Service from a Browser
http://server/vroot/webservice.asmx
http://server/vroot/webservice.asmx
*****************************illegal for non -trainer use******************************
Because Web Services are accessible by using URLs, HTTP, and XML,
programs running on any platform and in any language can access them.
If you know the base URL for a Web service (the URL to the .asmx file that is
the base of the Web service), you can use this URL to access a Web page
known as the HTML description page. The HTML description page provides
information about what a Web service does, the methods it contains and their
parameters, and its response type. In addition, you can use the description page
to test the functionality of the Web service.
Module 6: Using Web Services 13
For example, suppose that you access a Web service called hotel_Full.asmx that
is used to retrieve details from a hotel. You know the base URL for this service
is http://localhost/ASPNET/hotel_full.asmx. Entering the base URL with no
extensions or parameters produces a page that displays information about the
service and the methods it contains.
In addition to viewing information about the Web service in the browser, you
can obtain a more formal definition of the Web service by viewing its Web
Service Description Language (WSDL) contract. A Service Description link at
the top of the description page allows you to view the contract, which contains
an XML description of the Web service and its contents. You can use this file to
generate a proxy manually.
WSDL Contract
The WSDL contract is an XML document. The document defines the format of
messages that the Web service understands. The service description acts as an
agreement that defines the behavior of a Web service and instructs potential
clients in how to interact with it.
In addition to message format definitions and messaging patterns, the service
description also contains the address that is associated with each Web service
entry point. The format of this address depends on the protocol that is used to
access the service, such as a URL for HTTP or an e-mail address for Simple
Mail Transfer Protocol (SMTP).
14 Module 6: Using Web Services
Calling a Web Service from a Browser (continued)
n Pass the Name of the Method and All Required
Parameters to the URL of the Web Service
n Return Value Is in XML Format
http://server/vroot/webservice.asmx/method?param=value
http://server/vroot/webservice.asmx/method?param=value
*****************************illegal for non-trainer use******************************
You can also call the methods of a Web service directly from a browser.
To call a Web service method, pass the name of the method, the required
parameters, and the values of the parameters to the URL of the Web service.
The Web service returns data in XML format when it is called from a Web
browser by using HTTP.
For example, if a Web service named hotel_full has a method named Price that
takes one parameter named strRoomType1, you can call it directly from the
browser by viewing the following URL:
http://localhost/conference/hotel_full.asmx/Price?strRoomType1=single
The following XML is data that was returned from this URL:
<?xml ver si on="1. 0"?>
<doubl e xml ns=" ht t p: / / t empur i . or g/ " >200</ doubl e>
If you want to use this kind of data in your Web application, you must parse it
in a separate step.
Module 6: Using Web Services 15
u Calling a Web Service by Using a Proxy
n Compiling an .asmx File into a Proxy
n Compiling the Proxy into a DLL
n Calling Web Service Methods
n Demonstration: Calling a Web Service by Using a Proxy
*****************************illegal for non-trainer use******************************
Another method for calling a Web service is by using a proxy. In this section
you will learn how to call a Web service by using a proxy.
You will first learn how to create a Web service manually, and then learn
how to create it by using Microsoft Visual Studio .NET.
Note
16 Module 6: Using Web Services
Compiling an .asmx File into a Proxy
n A Proxy Class:
l Looks like the original class but does not contain any
application logic
l Allows a client to access a Web service as if it were a
local COM object
n Creating a Proxy Class from an .asmx File
wsdl /l:vb /n:myNameSpace
http://location/service.asmx?wsdl
wsdl /l:vb /n:myNameSpace
http://location/service.asmx?wsdl
*****************************illegal for non-trainer use******************************
A proxy class is code that looks exactly like the class it is meant to represent,
but does not contain any of the application logic. Instead, it contains marshaling
and transport logic. The Proxy object allows a client to access a Web service as
if it were a local Component Object Model (COM) object, which lets any
COM-enabled language access the Web servic e easily. You can create a proxy
class from an SDL file.
The Microsoft .NET Framework software development kit (SDK) includes a
tool called Wsdl.exe that you can use to create a proxy class.
wsdl [ opt i ons] {URL | pat h}
In the preceding syntax, URL is the Uniform Resource Location (URL) to a
WSDL contract file (.wsdl), XSD schema file (.xsd), or a discovery document
(.disco). Path is the path to a local WSDL contract, XSD schema, or discovery
document (including .discomap files).
Syntax
Module 6: Using Web Services 17
The following table provides a detailed description of the options that are used
with the Wsdl.exe command.
Option Description
/urlkey Specifies the configuration key to use to read the default value for
the URL property when generating code. Also called
/appsettingurlkey.
/baseurl Specifies the base URL to use when calculating the URL fragment.
You must use the /urlkey option with this option. Also called
/appsettingbaseutl.
/d[omain] Specifies the domain name to use when connecting to a server that
requires authentication.
/l[anguage] The language that is used for the generated proxy: CS (Microsoft
Visual C#
database;
or in a separate process on the Web server or remote
computer.
sqlConnectionString Specifies the connection string for a SQL Server. For
example, "data source=127.0.0.1;user id=sa; password=".
This attribute is required when mode is set to sqlserver.
timeout="[number of
minutes]"
Specifies the number of minutes a session can be idle
before it is abandoned. The default value is 20 minutes.
For example, to double the default timeout of 20 minutes, the following can be
added to the web.config of an application:
<sessi onst at e t i meout ="40" / >
Setting Up a Cookie-less Session
By default, ASP.NET uses cookies to identify requests within a single session.
If cookies are not available, or have been disabled by the user, a session can be
tracked by adding a session identifier to the URL. You can enable cookie -less
sessions as follows:
<sessi onst at e cooki el ess=" t r ue" / >
Module 7: Creating a Microsoft ASP.NET Web Application 9
Global Application File (Global.asax)
n Global.asax is Similar to Global.asa in ASP Applications
n Global.asax Supports More Than 15 Events
l As page is requested: BeginRequest,
AuthenticateRequest, AuthorizeRequest
l As page is returned: EndRequest
*****************************illegal for non-trainer use******************************
Similar to ASP, ASP.NET supports one global declarative file per application
for application events and state called global.asax. The global.asax file is
similar to ASPs global.asa, but has numerous new events that are not supported
by global.asa.
In ASP.NET, global.asax can be used as an .asax file or as a component
that can be deployed in the applications /bin directory.
Events
The event model provided by ASP.NET supports more than 15 events. This is
different from global.asa, which had only Application and Session OnStart and
OnEnd events.
For example, in ASP, if you wanted some code to run at the beginning of every
page, you would have needed to use an Include file at the top of every ASP
page. Using the ASP.NET global.asax file, you can simply declare the code in
the Application_BeginRequest event procedure, which is called at the
beginning of every request for the application.
Sub Appl i cat i on_Begi nRequest ( s As Obj ect , e As Event Ar gs)
. . .
End Sub
Note
10 Module 7: Creating a Microsoft ASP.NET Web Application
ASP.NET still supports the Application and Session OnStart and OnEnd event
procedures, but Global.asax also includes events that are fired when a client
requests a page. The following table lists events that can be used when a page is
requested.
Event Name Description
Application_Error This event is fired when an un-handled
error occurs within an application.
Application_BeginRequest This event is fired whenever a new
request is received.
Application_AuthenticateRequest This event indicates that the request is
ready to be authenticated.
Application_AuthorizeRequest This event signals that the request is
ready to be authorized.
Application_ResolveRequestCache This event is used by the output cache
module to stop the processing of requests
that have been cached.
Application_AcquireRequestState This event signals that per-request state
should be obtained.
Application_PreRequestHandlerExecute This event signals that the request
handler is about to execute.
Global.asax also includes events that are fired when the requested page is sent
back to the client. The following table lists these events.
Event Name Description
Application_PostRequestHandlerExecute This event is first available after the
handler (such as an ASP.NET page), or
Web service has completed its work.
Application_ReleaseRequestState This event is called when the request
state should be stored, because the
application is finished with it.
Application_UpdateRequestCache This event signals that code processing
is complete and the file is ready to be
added to the ASP.NET cache.
Application_EndRequest This event is the last event called when
the application ends.
Application_PreRequestHeaderSent This event provides the opportunity to
add, remove, or update headers and the
response body.
Module 7: Creating a Microsoft ASP.NET Web Application 11
Demonstration: Using Event Procedures in Global.asax
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to display events fired in the
global.asax file.
To run this demonstration
1. Copy the file <install folder>\Democode\Mod07\global.asax to the folder
<install folder>.
This is the root of the 2063 virtual directory.
2. Open the file global.asax. There are Response.Write statements in the event
procedures.
3. View http://localhost/2063/DemoCode/Mod07/GlobalEvents.aspx in
Microsoft Internet Explorer.
4. Delete the global.asax file from the root of the 2063 virtual directory.
12 Module 7: Creating a Microsoft ASP.NET Web Application
Page Caching
n Output Caching
l Caches content generated from dynamic pages
l Page is compiled into IL and native code
l Native code is cached as Page class and is available to
serve for the next request
l Page class is updated when the source ASP.NET file is
changed or cache timeout happens
n Setting the Cache Timeout
<%@ OutputCache Duration= "900" %>
<%@ OutputCache Duration= "900" %>
*****************************illegal for non-trainer use******************************
Page caching allows you to cache dynamic content. When an ASP.NET page is
accessed for the first time, the page is compiled into Intermediate Language (IL)
and to native code. This native code is cached as Page class and is available to
serve the next request. This cached Page class is updated and rebuilt when the
source ASP.NET file is changed or the cache timeout is reached.
Setting the Cache Timeout Value
You can specify the cache timeout value by setting the output cache page
directive. For example, to cache an ASP.NET page for 15 minutes, add the
following @OutputCache directive to the .aspx page:
<%@Out put Cache Dur at i on=" 900" %>
The unit for time for the Duration attribute is seconds.
This cache option is very useful for pages that do not change often (or do not
change within a known time period).
Creating an output cache for an application should be your final task in
application development. Otherwise, when you debug your pages, instead of
getting new and modified pages, you may get old pages that are stored in the
output cache.
Note
Module 7: Creating a Microsoft ASP.NET Web Application 13
u Sharing Information Between Pages
n Using ASP.NET Cache
n Using web.config Variables
n Demonstration: Using web.config Variables
n Using Session and Application Variables
n Demonstration: Using Session Variables
n Saving Session and Application Variables in a Database
n Discussion: Different Ways of Sharing Information
*****************************illegal for non-trainer use********** ********************
It is often necessary to share information between the pages of a Web
application. The information being shared can be either static or dynamic.
In this section, you will learn how to share both static and dynamic data
between pages of a Web application.
14 Module 7: Creating a Microsoft ASP.NET Web Application
Using ASP.NET Cache
n ASP.NET Cache:
l Stores objects and values for reuse in an application
n Placing Objects in ASP.NET Cache
n Retrieving Objects From ASP.NET Cache
Cache.Insert("mykey", myValue, _
Nothing, DateTime.Now.AddHours(1), _
TimeSpan.Zero)
Cache.Insert("mykey", myValue, _
Nothing, DateTime.Now.AddHours(1), _
TimeSpan.Zero)
myValue = Cache("mykey")
If myValue <> Nothing Then
DisplayData(myValue)
End If
myValue = Cache("mykey")
If myValue <> Nothing Then
DisplayData(myValue)
End If
*****************************illegal for non-trainer use******************************
The ASP.NET cache can be used to store objects and values that you reuse in
your application. ASP.NET provides a full-featured cache engine that can be
used by pages to store and retrieve arbitrary objects across HTTP requests. The
ASP.NET cache is private to each application and stores objects in memory.
The lifetime of the cache is equivalent to the lifetime of the application. This
means that, when the application is restarted, the cache is recreated.
The ASP.NET cache also provides a way to pass values between pages within
the same application. The ASP.NET cache methods implement automatic
locking; therefore, it is safe for objects to be accessed concurrently from more
than one page. The only drawback is that another page may change the values
that you place in the cache. It is not a per-user cache.
The cache provides a simple dictionary interface that allows you to insert
objects easily and retrieve them later. In the simplest case, placing an item in
the cache is exactly like adding an item to a dictionary:
Cache( " mykey" ) = myVal ue
Retrieving this data is equally simple:
myVal ue = Cache( " mykey" )
I f myVal ue <> Not hi ng Then
Di spl ayDat a( myVal ue)
End I f
You can also supply parameters when inserting an item into the cache by using
the Insert method.
Module 7: Creating a Microsoft ASP.NET Web Application 15
Cache.Insert Syntax
Cache. I nser t ( key As St r i ng, _
val ue As Obj ect , _
dependenci es As CacheDependency, _
absol ut eExpi r at i on As Dat eTi me, _
sl i di ngExpi r at i on As Ti meSpan )
n key is the cache key used to reference the object.
n value is the object to be cached.
n dependencies should be set to Nothing.
n absoluteExpiration is the time at which the cached object expires and is
removed from the cache.
n slidingExpiration is the interval between the time the cached object was
last accessed and when that object is scheduled to expire. For example, if
slidingExpiration is set to 20 minutes, the object will expire and be
removed from the cache 20 minutes after the object was last accessed.
The following code shows how to use the ASP.NET cache to store a DataView
that is used in an ASPX page. The first time the page is requested, it reads data
from the database and then stores it in the ASP.NET cache. At every
subsequent request for the page, the DataView is retrieved from the cache,
eliminating a call to the database. This example uses absolute expiration to set
the cache to expire one hour from the first time it was accessed.
Di mdvMenuI t ems As Dat aVi ew
dvMenuI t ems = Cache( " dvMenuI t ems" )
I f ( dvMenuI t ems = Not hi ng) Then
Di mpr oduct s As New Conf er ence. Pr oduct sDB
dvMenuI t ems = pr oduct s. Get Pr oduct Cat egor i es( ) . _
Tabl es( 0) . Def aul t Vi ew
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now. AddHour s( 1) , Ti meSpan. Zer o)
End I f
MyLi st . Dat aSour ce = dvMenuI t ems
MyLi st . Dat aBi nd( )
To set the cache to use sliding expiration and expire one hour after the last time
it was accessed, apply the following parameters to the Insert method:
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now, Ti meSpan. Fr omHour s( 1) )
16 Module 7: Creating a Microsoft ASP.NET Web Application
Using web.config Variables
n Store Application Variables in web.config
n Retrieve in an .aspx File
<configuration>
<appsettings>
<add key="pubs" value=
"server=localhost;uid=sa;pwd=;database=pubs"/>
</appsettings>
</configuration>
<configuration>
<appsettings>
<add key="pubs" value=
"server=localhost;uid=sa;pwd=;database=pubs"/>
</appsettings>
</configuration>
Dim appSetting As NameValueCollection
Dim strConn As String
appSetting = CType(Context.GetConfig _
("appsettings"), NameValueCollection )
strConn = appSetting("pubs").ToString()
Dim appSetting As NameValueCollection
Dim strConn As String
appSetting = CType(Context.GetConfig _
("appsettings"), NameValueCollection )
strConn = appSetting("pubs").ToString()
*****************************illegal for non-trainer use******************************
You can use the <appsettings> section of the web.config file as a repository for
application settings. In the <appsettings> section, you can create key/value pairs
for data that is commonly used throughout your application. This is very useful
because you can define all application configuration data in a central location.
For example, you can store a database connection string for an application in a
central location, instead of having it in each ASP.NET page.
The following web.config file creates two key/value pairs for the connection
strings for the databases used in the application:
<conf i gur at i on>
<appset t i ngs>
<add key=" pubs"
val ue="ser ver =l ocal host ; ui d=sa; pwd=; dat abase=pubs" / >
<add key=" nor t hwi nd"
val ue=" ser ver =l ocal host ; ui d=sa; pwd=; dat abase=nor t hwi nd"
/ >
</ appset t i ngs>
</ conf i gur at i on>
Use the GetConfig method of the Context object to read the data from the
web.config file. You need to supply the name of the section and the name of the
key to retrieve. The GetConfig method returns a NameValueCollection
variable containing the key/value pairs defined in the requested section.
Module 7: Creating a Microsoft ASP.NET Web Application 17
For example, the following sample code reads the value of the pubs key from
the <appSettings> section.
Di mappSet t i ng As NameVal ueCol l ect i on
Di mst r Conn As St r i ng
appSet t i ng = CType( Cont ext . Get Conf i g( " appset t i ngs" ) , _
NameVal ueCol l ect i on)
st r Conn = appSet t i ng( "pubs") . ToSt r i ng( )
You can also use the GetConfig method of the HttpContext object to access
configuration information from a component. The syntax for this is:
appSet t i ng = _
CType( Ht t pCont ext . Cur r ent . Get Conf i g( " appset t i ngs " ) , _
NameVal ueCol l ect i on)
18 Module 7: Creating a Microsoft ASP.NET Web Application
Demonstration: Using web.config Variables
*****************************illegal for non-trainer use******************************
In this demonstration, you will see how to create a constant in web.config and
use the constant from different ASP.NET pages.
To run the demonstration
1. Create a new web.config file in the folder
<install folder>\DemoCode\Mod07.
2. Add the <configuration> tag with an <appsettings> section.
3. Add a new key to the <appsettings> section:
<conf i gur at i on>
<appSet t i ngs>
<add key=" i nt Number I nConf i g" val ue=" 9" / >
</ appSet t i ngs>
</ conf i gur at i on>
4. Open the file <install folder>\DemoCode\ Mod07\ UsingConfigVar1.aspx.
The intNumberInConfig value is retrieved and displayed in the
Page_Load event procedure.
5. View the UsingConfigVar1.aspx page in Internet Explorer.
The value of intNumberInConfig, 9, is displayed.
6. Click Next.
The UsingConfigVar2.aspx page opens and displays the same value.
Module 7: Creating a Microsoft ASP.NET Web Application 19
Using Session and Application Variables
n Session Object Stores Information for a Particular User
Session
n Application Object Shares Information Among All Users
of a Web Application
Sub Session_Start(s As Object, e As EventArgs)
Session("BackColor") = "beige"
Session("ForeColor") = "black"
End Sub
Sub Session_Start(s As Object, e As EventArgs)
Session("BackColor") = "beige"
Session("ForeColor") = "black"
End Sub
Sub Application_Start(s As Object, e As EventArgs)
Application("NumberofVisitors") = 0
End Sub
Sub Application_Start(s As Object, e As EventArgs)
Application("NumberofVisitors") = 0
End Sub
*****************************illegal for non-trainer use******************************
You can use session and application variables to share information between
pages of an ASP.NET application.
You generally initialize session and application variables in the Start event
procedures of the Session and Application objects in the global.asax file.
Session Variables
You use the Session object to store information that is needed for a particular
user session. Variables stored in the Session object will not be discarded when
the user goes between pages in the Web application. Instead, these variables
will persist for the entire user session. The following example illustrates how
session variables are used to store information about a particular user session.
<scr i pt l anguage=" VB" r unat =" ser ver " >
Sub Sessi on_St ar t ( S As Obj ect , E As Event Ar gs)
Sessi on( " BackCol or " ) = " bei ge"
Sessi on( " For eCol or " ) = " bl ack"
Sessi on( " Font Name" ) = " ver dana"
End Sub
</ scr i pt >
20 Module 7: Creating a Microsoft ASP.NET Web Application
Application Variables
You can use the Application object to share information among all users of a
Web application. An Application object is created when the first user of the
application requests an .aspx file. It is destroyed when all users have exited the
application and the application is unloaded.
For example, you might store the total number of visitors to a Web site in an
application- level variable.
Sub Appl i cat i on_St ar t ( s As Obj ect , e As Event Ar gs)
Appl i cat i on( " Number of Vi si t or s" ) = 0
End Sub
A disadvantage of using session and application variables is that the
memory occupied by these variables will not be released until the value is either
removed or replaced. For example, keeping seldom-used 10-megabyte (MB)
recordsets in application-state permanently is not the best use of system
resources.
Reading Session and Application Variables
To use a session or application variable in an ASP.NET page, simply read the
value from the Session or Application object.
Sessi on( " BackCol or " )
Sessi on( "For eCol or " )
Sessi on( " Font Name" )
Appl i cat i on( "Number of Vi si t or s")
Note
Module 7: Creating a Microsoft ASP.NET Web Application 21
Demonstration: Using Session Variables
*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to share the same session variable
through two different ASP.NET pages.
To run the demonstration
1. Copy the file <install folder>\Democode\Mod07\global.session to the root
of the 2063 virtual folder and rename it global.asax.
2. Open the file global.asax and initialize a session variable named intNumber
to 3 by adding the following code to the Session_Start event procedure:
Sessi on( " i nt Number " ) =3
3. Open the file <install folder>\Democode\Mod07\UsingSessionVar1.aspx.
The session variable is retrieved and displayed in the Page_Load event
procedure.
4. View the page
http://localhost/2063/democode/Mod07/UsingSessionVar1.aspx in
Internet Explorer.
The value of the session variable, 3, is displayed.
5. Click Next.
The UsingSessionVar2.aspx page opens, increments the session variable by
4, and displays the new value, 7.
6. Click Back to return to the UsingSessionVar1.aspx, which displays the new
value of the session variable.
22 Module 7: Creating a Microsoft ASP.NET Web Application
Saving Session and Application Variables in a Database
n Session State Can Be Stored in a Separate SQL Server
Database
n A Temporary Table Is Used for the Serialized Session
Data
n Advantages:
l State can be recovered even if an application crashes
l An application can be partitioned across multiple Web
farm machines
*****************************illegal for non-trainer use******************************
In ASP.NET, an application can store session state in a separate SQL Server
database. A temporary table is used for the serialized session data. The table
can be accessed by a combination of stored procedures and managed data
access components for SQL Server.
By cleanly separating the storage of session data from the application usage of
it, ASP.NET provides advantages that did not exist in ASP:
n Ability to recover from application crashes
Because all state is stored externally from an individual worker process, it
will not be lost if the process crashes or is forcibly restarted.
n Ability to partition an application across multiple Web farm servers
Because all state is stored externally from worker processes, you can
partition an application across multiple worker processes running on
multiple servers. The model for communicating state between a worker
process and a state service running on the same server is almost identical to
models in which the state service is located on a completely different
machine.
To configure your application to store session state in a separate database, set
the mode attribute of the sessionState section to SQLServer and set the
sqlConnectionString attribute to the connection string for the server.
For more information on saving session information in a database, see Session
State in the Microsoft .NET Framework software development kit (SDK)
documentation.
Module 7: Creating a Microsoft ASP.NET Web Application 23
Discussion: Different Ways of Sharing Information
*****************************illegal for non-trainer use**************** **************
24 Module 7: Creating a Microsoft ASP.NET Web Application
u Securing an ASP.NET Application
n What Is Authentication?
n Forms Authentication Architecture
n Setting Up Security in web.config
n Creating a Login Form
n Demonstration: Setting Up Security in web.config
*****************************illegal for non-trainer use******************************
Securing Web sites is a critical is sue for Web developers. A secure system
requires careful planning, and Web site administrators and programmers must
have a clear understanding of the options for securing a site. Security, in the
context of an ASP.NET application, involves performing three fundamental
functions for all requests: authentication, authorization, and impersonation.
Authentication is the process verifying that the user requesting a page is
actually that user. To authenticate a request, you accept credentials from a user
and validate those credentials against some authority.
After you have authenticated the user, the authorization process determines
whether that user should be granted access to a given resource.
Another important feature of server applications is the ability to control the
identity under which server application code is executed. When a server
application executes code with the identity of the requesting entity, this is
known as impersonation.
In this section, you will learn about securing an ASP.NET application by
implementing authentication and authorization in web.config.
Module 7: Creating a Microsoft ASP.NET Web Application 25
What Is Authentication?
n Authentication
l Accept credentials from a user
l Validate the credentials
n Types of ASP.NET Authentication
l Windows authentication
l Passport authentication
l Forms authentication
*****************************illegal for non-trainer use******************************
Authentication is the process of accepting credentials from a user and validating
those credentials against some authority. If the credentials are valid, you have
an authenticated identity.
Authentication in ASP.NET is implemented through authentication providers.
ASP.NET authentication providers are the code modules that contain the code
necessary to authenticate the requestor s credentials.
The first version of ASP.NET will ship with support for the following
authentication providers:
n Windows authentication
This method is used in conjunction with the IIS authentication.
Authentication is performed by IIS in one of three ways: Basic, Digest, or
Integrated Windows Authentication. The advantage of using this
authentication type is that it requires minimum coding. Also, because it is
Microsoft Windows NT authentication, there is no additional cost to
implement this type of security. However, because the resources for
authentication are not embedded in the ASP.NET application, using this
method involves additional effort when deploying the application.
For more information on Windows authentication, see the Microsoft .NET
Framework SDK documentation.
n Passport authentication
Passport authentication is a centralized authentication service provided by
Microsoft that offers a single sign-in and core profile services for member
sites. It is a Web service and an integral part of the Microsoft .NET
Framework.
For more information on Passport authentication, go to:
http://www.passport.com/Business
26 Module 7: Creating a Microsoft ASP.NET Web Application
n Forms authentication
Forms authentication refers to a system where unauthenticated requests are
redirected to a Hypertext Markup Language (HTML) form (by using HTTP
client-side redirection). The user provides credentials and submits the form.
If the application validates credentials on the form, the system issues a
cookie to the user. Subsequent requests are issued with the cookie in the
request headers; therefore, they are authenticated.
Module 7: Creating a Microsoft ASP.NET Web Application 27
Forms Authentication Architecture
Client requests page
Authorized
ASP.NET
Authentication
Not
Authenticated Authenticated
Login Page
(Users enter
their credentials)
Authenticated
Cookie
Authorized
Not
Authenticated
Access Denied
Requested
Page
*****************************illegal for non-trainer use******************************
The most commonly used authentication type in ASP.NET applications is
forms authentication.
A request for a page protected by forms authentication must still go through IIS
first. Therefore, you must set IIS authentication to Anonymous Access. This
allows all requests to get to ASP.NET before being authenticated.
For more information on setting up Anonymous Access, see the Security
section in the IIS documentation.
The following is the set of events that take place during forms authentication:
1. A client generates a request for a protected page.
2. IIS receives the request, and passes it to the ASP.NET application. Because
the authentication mode is set to Anonymous Access, IIS authentication is
not used.
3. ASP.NET checks to see if a valid authentication cookie is attached to the
request. If it is, this means that the users credentials have already been
confirmed, and the request is tested for authorization. The authorization test
is performed by ASP.NET and is accomplished by comparing the
credentials contained in the requests authorization cookie to the
authorization settings in the applications configuration file (web.config). If
the user is authorized, access is granted to the protected page.
4. If there is no cookie attached to the request, ASP.NET redirects the request
to a login page (the path of which resides in the applications configuration
file), where the user enters the required credentials, usually a name and
password.
Tip
28 Module 7: Creating a Microsoft ASP.NET Web Application
5. The application code on the login page checks the credentials to confirm
their authenticity and, if authenticated, attaches a cookie containing the
credentials to the request. If authentication fails, the request is returned with
an Access Denied message.
6. If the user is authenticated, ASP.NET checks authorization as in step 3, and
can either allow access to the originally requested, protected page or redirect
the request to some other page, depending on the design of the application.
Alternatively, it can direct the request to some custom form of authorization
where the credentials are tested for authorization to the protected page.
Usually if authorization fails, the request is returned with an Access
denied message.
Module 7: Creating a Microsoft ASP.NET Web Application 29
Setting Up Security in web.config
n Setting Up Authentication
n Setting Up Authorization
<system.web>
<authentication mode="Forms">
<forms name="name" loginurl="login.aspx"/>
</authentication>
</system.web>
<system.web>
<authentication mode="Forms">
<forms name="name" loginurl="login.aspx"/>
</authentication>
</system.web>
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="Mary"/>
</authorization>
</system.web>
</location>
<location path="ShoppingCart.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="Mary"/>
</authorization>
</system.web>
</location>
*****************************illegal for non-trainer use******************************
Security for ASP.NET applications is set up in the applications web.config file.
The security settings in web.config are included in the <authentication>,
<authorization>, and <identity> sections.
You can set up authentication only in the web.config file in the root of
your Web application.
Setting Up Authentication
Begin by setting the authentication method for the application in an
<authentication> subsection of the <system.web> section, as shown in the
following example.
<conf i gur at i on>
<syst em. web>
<aut hent i cat i on mode=" aut hmode" >
</ aut hent i cat i on>
</ syst em. web>
</ conf i gur at i on>
As mentioned earlier in this module, ASP.NET supports three types of
authentication: Windows authentication, Forms authentication, and Passport
authentication. You can set the authentication mode for an application by
setting the mode attribute in the <authentication> tag to "None", "Windows",
"Passport", or "Forms".
Note
30 Module 7: Creating a Microsoft ASP.NET Web Application
If you set the authentication mode to Forms, you need to add a <forms>
element to the <authentication> section, as shown in the following example:
<syst em. web>
<aut hent i cat i on mode="For ms">
<f or ms name=". namesuf f i x" l ogi nur l =" l ogi n. aspx" / >
</ aut hent i cat i on>
</ syst em. web>
In the <forms> section, you configure settings of the cookie. Set the name
attribute to the suffix to be used for the cookies and the loginUrl attribute to the
URL of the page to which un-authenticated requests are redirected.
Setting Up Authorization
After specifying the authentication mode, you need to either mark the entire
Web application as needing authorization or specify which pages are secure and
require authorization.
Securing an Entire Application
To mark the entire application as secure, create an <authorization> section in
the <authentication> section, as illustrated in the following code example:
<syst em. web>
<aut hent i cat i on mode=" For ms" >
<f or ms name=" . aspxaut h"
l ogi nur l =" l ogi n. aspx" / >
<aut hor i zat i on>
</ aut hor i zat i on>
</ aut hent i cat i on>
</ syst em. web >
Module 7: Creating a Microsoft ASP.NET Web Application 31
Securing Specific Pages
To mark only specific pages as secure, create a <location> section with
<sys tem.web> and <authorization> sub-sections for each secure page in your
Web application:
<l ocat i on pat h="Shoppi ngCar t . aspx">
<syst em. web>
<aut hor i zat i on>
</ aut hor i zat i on>
</ syst em. web>
</ l ocat i on>
Any configuration settings contained in the <location> section will be directed
at the file or directory indicated in the path attribute. There can be multiple
<location> sections in the <configuration> section.
In the <system.web> section, you create an <authorization> subsection to
specify what type of authorization will be enforced. Create <allow> or <deny>
tags to allow or deny users access to a page. Within these tags, "?" indicates
anonymous users, whereas "*" means all users. For example, the following
code denies access to all anonymous users.
<aut hori zat i on>
<deny user s="?"/ >
</ aut hor i zat i on>
The following code allows the user Mary access to a page:
<aut hor i zat i on>
<al l ow user s="Mar y"/ >
</ aut hor i zat i on>
The following example denies all anonymous users access to the
ShoppingCart.aspx page.
<l ocat i on pat h="Shoppi ngCar t . aspx">
<syst em. web>
<aut hor i zat i on>
<deny user s="?"/ >
</ aut hor i zat i on>
</ syst em. web>
</ l ocat i on>
For more information about setting up authorization in web.config, see
ASP.NET Authorization in the Microsoft .NET Framework SDK
documentation.
32 Module 7: Creating a Microsoft ASP.NET Web Application
Creating a Login Form
n Login Page Verifies and Checks the Credentials of a User
l Login page validates user credentials and redirects if valid
n Reading User Credentials from Cookie
l User.Identity.Name returns the value saved by
CookieAuthentication.RedirectFromLoginPage
Sub cmdLogin_Click(s As Object, e As EventArgs)
If (login(txtEmail.Value, txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage _
(txtEmail.Value, False)
End If
End Sub
Sub cmdLogin_Click(s As Object, e As EventArgs)
If (login(txtEmail.Value, txtPassword.Value))
FormsAuthentication.RedirectFromLoginPage _
(txtEmail.Value, False)
End If
End Sub
*****************************illegal for non-trainer use******************************
During authentication, all requests are redirected to the login page specified in
the loginurl attribute of the <cookie> tag. The login page verifies and checks
the credentials of a user.
How Does a Login Page Work?
If the authentication mode is set to "Forms", ASP.NET looks for a cookie
attached to a request for a secure page. If it does not find one, it redirects the
request to a specified login page.
On the login page, the user enters the required credentials. The page checks the
entered credentials either through application-specific code or by calling
FormsAuthentication.Authenticate. If the credentials are valid, a cookie is
generated and the user is redirected to the originally requested page by calling
FormsAuthentication.RedirectFromLoginPage . However, if the credentials
are not valid, the user stays on the login page and is given a message that
indicates that the login credentials are invalid.
The RedirectFromLoginPage method takes two parameters, userName,
which specifies the name of the user for forms authentication purposes, and
createPersistentCookie. If the value of createPersistentCookie is True, a
cookie is created on the users machine.
Module 7: Creating a Microsoft ASP.NET Web Application 33
The following table lists all the methods of the FormsAuthentication object,
which can be used in the authentication process.
Method Function
Authenticate Given the supplied credentials, this method attempts to
validate the credentials against those contained in the
configured credential store.
GetAuthCookie Creates an authentication cookie for a given user name.
This does not set the cookie as part of the outgoing
response, so that an application can have more control over
how the cookie is issued.
GetRedirectUrl Returns the redirect URL for the original request that
caused the redirect to the login page.
RedirectFromLoginPage Redirects authenticated users back to the original URL they
requested.
SetAuthCookie Creates an authentication ticket for the given userName and
attaches it to the cookies collection of the outgoing
response. It does not perform a redirect.
SignOut Given an authenticated user, calling SignOut removes the
authentication ticket by doing a SetCookie with an empty
value. This removes either durable or session cookies.
Creating a Login Page
A login page is simply an ASP.NET page with an HTML form, a Submit
button, and a Click event procedure for the Submit button.
The following is an example of a form on a login page:
<f or m r unat =ser ver >
Emai l : <i nput i d=" t xt Emai l " t ype=" t ext " r unat =ser ver / >
<BR>
Passwor d<i nput i d=" t xt Passwor d" t ype=" passwor d"
r unat ="ser ver "/ >
<BR>
<asp: but t on t ext =" Logi n" OnCl i ck=" Logi n_Cl i ck"
r unat =" ser ver " / >
<asp: l abel i d=" l bl Msg" r unat =" ser ver " / >
</ f or m>
34 Module 7: Creating a Microsoft ASP.NET Web Application
In the Click event procedure of the Submit button, you validate the information
entered in the form, then call FormsAuthentication.RedirectFromLoginPage
if it is valid. The RedirectFromLoginPage method issues the cookie and then
redirects the user to the originally requested page. The following sample code
uses a custom function named Login to validate the username and password,
and then calls RedirectFromLoginPage if they are valid:
<scr i pt l anguage="VB" r unat =ser ver >
Sub cmdLogi n_Cl i ck( Sender As Obj ect , E As Event Ar gs)
Di mst r Cust omer I d As St r i ng
' Val i dat e User Cr edent i al s
st r Cust omer I d = Logi n( t xt Emai l . Val ue, t xt Passwor d. Val ue)
I f ( st r Cust omer I d <> "") Then
For msAut hent i cat i on. Redi r ect Fr omLogi nPage _
( st r Cust omer I d, Fal se)
El se
l bl Msg. Text = " I nval i d Cr edent i al s: Pl ease t r y agai n"
End I f
End Sub
</ scr i pt >
Reading Credentials from Cookie
After a user has been authenticated, you can obtain the user name of the
authenticated user programmatically by using the User.Identity.Name property.
This is useful to build an application that uses the users name as a key to save
information in a database table or directory resource.
Using Credentials from web.config
If you do not want to write your own validation function, you can create a list
of users in the web.config file and use the FormsAuthentication.Authenticate
method to validate a username and password pair.
The following web.config file creates two valid users for an application:
<syst em. web>
<aut hent i cat i on mode="For ms">
<f or ms l ogi nur l =" democode/ Mod07/ Logi nDemo. aspx" >
<cr edent i al s passwor dFor mat =" Cl ear " >
<user name="r ut h" passwor d="passwor d"/ >
<user name="bob" passwor d=" passwor d" / >
</ cr edent i al s>
</ f or ms>
</ aut hent i cat i on>
</ syst em. web>
Module 7: Creating a Microsoft ASP.NET Web Application 35
The following event procedure on the login page calls the Authenticate method
to authenticate only those users from the web.config file:
Sub cmdLogi n_Cl i ck( S As Obj ect , E As Event Ar gs)
I f ( For msAut hent i cat i on. Aut hent i cat e _
( t xt Emai l . val ue, t xt Passwor d. Val ue) )
For msAut hent i cat i on. Redi r ect Fr omLogi nPage _
( t xt Emai l . Val ue, Fal se)
El se
l bl Msg. Text = " I nval i d Cr edent i al s: Pl ease t r y agai n"
End I f
End Sub
36 Module 7: Creating a Microsoft ASP.NET Web Application
Demonstration: Setting Up Security in web.config
*****************************illegal for non-trainer use******************************
In this demonstration, you will learn how to set up authentication in web.config
and how to create an authentication cookie in a login file.
To run the demonstration
1. Copy the files <install folder>\Democode\Mod07\config.demo,
LoginDemo.aspx, SecurePageDemo1.aspx, SecurePageDemo2.aspx,
UsingSessionVar1.aspx, and UsingSessionVar2.aspx to the root of the 2063
virtual directory.
2. Rename the file config.demo to web.config.
3. Edit the file web.config.
There is an <authentication> section that redirects all unauthenticated
requests to the LoginDemo.aspx page.
Two pages have been set up as secure pages.
4. Edit the file <install folder>\LoginDemo.aspx.
The cmdLogin_Click event procedure validates the user name and
password and calls RedirectFromLoginPage if they are valid.
5. View the unsecured page http://localhost/2063/Us ingSessionVar1.aspx page
in Internet Explorer.
6. View the secure page http://localhost/2063/SecurePageDemo1.aspx page in
Internet Explorer.
You are redirected to the LoginDemo.aspx page.
Module 7: Creating a Microsoft ASP.NET Web Application 37
7. Type an e-mail name and an invalid password (password is the only valid
password) and click Sign In Now.
It will fail because the password is invalid.
8. Type password for the password field and click Sign In Now again. You
will be redirected to the SecurePageDemo1.aspx page.
9. View the secure page http://localhost/2063/SecurePageDemo2.aspx in
Internet Explorer.
38 Module 7: Creating a Microsoft ASP.NET Web Application
Lab 7: Creating an ASP.NET Web Application
*****************************illegal for non-trainer use******************************
Objectives
After completing this lab, you will be able to:
n Use forms authentication to authenticate and authorize users when accessing
secured pages.
n Use the ASP.NET cache to save data for the _menu.aspx page.
n Maintain state of an application by saving data in a database.
Prerequisite
Before working on this lab, you must know how to use a component.
Lab Setup
There are starter and solution files associated with this lab. The starter files are
in the folder <install folder>\Labs\Lab07\Starter and the solution files for this
lab are in the folder <install folder>\Labs\Lab07\Solution.
Module 7: Creating a Microsoft ASP.NET Web Application 39
Scenario
In Exercise 1, you will use the ASP.NET cache to store a DataSet that is used
by the _menu.aspx page.
When users want to sign into the conference system, they need to enter a valid
e-mail name and corresponding password. This is done on the login.aspx page
or through register.aspx in the case of a new user. In this lab, you will first
complete the login.aspx and register.aspx pages to attempt to authenticate a user
through the use of a cookie (forms authentication). Exercises 2 and 4 involve
variations on forms authentication of this user. Exercise 3 illustrates how to
retrieve the customer ID of the authenticated user from any of the pages of your
application. You can use this ID to store customer information or products
selected by the customer in the database.
Estimated time to complete this lab: 60 minutes
40 Module 7: Creating a Microsoft ASP.NET Web Application
Exercise 1
Storing Data
In this exercise, you will programmatically cache the DataView used by the
DataList control in the file _Menu.ascx. You will then look at web.config to
see how the connection string for the Conf database is stored.
To read the DataView from the cache
1. Open the file _Menu.ascx file in the folder InetPub\wwwRoot\ASPNET.
2. At the beginning of the Page_Load event procedure, immediately after the
dvMenuItems variable is declared, add code to read the contents of the
dvMenuItems item from the cache and save it in the dvMenuItems variable.
Your code should look like the following:
dvMenuI t ems = Cache( " dvMenuI t ems" )
3. Test the contents of dvMenuItems. If the content is empty:
a. Create the DataView from the database by using the code that is already
in the event procedure.
b. Store the DataViewin the cache. Create the cache such that it will be
stored for one hour.
Your code should look like the following:
I f ( dvMenuI t ems I s Not hi ng) Then
Response. Wr i t e ( " Get t i ng i t ems f r omt he dat abase. <P>" )
Di mpr oduct s As New Conf er ence. Pr oduct sDB
dvMenuI t ems = pr oduct s. Get Pr oduct Cat egor i es( ) . _
Tabl es( 0) . Def aul t Vi ew
Cache. I nser t ( " dvMenuI t ems" , dvMenuI t ems, Not hi ng, _
Dat eTi me. Now. AddHour s( 1) , Ti meSpan. Zer o)
El se
Response. Wr i t e ( " Got i t ems f r omt he cache. <P>" )
End I f
To save and test your work
1. Save your changes to _Menu.ascx.
2. By using Internet Explorer, go to the home page of the ASPNET Web site
by viewing http://localhost/ASPNET/default.aspx
The items are retrieved from the database.
3. Refresh the page in Internet Explorer.
The items are retrieved from the cache.
Module 7: Creating a Microsoft ASP.NET Web Application 41
To investigate web.config application settings
As you can see in the _Menu.ascx file, the GetProductCategories() method is
used to get the items for the menu from the database. This method is in the
ProductsDB.vb component.
1. Open the ProductsDB.vb file from the Components folder and locate the
GetProductCategories method.
The SQL connection string is obtained from
ConferenceDB.ConnectionString.
2. Open the ConferenceDB.vb file from the Components folder and locate the
ConnectionString property.
The connection string is read from the DSN key in the <appSettings>
section of the web.config file.
3. Open the web.config file in the ASPNET Web site and locate the DSN key
in the <appSettings> section.
42 Module 7: Creating a Microsoft ASP.NET Web Application
Exercise 2
Using Forms Authentication
In this exercise, you will validate the users name and password from the
login.aspx page with information stored in the database. If the information is
valid, you will transfer the contents of the temporary shopping cart into a
permanent shopping cart for the user. Next, you will create an authentication
cookie that will be used throughout the Web site.
You will use two different classes in the conference component:
Conference.ShoppingCartDB manipulates the shopping cart and
Conference.CustomersDB accesses the customer information in the Conf
database.
The source code for these classes can be found in the
\Components\ShoppingCartDB.vb and \Components\CustomerDB.vb files in
the ASPNET Web site.
You will call the following methods:
n Conference.ShoppingCartDB.GetShoppingCartID() returns a string with
the ID of the current shopping cart.
Publ i c Funct i on Get Shoppi ngCar t I d( ) As St r i ng
n Conference.ShoppingCartDB.MigrateCart() migrates the items from one
shopping cart (temporary) to another (permanent). The permanent shopping
cart uses the customer's ID as the shopping cart ID.
Publ i c Sub Pr ocedur e Mi gr at eCar t ( ol dCar t I d As St r i ng,
NewCar t I d As St r i ng)
n Conference.CustomersDB.Login() validates an e-mail name and password
pair against credentials stored in the customers table of the database. If the
e-mail name and password pair is valid, the method returns the customer ID.
In the case of an invalid e-mail name and password pair, this method returns
an empty string.
Publ i c Funct i on Logi n( emai l As St r i ng, passwor d As St r i ng)
As St r i ng
Note
Module 7: Creating a Microsoft ASP.NET Web Application 43
To connect to a data source
1. Open the file Login.aspx in the folder InetPub\wwwRoot\ASPNET.
2. In the cmdLogin_Click event procedure, declare the variables as shown in
the following table.
Variable name Data Type
shoppingCart New Conference.ShoppingCartDB
strTempCartID String
accountSystem New Conference.CustomersDB
strCustomerID String
3. Call the Login method of the accountSystem object and store the returned
customer ID in the variable strCustomerID. Pass the e-mail name and
password to the Login method:
Your code should look like the following:
st r Cust omer I d = _
account Syst em. Logi n( t xt Emai l . Val ue, t xt Passwor d. Val ue)
4. If the returned CustomerID is empty, this indicates that the user is not
authorized to log on. Output a "login failed" message in the spnInfo label.
5. If the returned CustomerID is not empty, the user is authorized to log on and
you need to migrate the contents of the temporary shopping cart to a
permanent one by performing the following operations:
a. Get the shopping cart ID by using the GetShoppingCartId method of
the shoppingCart object and store it in the strTempCartID variable.
b. Migrate any existing temporary shopping cart items to the permanent
shopping cart by using the MigrateCart method of the shoppingCart
object. Pass the temporary shopping cart ID and the customer ID to the
method.
c. Create a non-persistent cookie and direct the user back to the Login page
by calling the RedirectFromLoginPage method of the
FormsAuthentication object.
Your code should look like the following:
I f ( st r Cust omer I d <> " " ) Then
' Get t he ol d Shoppi ng Car t I D
st r TempCar t I D = shoppi ngCar t . Get Shoppi ngCar t I d( )
' Mi gr at e exi st i ng shoppi ng car t i nt o
' per manent shoppi ng car t
shoppi ngCar t . Mi gr at eCar t ( st r TempCar t I D, st r Cust omer I d)
' Redi r ect br owser back t o or i gi nat i ng page
For msAut hent i cat i on. Redi r ect Fr omLogi nPage( _
st r Cust omer I d, f al se)
El se ' Logi n f ai l ed
spnI nf o. i nner HTML = "Logi n Fai l ed"
End I f
44 Module 7: Creating a Microsoft ASP.NET Web Application
To save and test your work
1. Save your changes to login.aspx.
2. By using Internet Explorer, go to the Login page of the ASPNET Web site
by viewing http://localhost/ASPNET/Login.aspx
3. Fill out the e-mail field with someone@microsoft.com with a blank
password and click Sign In Now.
You will get the Login Failed message.
4. Fill in the password field with the value password and click Sign In Now.
You will be redirected to the default page of the ASPNET Web site,
default.aspx.
The e-mail name and password pair
someone@microsoft.com/password is already in the database.
Note
Module 7: Creating a Microsoft ASP.NET Web Application 45
Exercise 3
Retrieving Cookie Data in ASP.NET Pages
In this exercise, you will add code to the GetID.aspx page that reads the
customer ID (also known as Cart ID) from the authentication cookie. If the
customer has not been authenticated, you will use a temporary ID. The
GetID.aspx page is not directly linked to the ASPNET Web site. Instead, it
simply reads the customer ID or temporary ID and displays it.
To read the customer ID
1. Add the GetID.aspx page to the ASPNET Web site.
a. On the Project menu, click Add Existing Item.
b. In the Add Existing Item dialog box, navigate to the
<install folder>\Labs\Lab07\Starter folder.
c. Select the GetID.aspx file, and then click Open.
You will be asked if you want to create a new class file. Click No.
2. Open the GetID.aspx file.
3. Locate the comment:
' TO DO: Read t he cust omer I D
4. Test the value of User.Identity.Name.
5. If the string is not empty (""), output the value of User.Identity.Name using
Response.write.
Note
46 Module 7: Creating a Microsoft ASP.NET Web Application
6. If the string is empty, the user has not previously been authenticated.
a. Read the value of the Conference_CartID cookie. This cookie is issued
the first time a non-authentic ated user accesses the shopping cart.
b. If the cookie is not empty, output the value of the Conference_CartID
cookie.
c. If the cookie is empty, output a message that says that the customer is
not authenticated, and has not yet accessed the shopping cart.
Your code should look like the following:
I f User . I dent i t y. Name <> " " Then
Response. wr i t e( " Cust omer I D f r omaut hent i cat i on " & _
"cooki e: <br >")
Response. wr i t e( User . I dent i t y. Name)
El se
I f Request . Cooki es( " Conf er ence_Car t I D" ) I s Not hi ng Then
Response. wr i t e( " Cust omer not aut hent i cat ed " & _
"and has not accessed t he shoppi ng car t yet ")
El se
Response. wr i t e( " Tempor ar y Cust omer I D st or ed " & _
" i n a cooki e: <br >" )
Response. wr i t e( _
Request . Cooki es( " Conf er ence_Car t I D" ) . Val ue)
End I f
End I f
To save and test your work
1. Save your changes to GetID.aspx.
2. Start a new instance of Internet Explorer and go to the GetID.aspx page by
viewing http://localhost/ASPNET/GetID.aspx
You should be able to see the message stating that the customer is not
authenticated and has not yet accessed the shopping cart.
3. Click Go to Home Page.
4. Select an item and add it to the shopping cart.
5. Go back to the GetID.aspx page and click Refresh.
You should see the message that a temporary customer ID is stored in a
cookie, as well as the value of the temporary ID.
6. Click Go to Login Page.
7. Enter a valid e-mail name and password, and then click Sign In Now. For
this lab, use someone@microsoft.com for the user name and password for
the password.
8. Go back to the GetID.aspx page, and click Refresh.
You should see the message that the customer ID is from an authentication
cookie and the value of the Customer ID.
Module 7: Creating a Microsoft ASP.NET Web Application 47
To view the GetShoppingCartId method
1. Open the ShoppingCartDB.vb file in the Components folder of the ASPNET
Web site.
2. Locate the GetShoppingCartID method.
This method returns an ID to be used for adding items to a shopping cart in
the database. The method returns the value of the authenticated user, the
value stored in the Conference_CartID cookie, or a new temporary ID
created by calling Guid.NewGuid.
48 Module 7: Creating a Microsoft ASP.NET Web Application
Exercise 4
Using Forms Authentication in Register.aspx
In this exercise, you will add a new customer to the database. Next, you will
create an authentication cookie for the new customer. Afterward, you will
transfer the content of the temporary shopping cart into the new customers
permanent shopping cart and redirect to the shopping cart page
(ShoppingCart.aspx).
As you did in the previous exercise, you will call two different components: the
first, named Conference.ShoppingCartDB, is used to manipulate the shopping
cart; the second, Conference.CustomersDB is used to access to the customer
information.
You will need to call the Conference.CustomersDB.AddCustomer() method,
which inserts a new customer record into the customers database. This method
returns a unique Customer ID.
Publ i c Funct i on AddCust omer ( f ul l Name As St r i ng, emai l As
St r i ng, passwor d As St r i ng) As St r i ng
To connect to a data source
1. Open the file Register.aspx in the folder InetPub\wwwRoot\ASPNET.
2. Delete the following ins truction from the cmdValidation_Click event
procedure:
Response. Redi r ect ( " val i dOK. aspx" )
3. In the cmdValidation_Click event procedure, declare the following
variables:
Variable Name Data Type
shoppingCart New Conference.ShoppingCartDB
strTempCartID String
accountSystem New Conference.CustomersDB
strCustomerID String
4. Call the GetShoppingCartId method of the shoppingCart object to read
the current shopping cart ID. Save the value in the strTempCartID variable.
5. Create a new customer in the Customers table of the database by calling the
AddCustomer method of the accountSystem object. Save the created
customer ID in the strCustomerID variable.
Your code should look like the following:
st r Cust omer I d = _
account Syst em. AddCust omer ( t xt Ful l Name. Text , _
t xt Emai l . Text , t xt Passwor d. Text )
Use the Text property of these controls because they are Web
controls.
Note
Module 7: Creating a Microsoft ASP.NET Web Application 49
6. If the returned CustomerID is not empty, the user was added to the database
and you need to migrate the items in the temporary shopping cart to the
permanent shopping cart:
a. Authenticate a non-persistent cookie by passing the strCustomerID
parameter to the SetAuthCookie method.
b. Get the shopping cart ID by using the GetShoppingCartId method of
the shoppingCart object and store it in the strTempCartID variable.
c. Migrate any existing shopping cart items to the permanent shopping cart
by using the MigrateCart method of the shoppingCart object. Pass the
temporary cart ID and the customer ID to the MigrateCart method.
d. Redirect the user to the shoppingCart.aspx page he or she came from by
calling the Navigate method of the Page object.
Your code should look like the following:
I f ( st r Cust omer I d <> " " ) Then
' Set t he user ' s aut hent i cat i on name t o t he cust omer I d
For msAut hent i cat i on. Set Aut hCooki e( st r Cust omer I d, Fal se)
' Mi gr at e any exi st i ng shoppi ng car t i t ems i nt o
' t he per manent shoppi ng car t
shoppi ngCar t . Mi gr at eCar t ( st r TempCar t I D, st r Cust omer I d)
' Redi r ect br owser back t o shoppi ng car t page
Response. Redi r ect ( "Shoppi ngCar t . aspx")
End I f
To save and test your work
1. Save your changes to Register.aspx.
2. Using Internet Explorer, go to the register page of the ASPNET Web site by
viewing http://localhost/ASPNET/register.aspx
3. Create a new user with your full name, your e-mail address, and a password,
and then click Submit.
4. To verify whether this new user was successfully registered, open the Login
page by viewing http://localhost/ASPNET/login.aspx. Enter the e-mail
address and password of the new user you just registered, and then click
Sign In Now!
You should receive validation and be redirected to the home page of the
ASPNET Web site, default.aspx.
50 Module 7: Creating a Microsoft ASP.NET Web Application
Review
n Requirements of a Web Application
n What Is New in ASP.NET?
n Sharing Information Between Pages
n Securing an ASP.NET Application
*****************************illegal for non-trainer use******************************
1. How do you set up a Web application to use cookie-less sessions?
2. Where is global.asax file of an application located?
3. Where is the web.config file for an application located?
4. In web.config, all configuration information must reside under what tags?
Module 7: Creating a Microsoft ASP.NET Web Application 51
5. How do you specify which authentication method will be used by an
ASP.NET application?
6. What is the difference between output cache and ASP.NET cache?
7. How can you secure an entire application?
THIS PAGE INTENTIONALLY LEFT BLANK