0% found this document useful (0 votes)
12 views258 pages

2310CK-En Developing Web Apps VS2008-TrainerManual2

The document outlines the licensing terms for the Microsoft Learning Product 'Developing Web Applications Using Microsoft Visual Studio 2008', intended for use by Microsoft Certified Trainers (MCTs) only. It details the definitions, rights, and responsibilities regarding the use of the Licensed Content, including software and training materials, and emphasizes the prohibition of student use. Additionally, it includes stipulations for pre-release versions and confidentiality requirements.

Uploaded by

eliopires
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views258 pages

2310CK-En Developing Web Apps VS2008-TrainerManual2

The document outlines the licensing terms for the Microsoft Learning Product 'Developing Web Applications Using Microsoft Visual Studio 2008', intended for use by Microsoft Certified Trainers (MCTs) only. It details the definitions, rights, and responsibilities regarding the use of the Licensed Content, including software and training materials, and emphasizes the prohibition of student use. Additionally, it includes stipulations for pre-release versions and confidentiality requirements.

Uploaded by

eliopires
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 258

MCT USE ONLY.

STUDENT USE PROHIBITED


OFFICIAL MICROSOFT LEARNING PRODUCT

2310C
Developing Web Applications
Using Microsoft® Visual Studio®
2008

Be sure to access the extended learning content on your


Course Companion CD enclosed on the back cover of the book.
ii Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


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, place or event 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.

The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
© 2008 Microsoft Corporation. All rights reserved.

Microsoft, Active Directory, ActiveX, Expression, Hotmail, IntellliSense, Internet Explorer, Jscript,
MSDN, PowerPoint, Silverlight, SQL Server, Visual Basic, Visual C#, Visual C++, Visual J#, Visual
Studio, Visual Web Developer, Windows, Windows CardSpace, Windows Media, Windows NT,
Windows Server and Windows Vista are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries.
All other trademarks are property of their respective owners.

Product Number: 2310C


Released: 04/2008
MICROSOFT LICENSE TERMS
OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER
EDITION – Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They
apply to the Licensed Content named above, which includes the media on which you received it, if any. The
terms also apply to any Microsoft
• updates,
• supplements,
• Internet-based services, and
• support services
for this Licensed Content, unless other terms accompany those items. If so, those terms apply.
By using the Licensed Content, you accept these terms. If you do not accept them, do not use
the Licensed Content.

If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Academic Materials” means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.
b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions
location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and
conducted at or through Authorized Learning Centers by a Trainer providing training to Students
solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or
“MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions
Courseware). Each Authorized Training Session will provide training on the subject matter of one
(1) Course.
d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.
e. “Device(s)” means a single computer, device, workstation, terminal, or other digital electronic or
analog device.
f. “Licensed Content” means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.
g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.
h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.
i. “Student Content” means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.
j. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.
k. “Trainer Content” means the materials accompanying these license terms that are for use by
Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.
l. “Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.
m. “Virtual Machine” means a virtualized computing experience, created and accessed using
Microsoft® Virtual PC or Microsoft® Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered “Trainer Content”.
n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.
2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.
3. INSTALLATION AND USE RIGHTS.
a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i. either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR
ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.
i. Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.
ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.
b. Trainers:
i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.
ii. Trainers may also Use a copy of the Licensed Content as follows:
A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.
B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.
4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions
in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not
contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.
c. Confidential Information. The Licensed Content, including any viewer, user interface, features
and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i. Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.
ii. Survival. Your duty to protect confidential information survives this agreement.
iii. Exclusions. You may disclose confidential information in response to a judicial or
governmental order. You must first give written notice to Microsoft to allow it to seek a
protective order or otherwise protect the information. Confidential information does not
include information that
• becomes publicly known through no wrongful act;
• you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or
• you developed independently.

d. Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs
you is the end date for using the beta version, or (ii) the commercial release of the final release
version of the Licensed Content, whichever is first (“beta term”).
e. Use. You will cease using all copies of the beta version upon expiration or termination of the beta
term, and will destroy all copies of same in the possession or under your control and/or in the
possession or under the control of any Trainers who have received copies of the pre-released
version.
f. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta
version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If
Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you
for such copies and distribution.
5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.
a. Authorized Learning Centers and Trainers:
i. Software.
ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft
Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced
Server and/or other Microsoft products which are provided in Virtual Hard Disks.
A. If the Virtual Hard Disks and the labs are launched through the Microsoft
Learning Lab Launcher, then these terms apply:
Time-Sensitive Software. If the Software is not reset, it will stop running based upon the
time indicated on the install of the Virtual Machines (between 30 and 500 days after you
install it). You will not receive notice before it stops running. You may not be able to
access data used or information saved with the Virtual Machines when it stops running and
may be forced to reset these Virtual Machines to their original state. You must remove the
Software from the Devices at the end of each Authorized Training Session and reinstall and
launch it prior to the beginning of the next Authorized Training Session.
B. If the Virtual Hard Disks require a product key to launch, then these terms
apply:
Microsoft will deactivate the operating system associated with each Virtual Hard Disk.
Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized
Training Session, you will obtain from Microsoft a product key for the operating system
software for the Virtual Hard Disks and will activate such Software with Microsoft using such
product key.
C. These terms apply to all Virtual Machines and Virtual Hard Disks:
You may only use the Virtual Machines and Virtual Hard Disks if you comply with
the terms and conditions of this agreement and the following security
requirements:
o You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
Devices that are accessible to other networks.
o You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at
the end of each Authorized Training Session, except those held at Microsoft Certified
Partners for Learning Solutions locations.
o You must remove the differencing drive portions of the Virtual Hard Disks from all
classroom Devices at the end of each Authorized Training Session at Microsoft Certified
Partners for Learning Solutions locations.
o You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
downloaded from Devices on which you installed them.
o You will strictly comply with all Microsoft instructions relating to installation, use,
activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.
o You may not modify the Virtual Machines and Virtual Hard Disks or any contents
thereof.
o You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.
ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the
Course.
iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip
art, animations, sounds, music, shapes, video clips and templates provided with the Licensed
Content solely in an Authorized Training Session. If Trainers have their own copy of the
Licensed Content, they may use Media Elements for their personal training use.
iv. iv Evaluation Software. Any Software that is included in the Student Content designated as
“Evaluation Software” may be used by Students solely for their personal training outside of the
Authorized Training Session.
b. Trainers Only:
i. Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft
PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for
providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree
or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of
obscene or scandalous works, as defined by federal law at the time the work is created; and
(b) to comply with all other terms and conditions of this agreement.
ii. Use of Instructional Components in Trainer Content. For each Authorized Training
Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those
portions of the Licensed Content that are logically associated with instruction of the Authorized
Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer
agrees: (a) that any of these customizations or reproductions will only be used for providing an
Authorized Training Session and (b) to comply with all other terms and conditions of this
agreement.
iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and
use the Academic Materials. You may not make any modifications to the Academic Materials
and you may not print any book (either electronic or print version) in its entirety. If you
reproduce any Academic Materials, you agree that:

• The use of the Academic Materials will be only for your personal reference or training use
• You will not republish or post the Academic Materials on any network computer or
broadcast in any media;
• You will include the Academic Material’s original copyright notice, or a copyright notice to
Microsoft’s benefit in the format provided below:
Form of Notice:
© 2008 Reprinted for personal reference use only with permission by Microsoft
Corporation. All rights reserved.
Microsoft, Windows, and Windows Server are either registered trademarks or
trademarks of Microsoft Corporation in the US and/or other countries. Other
product and company names mentioned herein may be the trademarks of their
respective owners.
6. INTERNET-BASED SERVICES. Microsoft may provide Internet-based services with the Licensed
Content. It may change or cancel them at any time. You may not use these services in any way that
could harm them or impair anyone else’s use of them. You may not use the services to try to gain
unauthorized access to any service, data, account or network by any means.
7. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some
rights to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you
more rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that
only allow you to use it in certain ways. You may not
• install more copies of the Licensed Content on classroom Devices than the number of Students and
the Trainer in the Authorized Training Session;
• allow more classroom Devices to access the server than the number of Students enrolled in and the
Trainer delivering the Authorized Training Session if the Licensed Content is installed on a network
server;
• copy or reproduce the Licensed Content to any server or location for further reproduction or
distribution;
• disclose the results of any benchmark tests of the Licensed Content to any third party without
Microsoft’s prior written approval;
• work around any technical limitations in the Licensed Content;
• reverse engineer, decompile or disassemble the Licensed Content, except and only to the extent
that applicable law expressly permits, despite this limitation;
• make more copies of the Licensed Content than specified in this agreement or allowed by applicable
law, despite this limitation;
• publish the Licensed Content for others to copy;
• transfer the Licensed Content, in whole or in part, to a third party;
• access or use any Licensed Content for which you (i) are not providing a Course and/or (ii) have not
been authorized by Microsoft to access and use;
• rent, lease or lend the Licensed Content; or
• use the Licensed Content for commercial hosting services or general business purposes.
• Rights to access the server software that may be included with the Licensed Content, including the
Virtual Hard Disks does not give you any right to implement Microsoft patents or other Microsoft
intellectual property in software or devices that may access the server.
8. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and
regulations. You must comply with all domestic and international export laws and regulations that apply
to the Licensed Content. These laws include restrictions on destinations, end users and end use. For
additional information, see www.microsoft.com/exporting.
9. NOT FOR RESALE SOFTWARE/LICENSED CONTENT. You may not sell software or Licensed
Content marked as “NFR” or “Not for Resale.”
10. ACADEMIC EDITION. You must be a “Qualified Educational User” to use Licensed Content marked as
“Academic Edition” or “AE.” If you do not know whether you are a Qualified Educational User, visit
www.microsoft.com/education or contact the Microsoft affiliate serving your country.
11. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you
fail to comply with the terms and conditions of these license terms. In the event your status as an
Authorized Learning Center or Trainer a) expires, b) is voluntarily terminated by you, and/or c) is
terminated by Microsoft, this agreement shall automatically terminate. Upon any termination of this
agreement, you must destroy all copies of the Licensed Content and all of its component parts.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates, Internet-
based services and support services that you use, are the entire agreement for the Licensed
Content and support services.
13. APPLICABLE LAW.
a. United States. If you acquired the Licensed Content in the United States, Washington state law
governs the interpretation of this agreement and applies to claims for breach of it, regardless of
conflict of laws principles. The laws of the state where you live govern all other claims, including
claims under state consumer protection laws, unfair competition laws, and in tort.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws
of that country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the
laws of your country. You may also have rights with respect to the party from whom you acquired the
Licensed Content. This agreement does not change your rights under the laws of your country if the
laws of your country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. The Licensed Content is licensed “as-is.” You bear the risk of
using it. Microsoft gives no express warranties, guarantees or conditions. You may have
additional consumer rights under your local laws which this agreement cannot change. To
the extent permitted under your local laws, Microsoft excludes the implied warranties of
merchantability, fitness for a particular purpose and non-infringement.
16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. YOU CAN RECOVER FROM
MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT
RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL,
INDIRECT OR INCIDENTAL DAMAGES.
This limitation applies to
• anything related to the Licensed Content, software, services, content (including code) on third party
Internet sites, or third party programs; and
• claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in
this agreement are provided below in French.

Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses
dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre
garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont
exclues.
LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES
DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de
dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation
pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de
bénéfices.
Cette limitation concerne:
• tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers ; et
• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte,
de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel
dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages
indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne
s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits
prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de
votre pays si celles-ci ne le permettent pas.
Developing Web Applications Using Microsoft® Visual Studio® 2008 iii

MCT USE ONLY. STUDENT USE PROHIBITED


Contents
Module 1: Overview of the Microsoft .NET Framework
Lesson 1: Introduction to the .NET Framework 1-3
Lesson 2: Overview of ASP.NET 1-8
Lesson 3: Overview of the Lab Application 1-13

Module 2: Creating Web Applications by Using Microsoft Visual Studio 2008


and Microsoft .NET-Based Languages
Lesson 1: Overview of Visual Studio 2008 2-3
Lesson 2: Creating an ASP.NET Web Application Project 2-8
Lesson 3: Overview of the Microsoft .NET-Based Languages 2-13
Lesson 4: Creating a Component by Using Visual Studio 2008 2-19
Lab: Creating Web Applications by Using Microsoft Visual Studio 2008 and
Microsoft .NET-Based Languages 2-24

Module 3: Creating a Microsoft ASP.NET Web Form


Lesson 1: Creating Web Forms 3-3
Lesson 2: Adding Server Controls to a Web Form 3-6
Lesson 3: Creating Master Pages 3-13
Lab: Creating a Microsoft ASP.NET Web Form 3-18

Module 4: Adding Code to a Microsoft ASP.NET Web Form


Lesson 1: Implementing Code-Behind Pages 4-3
Lesson 2: Adding Event Procedures to Web Server Controls 4-8
Lesson 3: Handling Page Events 4-17
Lab: Adding Functionality to a Web Application 4-24
iv Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module 5: Tracing in Microsoft ASP.NET Web Applications
Lesson 1: Tracing and the Trace Object 5-3
Lesson 2: Remote Debugging 5-11
Lab: Tracing in Microsoft ASP.NET Web Applications 5-14

Module 6: Validating User Input


Lesson 1: Overview of User Input Validation 6-3
Lesson 2: Validation Controls 6-8
Lesson 3: Page Validation 6-16
Lab: Validating User Input 6-19

Module 7: Creating and Implementing User Controls


Lesson 1: Adding User Controls to an ASP.NET Web Form 7-3
Lesson 2: Creating User Controls 7-6
Lab: Creating and Implementing User Controls 7-10

Module 8: Accessing Data with Microsoft ADO.NET and Visual Studio 2008
Lesson 1: Overview of ADO.NET 8-3
Lesson 2: Connecting to a Database 8-8
Lesson 3: Accessing Data 8-13
Lesson 4: Accessing Multiple Tables 8-21
Lab: Accessing Data with Microsoft ADO.NET and Visual Studio 2008 8-25

Module 9: Accomplishing Complex Data Access Tasks


Lesson 1: Overview of Stored Procedures 9-3
Lesson 2: Calling Stored Procedures 9-6
Lesson 3: Data Access by Using LINQ to SQL 9-12
Lab: Accomplishing Complex Data Access Tasks 9-19
Developing Web Applications Using Microsoft® Visual Studio® 2008 v

MCT USE ONLY. STUDENT USE PROHIBITED


Module 10: Reading and Writing XML Data
Lesson 1: Overview of XML Architecture in ASP.NET 10-3
Lesson 2: XML and the DataSet Object 10-6
Lesson 3: Managing XML Data 10-12
Lesson 4: Accessing XML Data by Using the XML Web Server Control 10-18
Lab: Reading XML Data 10-21

Module 11: Creating a Microsoft® ASP.NET AJAX Application


Lesson 1: Introduction to ASP.NET AJAX 11-3
Lesson 2: Creating an ASP.NET AJAX Application by Using the ASP.NET AJAX
Extensions 11-7
Lesson 3: Extending an Application by Using the ASP.NET
AJAX Control Toolkit 11-13
Lab: Creating a Microsoft ASP.NET AJAX Application 11-17

Module 12: Delivering Dynamic Content with Microsoft Silverlight


Lesson 1: Overview of Microsoft Silverlight 12-3
Lesson 2: Creating Silverlight-Based Applications with Visual Studio 2008
12-8
Lab: Delivering Dynamic Content with Microsoft Silverlight 12-14

Module 13: Consuming and Creating XML Web Services


Lesson 1: Overview of XML Web Services 13-3
Lesson 2: Calling an XML Web Service 13-8
Lesson 3: Creating an XML Web Service 13-14
Lab: Consuming and Creating XML Web Services 13-17

Module 14: Managing State


Lesson 1: State Management 14-3
Lesson 2: Application and Session Variables 14-9
Lesson 3: Cookies and Cookieless Sessions 14-15
Lab: Storing Application and Session Data 14-20
vi Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module 15: Configuring, Optimizing, and Deploying a Microsoft® ASP.NET
Web Application
Lesson 1: Implementing the Cache Object 15-3
Lesson 2: ASP.NET Output Caching 15-8
Lesson 3: Configuring an ASP.NET Web Application 15-13
Lesson 4: Deploying an ASP.NET Web Application 15-21
Lab: Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web
Application 15-26

Module 16: Securing a Microsoft ASP.NET Web Application


Lesson 1: Web Application Security Overview 16-3
Lesson 2: Windows-Based Authentication 16-10
Lesson 3: Forms-Based Authentication 16-13
Lab: Securing a Microsoft ASP.NET Web Application 16-19
Course Evaluation 16-32
Accomplishing Complex Data Access Tasks 9-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 9
Accomplishing Complex Data Access Tasks
Contents:
Lesson 1: Overview of Stored Procedures 9-3
Lesson 2: Calling Stored Procedures 9-6
Lesson 3: Data Access by Using LINQ to SQL 9-12
Lab: Accomplishing Complex Data Access Tasks 9-19
9-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

Direct access and manipulation of data from a Web Form can be a very inefficient
use of resources and can create security risks. One way to improve the efficiency
and security of database access is to create stored procedures on the database
server and then call these stored procedures from your Web Form. Data access by
using a stored procedure limits the Web Form code and the network bandwidth
that you have to use when you perform complex tasks. It also protects the database
by limiting direct access to the database to trusted, local stored procedures.
The Microsoft® .NET Framework 3.5 introduces LINQ to SQL. LINQ to SQL is an
object-relational mapping implementation that enables you to use .NET
Framework classes to model, query, and update a relational database. This module
describes how to accomplish data access tasks from Web applications by using
Microsoft ADO.NET to access stored procedures. It also introduces LINQ to SQL
and explains how to use this new implementation to access a Microsoft SQL
Server™ database.
Accomplishing Complex Data Access Tasks 9-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Overview of Stored Procedures

One alternative to direct database access from your Web application is to call a
stored procedure that accesses the database for you. Stored procedures have
several advantages over direct database access; these include efficiency, security,
and the protection of the database.
This lesson describes stored procedures and explains the reasons why you call
stored procedures when you access a database.
9-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is a Stored Procedure?

Key Points
You create stored procedures for use with a specific database and store them in
that database. Stored procedures that you create in a SQL Server database consist
of one or more sequences of Transact-SQL statements and can have input and
output parameters.

Question: What stored procedures do you use in your own applications?


Accomplishing Complex Data Access Tasks 9-5

MCT USE ONLY. STUDENT USE PROHIBITED


Why Use Stored Procedures?

Key Points
Stored procedures have several advantages over direct Transact-SQL statements.
For example, they can provide increased security, faster performance, flexibility,
and a reduction in network traffic.

Question: How can stored procedures improve the security or performance of


your own applications?
9-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Calling Stored Procedures

Before you can call a stored procedure, you must identify the procedure name and
the available parameters. After you identify the stored procedure, you can call the
procedure, pass any input parameters that are required to process your request,
and handle the output parameters that are included in the response.
This lesson describes how to call stored procedures, pass input parameters, and
handle output parameters.
Accomplishing Complex Data Access Tasks 9-7

MCT USE ONLY. STUDENT USE PROHIBITED


Calling Stored Procedures

Key Points
The method that you call to run the stored procedure varies depending on the type
of stored procedure that you want to call, as shown in the following list:
• Return records stored procedures. Call the Fill method of the DataAdapter to
place the records in a DataSet or call the ExecuteReader method of the
Command object to place the records in a DataReader.
• Return value stored procedures. Call the ExecuteScalar method of the
Command object and save the result in a variable of the appropriate data type.
• Perform action stored procedures. Call the ExecuteNonQuery method of the
Command object.
9-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Parameters in Stored Procedures

Key Points
Parameters enable you to pass information into a stored procedure and receive
information back from it.
The names of the parameters that you add to the Parameters collection of the
SqlCommand object must match the names of the parameters that are in the
stored procedure; however, the order of the parameters is flexible.

Question: What is the difference between an output parameter and a return value
parameter?
Accomplishing Complex Data Access Tasks 9-9

MCT USE ONLY. STUDENT USE PROHIBITED


Passing Input Parameters

Key Points
To create an input parameter, use the following steps:
• Create a new SqlParameter object with the name and data type of the
parameter.
• Set the Direction property of the new parameter.
• Use the Add method of the Parameters collection to save the new parameter.
9-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Accessing Output Parameters

Key Points
To read the value of an output parameter or to read a returned value from a return
records stored procedure, you access the value of the output parameter in the
Parameters collection after the stored procedure has run.
Accomplishing Complex Data Access Tasks 9-11

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Passing Parameters

In this demonstration, you will see how to call a stored procedure that has two
input parameters and then bind the results to a GridView control.
9-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Data Access by Using LINQ to SQL

Microsoft Visual Studio® 2008 and the .NET Framework 3.5 introduce Language-
Integrated Query (LINQ), which provides a way for you to query data by using
Microsoft Visual C#® or Microsoft Visual Basic®. This lesson introduces LINQ
and describes how to use Visual Studio 2008 to query a SQL Server database by
using LINQ to SQL.
Accomplishing Complex Data Access Tasks 9-13

MCT USE ONLY. STUDENT USE PROHIBITED


What Is LINQ?

Key Points
Language-Integrated Query (LINQ) provides a programming model that you can
use to retrieve and update data from a variety of sources by using Visual C# and
Visual Basic syntax.
Visual Studio 2008 provides designer tools that you use to create an object-
relational mapping to the objects in the data store that you want to query.

Question: What are the advantages of a model that enables you to use Visual C#
or Visual Basic to query a database?
9-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Creating a LINQ to SQL Object Model

Key Points
You define the object model for a database in a LINQ to SQL Classes file, which
has a .dbml extension.
To open the Object Relational Designer (O/R Designer), you add a LINQ to SQL
Classes file to your application by using the Add New Item dialog box.
Accomplishing Complex Data Access Tasks 9-15

MCT USE ONLY. STUDENT USE PROHIBITED


The DataContext Class

Key Points
Visual Studio 2008 creates an entity class for each database table in the O/R
Designer. In addition, Visual Studio 2008 creates a DataContext class. This class
contains properties that represent each table that you add to the O/R Designer and
methods that represent each stored procedure or function.

Question: What is the purpose of the DataContext class?


9-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Querying a Database

Key Points
After you model a database by using the O/R Designer, the next step is to write
code that uses the model to run queries against the database.
A query expression must always begin with a from clause and end with either a
select or a group clause. Other optional clauses include join, where, let, and
orderby.
Accomplishing Complex Data Access Tasks 9-17

MCT USE ONLY. STUDENT USE PROHIBITED


Calling a Stored Procedure

Key Points
Stored procedures are represented by methods of the DataContext class. The
default name of the method is the same as the stored procedure name.
To run the stored procedure, call the appropriate method on the DataContext
class. The method returns a sequence of strongly typed results from the stored
procedure.

Question: What are the differences in the code required to call a stored procedure
by using ADO.NET and LINQ to SQL syntax?
9-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Binding a Data Model by Using the LinqDataSource Control

Key Points
The LinqDataSource control enables you to display data from a database by using
LINQ to SQL but without writing any code at all.
You can use a LinqDataSource control to bind to a LINQ data model and then set
the DataSourceID of a list-bound control to the LinqDataSource control.

Question: Describe a scenario when you may use a LinqDataSource control.


Accomplishing Complex Data Access Tasks 9-19

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Accomplishing Complex Data Access Tasks

Exercise 1: Get Unique City Names


Scenario
Coho Winery offers several benefits to its employees. In the labs for this course,
you will create a Web site that enables employees to select and set up their chosen
benefits.
One benefit that is offered by Coho Winery is medical insurance. When users
apply for medical insurance, they must select a primary care physician. The doctors
that are approved by your company are all listed in a SQL Server database that is
named doctors. The doctors’ specialties are also in the database. In this lab, you
will enhance the doctors.aspx page on the Coho Winery Web site to enable users
to view the list of specialties for a selected doctor.
In this exercise, you will bind the citiesList list on the doctors.aspx page so that
the list displays only unique city names from the doctors database. When the user
selects a city, the code will create a new view of the data and display the data in the
GridView control on the page.
9-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


The citiesList list is currently bound to the city field in the Doctors table by using
a SqlCommand object. This result of this binding is that the list displays all the
cities in the table. In this exercise, you will use a stored procedure to select only
unique city names from the doctors table.
Because the citiesList list is currently bound, you must first remove that binding
before you use the stored procedure.
The main tasks for this exercise are as follows:
1. Open the Benefits Web site.
2. Remove the existing binding code.
3. Bind the citiesList list by using a stored procedure.

f Task 1: Open the Benefits Web site


1. Open Visual Studio 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.

f Task 2: Remove the existing binding code


1. In the Benefits project, open the doctors.aspx.cs or doctors.aspx.vb page.
2. In the Page_Load event procedure, locate the following code.

[Visual C#]
// Bind the list to city field in the doctors table.
CreateDataSet()
SqlCommand citiesSqlCommand =
new SqlCommand("Select city FROM doctors", doctorsConnection);
SqlDataReader citiesSqlDataReader;

doctorsConnection.Open();
citiesSqlDataReader = citiesSqlCommand.ExecuteReader();
citiesList.DataSource = citiesSqlDataReader;
citiesList.DataTextField = "city";
citiesList.DataBind();
citiesSqlDataReader.Close();
doctorsConnection.Close();
Accomplishing Complex Data Access Tasks 9-21

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual Basic]
' Bind the list to city field in the doctors table.
CreateDataSet()
Dim citiesSqlCommand As New SqlCommand("Select city FROM doctors", _
doctorsConnection)
Dim citiesSqlDataReader As SqlDataReader

doctorsConnection.Open()
citiesSqlDataReader = citiesSqlCommand.ExecuteReader()
citiesList.DataSource = citiesSqlDataReader
citiesList.DataTextField = "city"
citiesList.DataBind()
citiesSqlDataReader.Close()
doctorsConnection.Close()

3. Comment out the preceding lines of code.

f Task 3: Bind the citiesList list by using a stored procedure


1. In the Page_Load event procedure, locate the following comment.

TODO Lab9: Bind the listbox to the getUniqueCities stored procedure.

2. In the code file, underneath the comment, call the CreateDataSet method.
3. Create a new SqlCommand object named citiesSqlCommand that uses the
doctorsConnection object to call the getUniqueCities stored procedure.
4. Set the CommandType for the citiesSqlCommand object to
StoredProcedure.
5. Declare a SqlDataReader object named citiesSqlDataReader.
6. Open the doctorsConnection SqlConnection object.
7. Build the citiesSqlDataReader object from the citiesSqlCommand object by
calling the ExecuteReader method of the citiesSqlCommand object.
8. Set the properties of the citiesList list as shown in the following table.

Property Value

DataSource citiesSqlDataReader

DataTextField "City"
9-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


9. Call the DataBind method of the citiesList list.
10. Close the SqlDataReader and the Connection objects.

Note: You can copy some of the preceding code from the lines that you previously
commented out.

Your code should resemble the following example.

[Visual C#]
CreateDataSet()
SqlCommand citiesSqlCommand =
new SqlCommand("getUniqueCities", doctorsConnection);
citiesSqlCommand.CommandType = CommandType.StoredProcedure;
doctorsConnection.Open();
SqlDataReader citiesSqlDataReader;
citiesSqlDataReader = citiesSqlCommand.ExecuteReader();
citiesList.DataSource = citiesSqlDataReader;
citiesList.DataTextField = "City";
citiesList.DataBind();
citiesSqlDataReader.Close();
doctorsConnection.Close();

[Visual Basic]
CreateDataSet()
Dim citiesSqlCommand As New SqlCommand _
("getUniqueCities", doctorsConnection)
citiesSqlCommand.CommandType = CommandType.StoredProcedure
doctorsConnection.Open()
Dim citiesSqlDataReader As SqlDataReader
citiesSqlDataReader = citiesSqlCommand.ExecuteReader()
citiesList.DataSource = citiesSqlDataReader
citiesList.DataTextField = "City"
citiesList.DataBind()
citiesSqlDataReader.Close()
doctorsConnection.Close()

11. Save the changes to the code-behind file.


12. View the doctors.aspx page in the browser.
Accomplishing Complex Data Access Tasks 9-23

MCT USE ONLY. STUDENT USE PROHIBITED


The citiesList list displays the list of cities where the doctors are located. There
are no duplicate cities listed.
13. Close the browser window.

Results: After this exercise, you have bound the citiesList list on the doctors.aspx page
so that the list displays only unique city names from the doctors database.

Exercise 2: Get Doctor Specialties


In this exercise, you will display a doctor’s specialties in a list. When the user
selects a doctor in the doctorsGridView control, your code will call the
getDrSpecialty stored procedure and display the results in the specialtiesListBox
control.
The main tasks for this exercise are as follows:
1. Call the getDrSpecialty stored procedure.
2. Bind the specialtiesListBox control to the specialtiesSqlDataReader object
and make the list visible.

f Task 1: Call the getDrSpecialty stored procedure


1. In the doctors.aspx page, create a SelectedIndexChanged event procedure for
the doctorsGridView control.
2. In the SelectedIndexChanged event procedure, call the CreateDateSet
procedure to initialize the connection string for the database.
3. Create a string variable named drID to hold the value of the dr_id column for
the row that was selected by the user.
4. Read the value of the dr_id field and store it in the drID variable by using the
Cells collection of the SelectedRow of the doctorsGridView.
Your code should resemble the following example.

[Visual C#]
CreateDataSet();
string drID;
drID = doctorsGridView.SelectedRow.Cells[1].Text;
9-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual Basic]
CreateDataSet()
Dim drID As String
drID = doctorsGridView.SelectedRow.Cells.Item(1).Text

5. Create a new SqlCommand object named specialtiesSqlCommand that uses


the doctorsConnection object to call the getDrSpecialty stored procedure.
6. Set the specialtiesSqlCommand command type to a stored procedure.
Your code should resemble the following example.

[Visual C#]
SqlCommand specialtiesSqlCommand =
new SqlCommand("getDrSpecialty", doctorsConnection);
specialtiesSqlCommand.CommandType = CommandType.StoredProcedure;

[Visual Basic]
Dim specialtiesSqlCommand As New SqlCommand _
("getDrSpecialty", doctorsConnection)
specialtiesSqlCommand.CommandType = CommandType.StoredProcedure

7. Create a SqlParameter object named specialtiesParameter by using the


parameter that is shown in the following table.

Parameter name Data type Size


@dr_id SqlDbType.Char 4

8. Set the Direction property of the SqlParameter to Input.


9. Set the value of the SqlParameter to the variable drID.
10. Add the parameter to the specialtiesSqlCommand object by using the Add
method.
Your code should resemble the following example.

[Visual C#]
SqlParameter specialtiesParameter = new SqlParameter
("@dr_id", SqlDbType.Char, 4);
specialtiesParameter.Direction = ParameterDirection.Input;
specialtiesParameter.Value = drID;
specialtiesSqlCommand.Parameters.Add(specialtiesParameter);
Accomplishing Complex Data Access Tasks 9-25

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual Basic]
Dim specialtiesParameter As New SqlParameter _
("@dr_id", SqlDbType.Char, 4)
specialtiesParameter.Direction = ParameterDirection.Input
specialtiesParameter.Value = drID
specialtiesSqlCommand.Parameters.Add(specialtiesParameter)

11. Create a new SqlDataReader object named specialtiesSqlDataReader.


12. Open the doctorsConnection SqlConnection object.
13. Fill the specialtiesSqlDataReader object from the specialtiesSqlCommand
object by calling the ExecuteReader method of the specialtiesSqlCommand
object.
Your code should resemble the following example.

[Visual C#]
SqlDataReader specialtiesSqlDataReader;
doctorsConnection.Open();
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader();

[Visual Basic]
Dim specialtiesSqlDataReader As SqlDataReader
doctorsConnection.Open()
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader()

f Task 2: Bind the specialtiesListBox control to the


specialtiesSqlDataReader object and make the list visible
1. In the SelectedIndexChanged event procedure, set the properties for the
specialtiesListBox control as shown in the following table.
9-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Property Value

DataSource specialtiesSqlDataReader

DataTextField "Specialty"

2. Call the DataBind method of the list.


Your code should resemble the following example.

[Visual C#]
specialtiesListBox.DataSource = specialtiesSqlDataReader;
specialtiesListBox.DataTextField = "Specialty";
specialtiesListBox.DataBind();

[Visual Basic]
specialtiesListBox.DataSource = specialtiesSqlDataReader
specialtiesListBox.DataTextField = "Specialty"
specialtiesListBox.DataBind()

3. Add code to make the specialtiesListBox list and specialtiesLabel label


visible if there are specialties in the specialtiesSqlDataReader.
Your code should resemble the following example.

[Visual C#]
if (specialtiesSqlDataReader.IsClosed == false)
{
specialtiesListBox.Visible = specialtiesSqlDataReader.HasRows;
specialtiesLabel.Visible = specialtiesSqlDataReader.HasRows;
}

[Visual Basic]
If specialtiesSqlDataReader.IsClosed = False Then
specialtiesListBox.Visible = specialtiesSqlDataReader.HasRows
specialtiesLabel.Visible = specialtiesSqlDataReader.HasRows
End If

4. Close the specialtiesSqlDataReader and doctorsConnection objects.


Your code should resemble the following example.
Accomplishing Complex Data Access Tasks 9-27

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual C#]
specialtiesSqlDataReader.Close();
doctorsConnection.Close();

[Visual Basic]
specialtiesSqlDataReader.Close()
doctorsConnection.Close()

5. Save the changes to the code-behind file.


6. Build the Benefits Web site.
7. View the doctors.aspx page in the browser.
8. In the browser, select a doctor from the list.
The Specialties list displays the specialties for the selected doctor.
9. Choose a city from the citiesList list, and then select a new doctor.
The Specialties list may display a different list of specialties. If it does not,
select a different doctor to ensure that your code works properly.
10. Click Submit.
You are redirected to the medical.aspx page, and the selected doctor’s name
displays in the Primary Care Physician box.

Results: After this exercise, you have called the GetDrSpecialty stored procedure to
display a doctor’s specialties in a list when the user selects a doctor in the
doctorsGridView control.

Exercise 3: Get Doctor Specialties by Using LINQ to SQL


In this exercise, you will duplicate the functionality that you implemented in
Exercise 2 to display a doctor’s specialties in a list. However, in this exercise, you
will use LINQ to SQL to achieve the required result.
The main tasks for this exercise are as follows:
1. Add a connection to the doctors database.
2. Open the O/R Designer.
3. Create the doctors DataContext class.
9-28 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


4. Call the getDrSpecialty stored procedure by using LINQ to SQL.

f Task 1: Add a connection to the doctors database


1. In Server Explorer, right-click the Data Connections folder, and then click
Add Connection.
2. In the Add Connection dialog box:
a) In the Server name box, type london\sqlexpress
b) In the Select or enter a database name list, click doctors, and then click
OK.

f Task 2: Open the O/R Designer


1. In Solution Explorer, right-click the App_Code folder, and then click Add New
Item.
2. In the App_Code folder of the Benefits Web site, add a LINQ to SQL Classes
item named Doctors.dbml.
An empty LINQ to SQL Classes file named Doctors.dbml is added to the
project, and the O/R Designer opens.

f Task 3: Create the doctors DataContext class


1. In Server Explorer, expand the connection to the doctors database, and then
locate the getDrSpecialty stored procedure.
2. Drag the getDrSpecialty stored procedure onto the right pane of the O/R
Designer window.
The O/R Designer creates the getDrSpecialty method for the LINQ to SQL
DataContext class.
3. Save the Doctors.dbml file.
4. Open the Class View window.
5. In the Class View window, expand the Benefits Web site, and then click
DoctorsDataContext.
6. Examine the methods of the DoctorsDataContext class and locate the
getDrSpecialty method.
Accomplishing Complex Data Access Tasks 9-29

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 4: Call the getDrSpecialty stored procedure by using LINQ to SQL
1. View the code-behind file of the doctors.aspx page.
2. In the code file, locate the doctorsGridView_SelectedIndexChanged event
procedure.
3. In the doctorsGridView_SelectedIndexChanged event procedure, comment
out all the lines of code.
You will duplicate the functionality of this code by using LINQ to SQL.
4. In the doctorsGridView_SelectedIndexChanged event procedure,
underneath the commented code, create a string variable named drID to hold
the value of the dr_id column for the row that was selected by the user.
5. Read the value of the dr_id field and store it in the drID variable by using the
Cells collection of the SelectedRow of the doctorsGridView.

Note: You can copy these lines of code from the commented-out lines in the event
procedure.

6. Create a new instance of the DoctorsDataContext class named


doctorsContext.
7. Call the getDrSpecialty method of the doctorsContext object and set the
DataSource property of the specialtiesListBox control to the result of the
method. Pass the drID variable as an argument to the getDrSpecialty method.
8. Set the DataTextField property of the specialtiesListBox control to
"Specialty".
9. Call the DataBind method of the specialtiesListBox control.
10. Add code to make the specialtiesListBox control and specialtiesLabel label
visible if specialties exist in the specialtiesListBox.
Your code should resemble the following example.

[Visual C#]
string drID;
drID = doctorsGridView.SelectedRow.Cells[1].Text;

DoctorsDataContext doctorsContext = new DoctorsDataContext();


specialtiesListBox.DataSource = doctorsContext.getDrSpecialty(drID);
specialtiesListBox.DataTextField = "Specialty";
9-30 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


specialtiesListBox.DataBind();

if (specialtiesListBox.Items.Count != 0)
{
specialtiesListBox.Visible = true;
specialtiesLabel.Visible = true;
}

[Visual Basic]
Dim drID As String
drID = doctorsGridView.SelectedRow.Cells.Item(1).Text

Dim doctorsContext As New DoctorsDataContext


specialtiesListBox.DataSource = doctorsContext.getDrSpecialty(drID)
specialtiesListBox.DataTextField = "Specialty"
specialtiesListBox.DataBind()

If specialtiesListBox.Items.Count <> 0 Then


specialtiesListBox.Visible = True
specialtiesLabel.Visible = True
End If

11. Save the changes to the code-behind file.


12. Build the Benefits Web site.
13. View the doctors.aspx page in the browser.
14. In the browser, select a doctor from the list.
The Specialties list displays the specialties for the selected doctor.
15. Choose a city from the citiesList list, and then select a new doctor.
16. Click Submit.
You are redirected to the medical.aspx page, and the selected doctor’s name
displays in the Primary Care Physician box.

Results: After this exercise, you have called the GetDrSpecialty stored procedure to
display a doctor’s specialties in a list when the user selects a doctor in the
doctorsGridView control. You have accomplished this task by using LINQ to SQL.
Accomplishing Complex Data Access Tasks 9-31

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. What advantages do stored procedures provide?
2. What are the three steps you use to call a stored procedure?
3. What are the four types of stored procedure parameters?
4. What are the parts of a LINQ to SQL query?

Real-world Issues and Scenarios


1. You must access a database. Why must you use stored procedures instead of
accessing the database directly?
2. What types of data can you query with LINQ?
9-32 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Tools

Tool Use for Where to find it


SqlMetal • Generates entity classes Command-line tool,
available for
download.
Reading and Writing XML Data 10-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 10
Reading and Writing XML Data
Contents:
Lesson 1: Overview of XML Architecture in ASP.NET 10-3
Lesson 2: XML and the DataSet Object 10-6
Lesson 3: Managing XML Data 10-12
Lesson 4: Accessing XML Data by Using the XML Web Server Control
10-18
Lab: Reading XML Data 10-21
10-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

Although a lot of data is stored in Microsoft® SQL Server™ databases and managed
by using Microsoft ADO.NET, XML has become a strong standard for storage,
management, and transmission of data.
This module explains how to read, write, and display XML data.
Reading and Writing XML Data 10-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Overview of XML Architecture in ASP.NET

Microsoft ASP.NET provides various types of classes and objects that you can use
to access and synchronize XML data. These classes and objects represent low-level
XML processing components that integrate XML into ASP.NET Web applications.
This lesson explains what an XML document consists of. It also describes XML
core technologies. Finally, it explains the classes and objects that you use to read
and write XML data.
10-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is XML?

Key Points
XML is a universal format that you can use to describe and exchange structured
documents and data on the Internet.
Companies confront many problems when they organize data because they must
fulfill requirements for the content and structure of their data.
XML fulfills all of these requirements; this assists companies in the organization of
data.

Question: How does XML enable you to transfer data across disparate systems?
Reading and Writing XML Data 10-5

MCT USE ONLY. STUDENT USE PROHIBITED


XML Core Technologies

Key Points
XML has initiated other technological innovations and developments that work
with XML to manipulate data.
These technologies enable you to define the structure of XML documents,
transform XML data, reference elements in XML documents, navigate and edit
XML documents, and retrieve and interpret information from XML data sources.

Question: How can you define an XML document as a schema?


10-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
XML and the DataSet Object

XML and DataSet objects share a close connection with each other. DataSet
objects are the basis for disconnected storage and the manipulation of relational
data. DataSet objects are also a container for one or more data tables. XML is the
standard format for data that is present in DataSet objects.
This lesson explains the relationship between XML and DataSet objects, and
demonstrates how to create nested XML data.
Reading and Writing XML Data 10-7

MCT USE ONLY. STUDENT USE PROHIBITED


Why Use XML with DataSets?

Key Points
A DataSet is a relational view of data that can be represented in XML. You can use
DataSets to serialize XML data, for example, to read and write XML data.
XML and XML schemas provide a convenient format that you can use to transfer
the contents of a DataSet to and from remote clients.
You can use different XML objects from the System.XML namespace to
synchronize and transform data that is represented by DataSets.

Question: How can you define the schema of a DataSet?


10-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Overview of XML and DataSets

Key Points
The Microsoft .NET Framework uses the XML format to store and transmit all
types of data.
DataSets can store and transmit data in XML format.

Question: How can you read an XML document or stream it into a DataSet?
Reading and Writing XML Data 10-9

MCT USE ONLY. STUDENT USE PROHIBITED


The XML-Based Methods of the DataSet Object

Key Points
You can create the contents of a DataSet from an XML stream or document.
The .NET Framework provides great flexibility for loading XML data and creating
the schema or relational structure of a DataSet.

Question: How can you obtain the XML representation of the DataSet as a string?
10-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Creating Nested XML Data

Key Points
You can implement the relationship between tables in a DataSet by using a
DataRelation.
In the hierarchical representation of data that XML provides, the parent-child
relationships are represented by parent elements that contain nested child
elements.
You can set the Nested property of a DataRelation to true to create nested XML
data.

Question: What is the default value of the Nested property of a DataRelation?


Reading and Writing XML Data 10-11

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Creating Nested XML

Question: How can you tell that the XML data is nested?
10-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Managing XML Data

The XmlDataDocument class enables you to store, retrieve, and manipulate XML
documents by using a relational DataSet. XmlDataDocument provides a relational
view of the loaded XML document and has a close affiliation with the DataSet
class. Any changes that are made to one object are reflected in the other. Similarly,
to transform the contents of a source XML document into another format such as
XML or HTML, you can use XSL transformations.
This lesson explains how to synchronize a DataSet with an XmlDataDocument. It
also describes how to use XmlDataDocument. Finally, it explains how to
transform XML data by using the XslCompiledTransform object.
Reading and Writing XML Data 10-13

MCT USE ONLY. STUDENT USE PROHIBITED


Overview of Synchronizing a DataSet with an
XmlDataDocument

Key Points
The DataSet object enables real-time, synchronous access to the relational
representations of data.
The XmlDataDocument object enables real-time, synchronous access to the
hierarchical representations of data.
When a DataSet is synchronized with an XmlDataDocument, both objects work
with the same single set of data.

Question: When you make a change to a DataSet, what happens to the


XmlDataDocument if both objects are synchronized?
10-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Synchronizing a DataSet with an XmlDataDocument

Key Points
You can synchronize a DataSet with an XmlDataDocument by storing XML data
in an XmlDataDocument or a DataSet in an XmlDataDocument.

Question: How can you store a DataSet in an XmlDataDocument?


Reading and Writing XML Data 10-15

MCT USE ONLY. STUDENT USE PROHIBITED


Manipulating an XmlDataDocument

Key Points
The XmlDocument implements the Document Object Model (DOM) in XML.
The XmlDataDocument unifies ADO.NET and XML by representing relational
data from a DataSet and synchronizing that data with the XML document model.

Question: How can you extract individual rows as XML from a DataSet?
10-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Transforming XML Data by Using XSLT

Key Points
You can use XSL transformations to transform the content of a source XML
document into another document that is different in format or structure.
In the .NET Framework, the XslCompiledTransform class is the XSLT processor
that transforms one XML document into another.
You can use the Transform method of an XslCompiledTransform object to
transform the data.

Question: Why does the Transform method have several overloads?


Reading and Writing XML Data 10-17

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Transforming Data by Using XSLT

Question: What does the Transform method of the XslCompiledTransform


object perform?
10-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 4
Accessing XML Data by Using the XML Web
Server Control

Information in an XML file is raw; the file contains only the data and no indication
about how to format or display this information. To display XML data in a Web
Forms page, you must provide formatting and display information.
This lesson explains how to display, load, and save XML data.
Reading and Writing XML Data 10-19

MCT USE ONLY. STUDENT USE PROHIBITED


What Is the XML Web Server Control?

Key Points
You can use the XSL Transformation language to specify the tags that display XML
data and provide instructions about how the data from an XML file fits into these
tags.
The output is a new file with the XML information formatted according to the
transformation file.
You can use the XML Web server control to write an XML document or the results
of an XSL Transformation to a Web page.

Question: Where does the XML output of the control appear on the Web page?
10-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Loading and Saving XML Data

Key Points
You can create an Xml control by adding it from the Toolbox to a Web page or
programmatically in code.
You can load XML data into a Web application by providing a path to an external
XML document, loading an XML document as an object, and including the XML
content inline.

Question: How can you transform the XML document before its contents are
written to the output stream?
Reading and Writing XML Data 10-21

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Reading XML Data

Exercise 1: Reading a List of Mutual Funds from an XML File


Scenario
Coho Winery offers several benefits to its employees. In the labs for this course,
you will create a Web site that enables employees to select and set up their chosen
benefits.
One benefit that is offered by Coho Winery is the retirement benefit. When users
apply for the retirement benefit, they can view the prospectuses of several mutual
funds that are offered by Coho Winery. In this lab, you will read mutual fund data
from an XML file and then read, transform, and display a prospectus for a specified
mutual fund.
In this exercise, you will read a list of mutual funds from the mutual_funds.xml file
and store them in a DataSet. You will then display the DataSet in a GridView
control.
The main tasks for this exercise are as follows:
1. Open the Benefits Web site.
10-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


2. Read a list of mutual funds.

f Task 1: Open the Benefits Web site


1. Start Microsoft Visual Studio® 2008.
2. In Visual Studio 2008, open the Benefits Web site from
E:\Labfiles\Starter\CS\Benefits or E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.

f Task 2: Read a list of mutual funds


1. Add the following files from the E:\Labfiles\Starter\CS or
E:\Labfiles\Starter\VB folder to the Web site:
• retirement.aspx
• prospectus.aspx
• mutual_funds.xml
• lgcap.xml
• growth.xml
• midcap.xml
• smcap.xml
• prospectus_style.xsl
2. Open the mutual_funds.xml file and examine its contents.
The fields <name> and <prospectus> are the elements of each fund.
3. Open retirement.aspx in Design view.
A GridView control has already been added to the page. This GridView has
two custom columns: a Name column to display the name of a mutual fund
and a Link to prospectus column that contains a hyperlink to the
prospectus.aspx Web Form. In the following steps, you will fill this GridView
with data from an XML file.
4. In the Page_Load event procedure of retirement.aspx, create a
Page.IsPostBack test.
Reading and Writing XML Data 10-23

MCT USE ONLY. STUDENT USE PROHIBITED


5. If the page is not a postback, fill the DataSet with the data in the XML file and
display the DataSet in the retirementGridView control:
a) Create a DataSet named retirementDataSet.
b) Call the ReadXml method of the DataSet to read the mutual_funds.xml
file.
c) Set the data source of the retirementGridView to retirementDataSet.
d) Call the DataBind method of retirementGridView.
The Server.MapPath method returns the physical file path that corresponds to
the specified virtual path that is on the Web server for the current request.
6. Save your changes.
7. View retirement.aspx in a browser.
The GridView control displays all of the mutual fund names, in addition to
links to the mutual fund prospectuses. Examine the columns in the GridView
control.
Although the links to the prospectuses currently do not work, the links will
open a page called prospectus.aspx and pass to it a prospectus identifer in the
ProspID parameter. You will build the prospectus.aspx page to display the
requested prospectus in Exercise 2.
8. Close the browser.

Results: After this exercise, you have read a list of mutual funds from the
mutual_funds.xml file, stored them in a DataSet, and displayed the DataSet in a
GridView control.

Exercise 2: Reading, Transforming, and Displaying XML


Scenario
In this exercise, you will use the Xml control to read, transform, and display a
prospectus for a specified mutual fund.
The main tasks for this exercise are as follows:
1. Read and display a prospectus.
2. Apply a transformation to the prospectus.
3. Modify the DocumentSource property of the Xml control dynamically.
10-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 1: Read and display a prospectus
1. Open lgcap.xml and examine its contents.
The three fields (elements) of a prospectus are <fundName>,
<fundGeneralDescription>, and <fundDetailedDescription>.
2. Open prospectus_style.xsl and examine its contents.
The prospectus_style.xsl file is an XML style sheet that uses XSLT to display
XML data. The title of the prospectus page is Prospectus and the text General
Description is in the color brown.
3. Open prospectus.aspx in Design view and examine its contents.
This page currently contains the header.ascx user control and a single
hyperlink.
4. Add an Xml control to the Web page between the user control and the
hyperlink.
5. In the Properties window, set the following properties of the Xml control:
• ID: prospectusXml
• DocumentSource: lgcap.xml
6. Save your changes.
7. View prospectus.aspx in a browser.
The Xml control displays the content of the lgcap.xml prospectus as a
continuous, unformatted string of text.
8. Close the browser.

f Task 2: Apply a transformation to the prospectus


1. In the prospectus.aspx Web Form, set the TransformSource property of the
prospectusXml control to prospectus_style.xsl.
2. Save your changes.
3. View prospectus.aspx in a browser.
The content of the lgcap.xml prospectus is now formatted as HTML.
4. Close the browser.
Reading and Writing XML Data 10-25

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 3: Modify the DocumentSource property of the Xml control
dynamically
You will now use a string parameter named ProspID to select which prospectus
will be displayed.
1. In the prospectus.aspx Web Form, clear the DocumentSource property of the
prospectusXml control.
2. In the Page_Load event handler of prospectus.aspx:
a) Read the ProspID parameter from the requested query string and store
the parameter in a variable named prospID.
b) If the prospID variable does not contain an empty string, set the
DocumentSource property of the prospectusXml control to the value of
the variable prospID, concatenated with an .xml extension.
3. Save your changes.
4. View retirement.aspx in a browser.
5. In the browser, click the Prospectus link that is next to Large cap stocks.
The browser displays the prospectus for the Large cap stocks mutual fund.
6. In the browser, click the Back to retirement page link.
7. In the browser, click the other Prospectus links for the Growth stocks, Mid-
cap stocks, and Small-cap stocks.
8. Close the browser.

Results: After this exercise, you have implemented an Xml control to read, transform,
and display a prospectus for a sp mutual fund.

Exercise 3: (If Time Permits): Nested Data


Scenario
In this exercise, you will experiment with the generation of nested XML data from
a SQL Server database.
The main task for this exercise is as follows:
• Generate sequential data.
10-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Generate sequential data
1. Add the nestedData.aspx file from the E:\Labfiles\Starter\CS or
E:\Labfiles\Starter\VB folder to the Web site.
2. Examine the code-behind file for nestedData.aspx.
The code generates a DataSet named doctorsDataSet that contains three
DataTable objects: doctors, drspecialties, and specialties. The code then
creates relationships between the three tables.
The dr_id column links the doctors and drspecialties DataTable objects
together in the myDataRelation1 DataRelation. The doctors DataTable is the
parent DataTable of this relationship.
3. Save your changes.
4. View nestedData.aspx in a browser.
5. In the browser, analyze the XML data.
The data is not nested; it is sequential. First, the doctors are listed, then all of
the drspecialties are listed, and then all of the specialties are listed.
6. Close the browser.
7. In the Page_Load event procedure, locate the following comment.

[Visual C#]
//TODO Lab 12: Create a nested relationship between the doctors and
// drspecialties DataTable objects.

[Visual Basic]
'TODO Lab 12: Create a nested relationship between the doctors and
' drspecialties DataTable objects

8. Uncomment the following line of code to create a nested relationship between


the doctors and drspecialties DataTable objects.

[Visual C#]
//myDataRelation1.Nested = true;

[Visual Basic]
'myDataRelation1.Nested = True

9. On the File menu, click Save All.


Reading and Writing XML Data 10-27

MCT USE ONLY. STUDENT USE PROHIBITED


10. In Solution Explorer, right-click nestedData.aspx, and then click View in
Browser.
11. In the browser, analyze the XML data.

Tip: You may have to refresh the browser after the page loads to see the changes to
the XML data.

In a change from the previous response, the doctors and drspecialties are
nested (for each doctor the drspecialties are listed), and then the specialties
are sequentially placed at the end of the file.
12. Close the browser.
13. Comment out the line of code that you uncommented earlier in this task.
14. In the Page_Load event procedure, locate the following comment.

[Visual C#]
//TODO Lab 12: Create a nested relationship between the specialties
// and drspecialties DataTable objects.

[Visual Basic]
'TODO Lab 12: Create a nested relationship between the specialties
' and drspecialties DataTable objects

15. Uncomment the following line of code to create a nested relationship between
the specialties and drspecialties DataTable objects.

[Visual C#]
//myDataRelation2.Nested = true;

[Visual Basic]
'myDataRelation2.Nested = True

16. On the File menu, click Save All.


17. In Solution Explorer, right-click nestedData.aspx, and then click View in
Browser.
18. In the browser, analyze the XML data.
10-28 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Tip: You may have to refresh the browser after the page loads to see the changes to
the XML data.

In a change from the previous response, at the beginning of the file, all of the
doctors are now listed sequentially, then the specialties and drspecialties are
nested (for every specialty, all of the drspecialties children are listed).

Note: You cannot use the two nested relationships at the same time because the
same DataTable (drspecialties) cannot be a child in two nested relations. For this
reason, you have commented out the nested property setting from the previous
exercise.

19. Close the browser.

Results: After this exercise, you have experimented with nested XML data from a SQL
Server database.
Reading and Writing XML Data 10-29

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. What is the advantage of managing data by using XML?
2. What is the difference between a well-formed XML document and a valid XML
document?
3. What is the importance of XSD?
4. What is the role of the XmlDataDocument class in the XML architecture?

Real-world Issues and Scenarios


1. You want to reference elements in an XML document. What XML technology
must you use?
2. You want to retrieve and interpret XML information. What XML technology
must you use?
3. You want to navigate and edit XML information. What XML technology must
you use?
10-30 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Best Practices related to representing XML in the .NET Framework
Supplement or modify the following best practices for your own work situations:
• If a class has a field or property that is an XML document or fragment, you
must be able to manipulate the property as both a string and as XmlReader.
• Methods that accept or return XML should return XmlReader or
XPathNavigator unless the user is expected to be able to edit the XML data, in
which case you must use XmlDocument.
• If you want to create an XML representation of an object for serialization, and
you need more control over the XML serialization process than XmlSerializer
provides, then you must use XmlWriter.
Creating a Microsoft® ASP.NET AJAX Application 11-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 11
Creating a Microsoft® ASP.NET AJAX
Application
Contents:
Lesson 1: Introduction to ASP.NET AJAX 11-3
Lesson 2: Creating an ASP.NET AJAX Application by Using the ASP.NET AJAX
Extensions 11-7
Lesson 3: Extending an Application by Using the ASP.NET
AJAX Control Toolkit 11-13
Lab: Creating a Microsoft ASP.NET AJAX Application 11-17
11-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

Asynchronous JavaScript and XML (Ajax) is a group of technologies that you can
use to make your Web pages more responsive. Microsoft® ASP.NET AJAX
integrates Ajax features such as partial-page updates and other user interface
elements into ASP.NET Web development.
This module provides an overview of ASP.NET AJAX and then explains how to
create an ASP.NET AJAX application. It also introduces the ASP.NET AJAX Control
Toolkit and explains how to install the Toolkit and add controls from the Toolkit
to an application.
Creating a Microsoft® ASP.NET AJAX Application 11-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Introduction to ASP.NET AJAX

ASP.NET AJAX uses client-script libraries and server components to implement


Ajax features. This lesson introduces the Ajax and ASP.NET AJAX technologies and
describes the architecture of ASP.NET AJAX.
11-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is Asynchronous JavaScript and XML?

Key Points
Ajax uses several technologies, including:
• XMLHttpRequest object.
• HTML, XHTML, and cascading style sheets.
• XML and other data transfer formats such as JavaScript Object Notation
(JSON).
• Document Object Model (DOM).
Creating a Microsoft® ASP.NET AJAX Application 11-5

MCT USE ONLY. STUDENT USE PROHIBITED


What Is ASP.NET AJAX?

Question: What benefits can ASP.NET AJAX provide for your own Web
applications?
11-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Architecture of ASP.NET AJAX

Key Points
The client architecture of ASP.NET AJAX is made up of client-script libraries that
are composed of JavaScript files.
The server architecture of ASP.NET AJAX consists of ASP.NET Web server controls
and components that you use to create the User Interface (UI) and implement the
functionality of an application.
Creating a Microsoft® ASP.NET AJAX Application 11-7

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Creating an ASP.NET AJAX Application by
Using the ASP.NET AJAX Extensions

The ASP.NET 2.0 AJAX Extensions provide server-side controls and functionality
that you use to implement ASP.NET AJAX features in your Web applications. This
lesson describes the Extensions and explains how to use several of the available
ASP.NET AJAX server controls.
11-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Are the ASP.NET AJAX Extensions?

Key Points
The ASP.NET 2.0 AJAX Extensions is included with Microsoft Visual Studio®
2008 and is available as a separate download for Visual Studio 2005.
The features of the ASP.NET AJAX Extensions are implemented in several
namespaces, including System.Web.Configuration and System.Web.UI.
Creating a Microsoft® ASP.NET AJAX Application 11-9

MCT USE ONLY. STUDENT USE PROHIBITED


ASP.NET AJAX Server Controls

Key Points
You must add a ScriptManager control to a Web page before you can use the
UpdatePanel, UpdateProgress, and Timer controls.

Question: How can you use the ASP.NET AJAX server controls to enhance your
own Web applications?
11-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Implementing the UpdatePanel Control

In this demonstration, you will see how to implement an UpdatePanel control in a


Web application.
Creating a Microsoft® ASP.NET AJAX Application 11-11

MCT USE ONLY. STUDENT USE PROHIBITED


Managing Partial-Page Updates

Key Points
When you implement partial-page rendering on a Web page, an instance of the
PageRequestManager class becomes available to the page.
You use JavaScript in your Web page to handle the events raised by the
PageRequestManager class. Get a reference to the current instance of the
PageRequestManager class by calling the getInstance method and then create a
function to handle the required event.

Question: What are some scenarios when you may want to handle the events of
the PageRequestManager class?
11-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Converting an ASP.NET Application to ASP.NET AJAX

Key Points
New Web sites that you create by using Visual Studio 2008 are automatically
enabled for ASP.NET AJAX.
To convert an existing Web site to use ASP.NET AJAX, you must configure the
web.config file of the application.
Creating a Microsoft® ASP.NET AJAX Application 11-13

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Extending an Application by Using the ASP.NET
AJAX Control Toolkit

The AJAX Control Toolkit provides more than 30 different controls and extenders
that you can use to enhance your Web applications. This lesson describes how to
download, install, and use the Toolkit.
11-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Overview of the ASP.NET AJAX Control Toolkit

Key Points
The Toolkit contains several folders of content, including the following:
• AjaxControlToolkit folder. This folder contains source code for the controls
that the Toolkit provides.
• SampleWebsite folder. This folder contains demonstrations of the controls.
• ToolkitTests folder. This folder contains automated tests for all controls.
• AjaxControlExtender folder. This folder contains an installer file for templates
to create new extender controls.

Question: What advantages does the AJAX Control Toolkit provide?


Creating a Microsoft® ASP.NET AJAX Application 11-15

MCT USE ONLY. STUDENT USE PROHIBITED


Accessing the ASP.NET AJAX Control Toolkit

Key Points
You can download the Control Toolkit from the following location:
http://go.microsoft.com/fwlink/?LinkId=110718
The most recent version of the Toolkit targets the official release of the Microsoft
.NET Framework 3.5 and Visual Studio 2008.
11-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Implementing an ASP.NET AJAX Extender
Control

In this demonstration, you will see how to implement a ConfirmButtonExtender


control in an ASP.NET Web application.
Creating a Microsoft® ASP.NET AJAX Application 11-17

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Creating a Microsoft ASP.NET AJAX
Application

Exercise 1: Implementing Partial-Page Rendering by Using


the UpdatePanel Control
Scenario
The doctors.aspx page on the Coho Winery Web site enables users to view the list
of specialties of a selected doctor. In this lab, you will use the ASP.NET AJAX
Extensions to implement partial-page rendering when the user selects a different
doctor or moves to a new page in the list of doctors. You will also install the
controls from the AJAX Control Toolkit and use the CalendarExtender control to
enhance the nameDate user control.
In this exercise, you will implement partial-page rendering.
The main tasks for this exercise are as follows:
1. Open the Benefits Web site.
2. Examine the doctors.aspx Web page.
11-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


3. Implement partial-page rendering for the GridView and ListBox controls.

f Task 1: Open the Benefits Web site


1. Open Visual Studio 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.

f Task 2: Examine the doctors.aspx Web page


1. View the doctors.aspx page in the browser.
2. In the doctorsGridView control, select page 2.
Note that this action forces a page refresh.
3. In the doctorsGridView control, select a doctor.
View the specialties of the selected doctor in the list on the page.
4. In the doctorsGridView control, select another doctor.
Note that each refresh of the list forces a page refresh.
5. Close the browser window.

f Task 3: Implement partial-page rendering for the GridView and


ListBox controls
1. Open the doctors.aspx page in Design view.
2. In the Toolbox, expand the AJAX Extensions tab.
3. In the AJAX Extensions tab, drag a ScriptManager component onto the
doctors.aspx page. Place the component above the Specialties label.
4. Name the ScriptManager component doctorsScriptManager.
5. In the AJAX Extensions tab, drag an UpdatePanel control onto the
doctors.aspx page. Place the control directly underneath the Specialties list.
6. Name the UpdatePanel control specialtiesUpdatePanel.
Creating a Microsoft® ASP.NET AJAX Application 11-19

MCT USE ONLY. STUDENT USE PROHIBITED


7. On the doctors.aspx page, drag the Specialties list and drop it inside the
specialtiesUpdatePanel control.
8. In the AJAX Extensions tab, drag an UpdatePanel control onto the
doctors.aspx page. Place the control directly underneath the Doctors label.
9. Name the UpdatePanel control doctorsUpdatePanel.
10. On the doctors.aspx page, drag the doctorsGridView grid view and drop it
inside the doctorsUpdatePanel control.
11. Save the doctors.aspx page.
The doctors.aspx page should resemble the following illustration.

12. View the doctors.aspx page in the browser.


13. In the doctorsGridView control, select page 2.
Note that this action no longer forces a page refresh.
11-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


14. In the doctorsGridView control, select a doctor, and then in the list on the
page, view the specialties of the selected doctor.
15. In the doctorsGridView control, select another doctor.
Note that each refresh of the list no longer forces a page refresh.
16. Close the browser window.

Results: After this exercise, you have implemented partial-page rendering in the
doctors.aspx page.

Exercise 2: Installing and Implementing the AJAX Control


Toolkit
In this exercise, you will install the controls from the AJAX Control Toolkit and use
the CalendarExtender control to enhance the nameDate user control.
The main tasks for this exercise are as follows:
1. Add the AJAX Control Toolkit controls to the Toolbox.
2. Add the CalendarExtender to the nameDate.ascx user control.
3. Change the initial display mode of the CalendarExtender.

Note: This exercise requires the AjaxControlToolkit.dll file that targets the official release
of .NET Framework 3.5 and Visual Studio 2008. Download the latest version of the
AjaxControlToolkit.dll file from the www.codeplex.com Web site and copy it to the
E:\Labfiles\Starter\ folder in the virtual machine. Ask the instructor for assistance if
required.

f Task 1: Add the AJAX Control Toolkit controls to the Toolbox


1. In Visual Studio 2008, add a new tab named AJAX Control Toolkit to the
Toolbox.
2. In the AJAX Control Toolkit tab, right-click the Toolbox, and then click
Choose Items.
3. In the Choose Toolbox Items dialog box, click Browse.
4. Browse to E:\Labfiles\Starter\.
5. In the Starter folder, click AJAXControlToolkit.dll, and then click Open.
6. In the Choose Toolbox Items dialog box, click OK.
Creating a Microsoft® ASP.NET AJAX Application 11-21

MCT USE ONLY. STUDENT USE PROHIBITED


In the Toolbox, examine the new controls that have been added to the AJAX
Control Toolkit tab.

f Task 2: Add the CalendarExtender to the nameDate.ascx user control


1. View the nameDate.ascx user control in Design view.
2. In the Toolbox, expand the AJAX Extensions tab.
3. Drag a ScriptManager component onto the nameDate.ascx user control and
drop it onto the bottom left cell of the table.
4. In the Toolbox, expand the AJAX Control Toolkit tab.
5. Drag a CalendarExtender control onto the nameDate.ascx user control and
drop it onto the birthTextBox control.
6. In the Properties window, in the list of controls at the top of the window select
the birthTextBox_CalendarExtender control.
7. In the Properties window, set the format of the
birthTextBox_CalendarExtender control to MM/dd/yy.
8. Save the nameDate.ascx user control.
9. Build the Benefits Web site.
10. View the medical.aspx page in Design view.
The medical.aspx page uses the nameDate.ascx user control. The
ScriptManager component and birthTextBox_CalendarExtender control
appear in the user control on the medical.aspx page.
11. View the medical.aspx page in the browser.
12. In the medical.aspx page, click the Birth Date box.
The calendar extender appears.
13. In the calendar, click the label at the top of the calendar, which displays the
current month and year.
The calendar display mode changes to display the months of the current year.
14. In the calendar, click the header again.
The calendar display mode changes to years.
15. Select a year, month, and date in the calendar control.
Verify that the date displays in the format MM/dd/yy.
11-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


16. Close the browser window.

f Task 3: Change the initial display mode of the CalendarExtender


1. View the nameDate.ascx user control in Design view.
2. In the Properties window, in the list of controls at the top of the window select
the birthTextBox_CalendarExtender control
3. In the Properties window, in the birthTextBox_CalendarExtender control, set
the OnClientShown event procedure to the value dobCalendarShown.
4. View the nameDate.ascx user control in Source view.
5. Locate the markup for the CalendarExtender control.
6. Underneath the closing tag for the CalendarExtender control, add the
following JavaScript code to change the initial display of the calendar.

<script type="text/javascript" language="javascript">


function dobCalendarShown(sender,args)
{
sender._switchMode("years", true);
}
</script>

7. Save the nameDate.ascx user control.


8. Build the Benefits Web site.
9. View the medical.aspx page in the browser.
10. On the medical.aspx page, click the Birth Date box.
The calendar extender appears with years as the initial display mode.
11. Select a year, month, and date in the calendar.
12. Close the browser window.

Results: After this exercise, you have installed the controls from the AJAX Control
Toolkit and used the CalendarExtender control to enhance the nameDate user
control.
Creating a Microsoft® ASP.NET AJAX Application 11-23

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. What is the design goal of the AJAX group of technologies?
2. What features does the ScriptManager control provide?
3. How can you use the AJAX Control Toolkit to enhance your applications?

Real-world Issues and Scenarios


1. What must you do to convert an existing Web site to use ASP.NET AJAX?
2. You have downloaded the AJAX Control Toolkit. What must you do before
you can use the AJAX Control Toolkit?
11-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Tools

Tool Use for Where to find it


AJAX Control Toolkit • Built on the ASP.NET AJAX Available for
Extensions and contains a download.
collection of Web-client
components that you can use
to enhance your Web
applications.
Delivering Dynamic Content with Microsoft Silverlight 12-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 12
Delivering Dynamic Content with Microsoft
Silverlight
Contents:
Lesson 1: Overview of Microsoft Silverlight 12-3
Lesson 2: Creating Silverlight-Based Applications with Visual Studio 2008
12-8
Lab: Delivering Dynamic Content with Microsoft Silverlight 12-14
12-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

The Microsoft® Silverlight™ browser plug-in is a powerful platform that enables


you to create rich and engaging user experiences on the Web. Silverlight provides
an increasingly robust platform that has many intuitive features. Silverlight
harnesses the power of Extensible Application Markup Language (XAML) so that
you can create an attractive presentation layer for your applications. In Microsoft
Visual Studio® 2008, you can create Silverlight applications by using managed
code and Microsoft JScript®.
This module provides an overview of Silverlight and describes how to create
Silverlight-based applications by using Visual Studio.
Delivering Dynamic Content with Microsoft Silverlight 12-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Overview of Microsoft Silverlight

Silverlight is a cross-browser, cross-platform plug-in that you can use to deliver


media experiences and rich interactive applications on the Internet by using
XAML. Silverlight also offers powerful functionality that improve the productivity
of both designers and developers.
This lesson introduces the features of Silverlight, explains the component
architecture of Silverlight, and describes the main tools that you can use to develop
Silverlight content.
12-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Key Features of Microsoft Silverlight

Key Points
Silverlight offers numerous features that you can use to create truly immersive
experiences.
You can publish media content that operates on different platforms and create
video applications that have similar functionality to DVD players.
Silverlight includes Windows Presentation Foundation (WPF) technology that
enables you to create rich client features that are not available with HTML alone.
You can use XAML to create WPF elements.
Silverlight extends JScript to provide powerful control over browser user interfaces
(UIs).

Question: Have you used Silverlight before or seen its capabilities?


Delivering Dynamic Content with Microsoft Silverlight 12-5

MCT USE ONLY. STUDENT USE PROHIBITED


Tools for Designing and Developing Silverlight Applications

Key Points
You can use the professional design tools in Microsoft Expression Studio to create
rich content and the development environment of Visual Studio to generate
interactive functionality.
By using these tools, designers and developers can collaborate more effectively to
deliver Web solutions.

Question: What are the similarities and differences between Expression Studio
and Visual Studio?
12-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Architecture of Silverlight

Key Points
Silverlight is a browser plug-in for constructing graphics, animations, and timelines
by using XAML. You can then attach the XAML to JScript code to implement
functionality.
Silverlight contains the codecs to play VC-1, Windows Media Video (WMV),
Windows Media Audio (WMA), and MP3 multimedia content.
A Silverlight application first invokes the Silverlight control from the HTML page,
which then loads a XAML file. The plug-in provides mechanisms at run time to
change the XAML content, retrieve objects by using JScript, and stream multimedia
content.

Question: How does AJAX relate to Silverlight?


Delivering Dynamic Content with Microsoft Silverlight 12-7

MCT USE ONLY. STUDENT USE PROHIBITED


XAML and Microsoft Silverlight

Key Points
XAML is a declarative markup language that you can use to define all aspects of the
UI for your Silverlight application. XAML is much richer than HTML; it enables
you to incorporate vector images, video, and much more.
A XAML file typically contains a Canvas root element that you can use to contain
objects and tags to define objects.

Question: How does Silverlight relate to XAML?


12-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Creating Silverlight-Based Applications with
Visual Studio 2008

Visual Studio 2008 enables you to create Silverlight 1.1 applications by using
managed code and JScript. When you create a Silverlight application, Visual Studio
creates a solution with a framework for the application.
This lesson explains how to create a Silverlight application in Visual Studio and
describes the content files in a Silverlight application. It also explains how to create
XAML objects and handle events in the code-behind file.
Delivering Dynamic Content with Microsoft Silverlight 12-9

MCT USE ONLY. STUDENT USE PROHIBITED


Creating a Silverlight Application

Key Points
Visual Studio 2008 provides templates that you can use to create Silverlight
applications and class libraries.

Question: What types of files can you add to a Silverlight application?


12-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Content of a Silverlight Application

Key Points
When you create a Silverlight project in Visual Studio, the solution contains:
• A Page.xaml file for the UI with an associated source code file in Microsoft
Visual C#® or Microsoft Visual Basic®.
• A Silverlight.js file to create a Silverlight control in the Web page.
• A TestPage.html default file with an associated JScript file.

Question: What do the JScript and XAML files contain?


Delivering Dynamic Content with Microsoft Silverlight 12-11

MCT USE ONLY. STUDENT USE PROHIBITED


Implementing XAML Objects

Key Points
You can define numerous objects in XAML. Each XAML object has a specific use.
XAML tags are similar to XML and HTML tags.
You can use a Canvas object as a drawing surface to contain other objects or
embedded drawing surfaces.

Question: Can you nest Canvas objects to create a hierarchy of XAML objects?
12-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Handling Events

Key Points
In Visual Studio, you can add event handling code to a Silverlight application by
implementing the event handlers in the associated source code file for the XAML
page. You can reference the event handler in the XAML page or in the associated
source code file.

Question: How is event handling in Visual C# different from event handling in


Visual Basic for a Silverlight application?
Delivering Dynamic Content with Microsoft Silverlight 12-13

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Displaying Video Files in a Silverlight
Application

Question: How can you extend the application in this demonstration?


12-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Delivering Dynamic Content with
Microsoft Silverlight

Exercise 1: Creating a Microsoft Silverlight-Based


Application
Scenario
Coho Winery wants to upgrade its existing Benefits Web site to use richer and
more dynamic content. In this lab, you will investigate the features of Microsoft
Silverlight and create a simple version of the Benefits Web site. The new Web site
will contain a default page that loads an associated picture and dynamic text that
explains each benefit when the user selects the benefit.
In this exercise, you will create a Silverlight project in Visual Studio and add some
XAML objects to Page.xaml to create a simple banner for the Web site.
The main tasks for this exercise are as follows:
1. Create a Silverlight project in Visual Studio.
2. Add XAML objects to Page.xaml to create a simple banner.
Delivering Dynamic Content with Microsoft Silverlight 12-15

MCT USE ONLY. STUDENT USE PROHIBITED


3. Build and view the page.

f Task 1: Create a Silverlight project in Visual Studio


1. Click Start, point to All Programs, expand the Microsoft Visual Studio 2008
folder, and then click Microsoft Visual Studio 2008.
2. On the File menu, point to New, and then click Project.
3. In the New Project dialog box:
a) In the Project types pane, expand Visual C# or Visual Basic, and then
click Silverlight.
b) In the Templates pane, click Silverlight Project.
c) In the Name box, type Benefits
d) In the Location box, type E:\Labfiles\Starter and then click OK.
This creates a Silverlight project that includes a default HTML file, a JScript file,
a XAML file, and an initial Visual C# or Visual Basic source code file.

f Task 2: Add XAML objects to Page.xaml to create a simple banner


1. In Solution Explorer, double-click Page.xaml.
2. Add a Rectangle object to the Canvas, and then set the properties as follows.

Attribute Value
x:Name myRectangle

Height 100

Width 600

Fill Black

3. Add two Ellipse objects to the Canvas, and then set the properties as follows.

Attribute Value of object 1 Value of object 2

x:Name myEllipse myCircle

Height 70 60
12-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Attribute Value of object 1 Value of object 2

Width 100 60

Fill Green White

Canvas.Left 20 40

Canvas.Top 15 20

4. Add two TextBlock objects to the Canvas, and then set the properties as
follows.

Attribute Value of object 1 Value of object 2

x:Name letterTextBlock titleTextBlock

Text B Benefits Selection Page

Foreground Blue White

FontFamily Arial Arial

FontSize 50 30

Canvas.Left 55 150

Canvas.Top 20 30

FontWeight Bold Do not set

f Task 3: Build and view the page


1. On the Build menu, click Build Solution.
2. In Solution Explorer, right-click TestPage.html, and then click View in
Browser.
3. In the browser, view the banner that you created.
4. Close Microsoft Internet Explorer®.

Results: After this exercise, you have created a Silverlight application that displays a
banner for the Benefits Web site.
Delivering Dynamic Content with Microsoft Silverlight 12-17

MCT USE ONLY. STUDENT USE PROHIBITED


Exercise 2: Adding Dynamic Content to a Microsoft
Silverlight Application
Scenario
In this exercise, you will add code created in Expression Blend to Page.xaml. This
code creates the XAML objects for a simple version of the Benefits Web site and
provides storyboard animations for object fading. After you have added the XAML
code, you will provide event handling code for XAML objects in the managed code-
behind file.
The main tasks for this exercise are as follows:
1. Add XAML code to create the Benefits Web site.
2. Add images to the project and create variables.
3. Create an event handler for when the user clicks a button.
4. Create an event handler for when the pointer enters a button.
5. Create an event handler for when the pointer leaves a button.
6. Create an event handler for page fading.
7. Add the event handlers and set the active button.
8. Build and view the page.

f Task 1: Add XAML code to create the Benefits Web site


1. Open the ObjectCode.txt file in the E:\Labfiles\Starter folder.
2. Copy all the code in the ObjectCode.txt file to the clipboard.
3. In Visual Studio, in Page.xaml, delete the code that you added in the previous
exercise, and then paste the code from the text file.
This code creates XAML objects for a simple version of the Benefits Web site
and provides storyboard animations for the objects.
4. Examine the code in Page.xaml.
The <Canvas.Resources> element contains <Storyboard> elements for object
animation. There are <Storyboard> elements for page fading and for when the
pointer enters, leaves, or clicks one of the four buttons. The code also contains
XAML objects for the background, four buttons, and four pages.
5. Open TestPage.html and set the width of the host window to 800 pixels.
12-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 2: Add images to the project and create variables
1. Add the images from the E:\Labfiles\Starter folder to the Benefits project.
There are five images in this folder. Four images display a different benefit type
and the other image displays a banner for the Web site.
2. Open Page.xaml, and then in the Page class, create the following objects:
• A string named activeButton that contains the name of the currently
selected button.
• An integer named currentPage that contains the current page number. Set
this integer to 1.
• An integer named nextPage that contains the current page number. Set
this integer to 0.

f Task 3: Create an event handler for when the user clicks a button
1. In the Page class, create an event handler named OnMouseDown that accepts
the event type MouseEventArgs.
2. If the user clicked a button other than the active button, perform the following:
a) Call the Begin method of the buttonName_Click storyboard where the
name of the button is the button selected.
b) Call the Begin method of the buttonName_Leave storyboard where the
name of the button is the previously selected button.
c) Check the name of the selected button, and then set the nextPage integer
accordingly, for example, 1 for Button1 and 2 for Button2.
d) Set the activeButton string to the name of the selected button.
e) Call the Begin method of the Page_Out storyboard.
To find the name of the clicked button, you can use (sender as
Canvas).Name (Visual C#) or TryCast(sender, Canvas).Name (Visual Basic).
You can use the FindName method to concatenate the name of the selected
button with the string _Click or _Leave to call the Begin method of the
storyboards. For example, the following code inside an event procedure calls
the Begin method of the clicked button.

[Visual C#]
void OnMouseDown(object sender, MouseEventArgs e)
{
Delivering Dynamic Content with Microsoft Silverlight 12-19

MCT USE ONLY. STUDENT USE PROHIBITED


(this.FindName((sender as Canvas).Name + "_Click") as
Storyboard).Begin();
}

[Visual Basic]
Private Sub OnMouseDown(ByVal sender As Object, _
ByVal e As MouseEventArgs)
TryCast(Me.FindName(TryCast(sender, Canvas).Name + "_Click"), _
Storyboard).Begin()
End Sub

f Task 4: Create an event handler for when the pointer enters a button
1. In the Page class, create an event handler named OnMouseEnter that accepts
the event type MouseEventArgs.
2. If the user clicked a button other than the active button, call the Begin method
of the buttonName_Enter storyboard where the name of the button is the
button selected.

f Task 5: Create an event handler for when the pointer leaves a button
1. In the Page class, create an event handler named OnMouseLeave that accepts
the event type EventArgs.
2. If the user clicked a button other than the active button, call the Begin method
of the buttonName_Leave storyboard where the name of the button is the
button selected.

f Task 6: Create an event handler for page fading


1. In the Page class, create an event handler named OnFadeOut that accepts the
event type EventArgs.
2. In the event handler, perform the following:
a) Concatenate the string Page with the nextPage integer, and then use this
string to set the Visibility property of the next page to Visibility.Visible.
b) Concatenate the string Page with the currentPage integer, and then use
this string to set the Visibility property of the current page to
Visibility.Collapsed.
12-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


c) Call the Begin method of the Page_In storyboard.
d) Set the currentPage integer to the nextPage integer.

f Task 7: Add the event handlers and set the active button
1. In the Page_Loaded event handler, add a For loop that adds the event
handlers in the following table. Add the event handlers for the objects
Button1, Button2, Button3, and Button4.

Event Method name

ButtonX.MouseLeftButtonDown OnMouseDown

ButtonX.MouseEnter OnMouseEnter

ButtonX.MouseLeave OnMouseLeave

You can use the FindName method to concatenate the string Button and the
loop counter with a base index of 1. For example, the following code adds four
event handlers for the MouseEnter event.

[Visual C#]
for (int i = 1; i < 5; i++)
{
(this.FindName("Button" + i) as Canvas).MouseEnter +=
new MouseEventHandler(OnMouseEnter);
}

[Visual Basic]
For i As Integer = 1 To 4
AddHandler TryCast(Me.FindName("Button" & i), _
Canvas).MouseEnter, AddressOf OnMouseEnter
Next

2. Add the OnFadeOut event handler to Page_Out.Completed.


3. Call the Begin method of the Button1_Click storyboard.
4. Set the activeButton string to Button1.
When you initially open the page, the first benefit is selected.
Delivering Dynamic Content with Microsoft Silverlight 12-21

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 8: Build and view the page
1. On the Build menu, click Build Solution.
2. In Solution Explorer, right-click TestPage.html, and then click View in
Browser.
3. In the browser, click the buttons in the left pane to display a related picture
and text.
4. Close Internet Explorer.

Results: After this exercise, you have added XAML code and images to display the
front page of the Web site and event handling code to display an associated picture
and text when the user selects a benefit.
12-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. Why is Silverlight so powerful?
2. What is XAML?
3. How easy is it to incorporate video capability into a Silverlight application?
4. How can you create managed event handlers for XAML objects?

Real-world Issues and Scenarios


1. The Media department have created a Silverlight 1.0 application. How can you
update it to a managed Silverlight 1.1 application?
2. You want to display videos in your application, but the videos are in a number
of different common formats. Is this an issue?
Delivering Dynamic Content with Microsoft Silverlight 12-23

MCT USE ONLY. STUDENT USE PROHIBITED


Tools

Tool Use for


Visual Studio 2008 • Includes templates to create Silverlight applications.
Microsoft Expression • Enables you to create engaging UI experiences.
Blend

Microsoft Expression • Enables you to create compelling, vector-based graphic


Design elements.

Microsoft Expression • Enables you to organize images and digital assets with
Media effortless retrieval.

Expression Encoder, a • Enables you to create rich, enhanced, encoded video and
feature of Expression audio content.
Media

Microsoft Expression • Enables you to create standards-based Web sites.


Web
Consuming and Creating XML Web Services 13-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 13
Consuming and Creating XML Web Services
Contents:
Lesson 1: Overview of XML Web Services 13-3
Lesson 2: Calling an XML Web Service 13-8
Lesson 3: Creating an XML Web Service 13-14
Lab: Consuming and Creating XML Web Services 13-17
13-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

The Internet enables better communication in and between companies by


providing fast access to information. However, for many companies, browsing
data-driven pages does not adequately satisfy their business requirements.
Programmable Web sites that directly link organizations, applications, and services
are a better solution. The XML Web service provides this direct linking of
applications. By using XML Web services, you can expand the functionality that
your Web site offers to users.
This module describes how to call an XML Web service directly by using a browser
and by proxy from a Web Form. It also explains how to create and publish XML
Web services by using Microsoft® Visual Studio® 2008.
Consuming and Creating XML Web Services 13-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Overview of XML Web Services

One of the challenges that you may encounter when you create feature-rich Web
sites is application integration. You often have to combine several applications into
a single, easy-to-use solution. The problem with this is that the applications that
you want to combine may be on a variety of platforms, and each platform may run
a different operating system. The applications may also use several different
programming languages.
XML Web services provide a simple, flexible, standards-based model that you can
use to connect applications together over the Internet. XML Web services enable
you to take advantage of the existing Internet infrastructure and link applications
regardless of which platforms, programming languages, or object models that they
use.
This lesson describes XML Web services and explains the process that you use to
call an XML Web service from a Web Form.
13-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is an XML Web Service?

Key Points
• XML Web services do not have a user interface (UI).
• XML Web services communicate by using standard Web protocols and data
formats such as HTTP, XML, and Simple Object Access Protocol (SOAP).
• The XML Web services model assumes a stateless service architecture; such
architectures are generally more scalable than statefull architectures.
Consuming and Creating XML Web Services 13-5

MCT USE ONLY. STUDENT USE PROHIBITED


Why Use XML Web Services?

Key Points
XML Web services enable you to share programming logic and capabilities with
many other applications.
Visual Studio 2008 provides applications that make XML Web services extremely
easy to develop and to consume.

Question: What are some functions for XML Web services in your own
applications?
13-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Finding an XML Web Service

Key Points
You can find existing XML Web services to add to your Web site by using one or
more of a series of discovery services, as follows:
• Universal Description, Discovery, and Integration (UDDI) Web site.
• Discovery file (DISCO) documents.
• .disco
• .vsdisco
• Web Services Description Language (WSDL) files.
Consuming and Creating XML Web Services 13-7

MCT USE ONLY. STUDENT USE PROHIBITED


Multimedia: XML Web Service Execution Model

Key Points
In this animation, you will see how XML Web services interact with browsers and
other Web Forms.
13-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Calling an XML Web Service

You can access an XML Web service directly from a browser by using HTTP, which
is a process called direct access. Direct access enables you to view the methods,
properties, and output of an XML Web service. You can also call an XML Web
service from a Web Form programmatically. To accomplish this, you must create a
proxy to handle the call.
This lesson describes how to access an XML Web service directly from a browser.
It also explains how to create a Web reference proxy for an XML Web service
method and call the Web method from a Web Form.
Consuming and Creating XML Web Services 13-9

MCT USE ONLY. STUDENT USE PROHIBITED


Calling an XML Web Service by Using HTTP

Key Points
When you access an XML Web service directly with a browser, you first access the
HTML description page.
The description page provides information about what an XML Web service does,
the available Web methods that it contains, the Web method parameters, and the
Web service responses.
You can click a Web method to view the available parameters for that Web method
and to test the method.

Question: Why may you want to access a Web service by using HTTP?
13-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is a Proxy?

Key Points
To call an XML Web service, you create a Web reference to the XML Web service.
The members in the generated proxy include:
• WebMethodName for synchronous communication.
• BeginWebMethodName to start asynchronous communication.
• EndWebMethodName to finish asynchronous communication.
• WebMethodNameAsync to implement the event-driven asynchronous
programming model.

Question: What is the purpose of the proxy class that is created when you create a
Web reference to an XML Web service?
Consuming and Creating XML Web Services 13-11

MCT USE ONLY. STUDENT USE PROHIBITED


Steps for Calling an XML Web Service

Key Points
To use an XML Web service from a Web Form, you must first identify the XML
Web service URL and then create a Web reference. You can use the Add Web
Reference option in Visual Studio 2008 to locate the Web Service and create the
reference.
13-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


XML Web Service Error Handling

Key Points
The three major sources of error when you use an XML Web service are:
• Unavailable service.
• Long response delays.
• Errors that are internal to the XML Web service.

Question: Discuss some occurrences that may cause an error when you access an
XML Web service.
Consuming and Creating XML Web Services 13-13

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Testing the Availability of an XML Web
Service

In this demonstration, the instructor will show you how to test if the XML Web
service is available.
13-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Creating an XML Web Service

Visual Studio 2008 provides templates that make it easy for you to develop XML
Web services. This lesson describes how to use these templates to create an XML
Web service.
Consuming and Creating XML Web Services 13-15

MCT USE ONLY. STUDENT USE PROHIBITED


Steps to Create an XML Web Service

Key Points
When you create a new Web service application, Visual Studio 2008 automatically
creates the required folders, files, and the XML Web service page. Visual Studio
2008 also creates a default Hello World function on the XML Web service page.
To test your Web service, right-click the XML Web service in Solution Explorer,
and then click View in Browser.
13-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


XML Web Service Code

Key Points
Web services consist of two primary files. The .asmx file identifies the Web page as
an XML Web service, and the code file contains the XML Web service logic.
Consuming and Creating XML Web Services 13-17

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Consuming and Creating XML Web
Services

Exercise 1: Creating the Dentist XML Web Service and the


GetAllDentists XML Web Service Method
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course,
you will create a Web site that enables employees to select and set up their chosen
benefits.
In this lab, you will create an XML Web service that retrieves data from the
Microsoft SQL Server™ dentists database. The Web service will contain two Web
methods: one that retrieves all of the dentists from the dentists table and one that
uses a stored procedure to retrieve the dentists for a specific postal code. You will
then call the stored procedures from a Web Form.
In this exercise, you will use Visual Studio 2008 to create an XML Web service.
The main tasks for this exercise are as follows:
13-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


1. Open the Benefits Web site.
2. Create the DentalService XML Web service.
3. Create the GetAllDentists XML Web service method.
4. Modify the output of the XML Web service.

f Task 1: Open the Benefits Web site


1. Open Visual Studio 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.

f Task 2: Create the DentalService XML Web service


1. In Solution Explorer, at the top of the window, right-click Solution 'Benefits',
point to Add, and then click New Project.
2. In the Add New Project dialog box, click Visual C# or Visual Basic, and then
click ASP.NET Web Service Application.
3. In the Name box, type DentalService
4. In the Location box, type E:\Labfiles\Starter\CS or E:\Labfiles\Starter\VB
and then click OK.
5. In Solution Explorer, right-click Service1.asmx, and then rename it to
DentalService1.asmx.
6. If necessary, open the DentalService1.asmx file in Code view.
7. In the DentalService1.asmx.cs or DentalService1.asmx.vb file, change the name
of the class from Service1 to DentalService1.
8. View the markup of the DentalService1.asmx file.
9. In the @ WebService directive, change the class attribute to
DentalService.DentalService1.

f Task 3: Create the GetAllDentists XML Web service method


1. Open the code-behind page of the DentalService1.asmx page.
Consuming and Creating XML Web Services 13-19

MCT USE ONLY. STUDENT USE PROHIBITED


2. In the code window, add a using (Microsoft Visual C#®) or Imports
(Microsoft Visual Basic®) statement for the System.Data.SqlClient
namespace.
3. In the DentalService1 class, delete the HelloWorld Web service method.
4. In the DentalService1 class, create three object variables at the class level with
the following settings.

Object name Object type

dentistsConnection SqlConnection

dentistsDataSet DataSet

dentistsSqlDataAdapter SqlDataAdapter

5. In the DentalService1 class, create an XML Web service method named


GetAllDentists that returns a DataSet object.
6. In the GetAllDentists method, declare a string variable named dentistsString.
7. Set the initial value of the dentistsString variable to the string Select * from
Dentists.
8. Set the ConnectionString property of the dentistsConnection object to a
string that contains the following settings:
• Data Source: LONDON\\SQLExpress (Visual C#)
LONDON\SQLExpress (Visual Basic)
• Initial Catalog: dentists
• Integrated Security: True
9. Initialize the dentistsSQLDataAdapter object, and pass the dentistsString
and dentistsConnection variables as arguments to the DataAdapter object.
10. Call the Fill method of the dentistsSqlDataAdapter object to fill the
dentistsDataSet.
11. Return the dentistsDataSet as the result of the Web service method.
12. Save your changes.
13. View the DentalService1.asmx page in the browser.
The description page of the XML Web service is displayed.
13-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Note: There is a warning message at the bottom of the page about the use of
tempuri.org. The warning is here because this temporary URL is the temporary
namespace of the XML Web service and it is used for testing purposes only.

14. In the browser, click the GetAllDentists link, and then click Invoke.
The browser displays the XML response from the XML Web service.
15. Close the browser window.

f Task 4: Modify the output of the XML Web service


1. In the DentalService1.asmx code-behind page, set the attributes of the Web
service according to the following table.

Attribute Value

Namespace http://microsoft.com/webservices/

Description This XML Web service contains information about the dentists

2. Add a Description attribute to the GetAllDentists XML Web service method


and set it to This XML Web service method returns all the dentists.
Your code should resemble the following example.

[Visual C#]
[WebMethod(Description= "This XML Web service "
+ "method returns all the dentists")]
public DataSet GetAllDentists()
{

[Visual Basic]
<WebMethod(Description:="This XML Web service " _
& "method returns all the dentists")> _
Public Function GetAllDentists() As DataSet

3. Save your changes.


4. View the DentalService1.asmx page in the browser.
The description page of the XML Web service is displayed.
Consuming and Creating XML Web Services 13-21

MCT USE ONLY. STUDENT USE PROHIBITED


5. In the browser, notice that the description of the XML Web service and the
description of the XML Web service method have changed. In addition, notice
that the warning message at the bottom of the page about the use of
tempuri.org no longer appears because you have changed the namespace of
the service.
6. Close the browser window.

Results: After this exercise, you have created and tested the GetAllDentists Web
service method.

Exercise 2: Creating the GetDentistsByPostalCode XML Web


Service Method
In this exercise, you will add another XML Web service method to your
DentistService XML Web service. The new XML Web service method is named
GetDentistsByPostalCode and returns a DataSet containing all of the dentists that
are in a specified postal code.
The main task for this exercise is as follows:
• Create the GetDentistsByPostalCode XML Web service method.

f Task 1: Create the GetDentistsByPostalCode XML Web service method


1. Create an XML Web service method named GetDentistsByPostalCode that
has one String parameter that is passed by the value named postalCodeString
and returns a DataSet.
2. Set the description of the XML Web service method to This XML Web service
method returns the dentists from a supplied postal code.
3. In the GetDentistsByPostalCode XML Web service method, add code to fill a
new DataSet with the dentists that are in a specified a postal code by calling
the DentistByPostalCode stored procedure.

Note: You can copy and paste this code from the file
E:\Labfiles\Starter\DentistsPoCodeCS.txt or E:\Labfiles\Starter\DentistsPoCodeVB.txt.

4. Save your changes.


5. View the DentalService1.asmx page in the browser.
13-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


The description page of the XML Web service is displayed.
6. In the browser, click the GetDentistsByPostalCode link, in the
postalCodeString box, type 98052 and then click Invoke.
You should see all of the dentists for the postal code 98052. There should be
six dentists for this postal code.
7. Test the GetDentistsByPostalCode XML Web service method again with the
postal code 94111.
You should now see all of the dentists for the postal code 94111. There should
be three dentists for this postal code.
8. Test the GetDentistsByPostalCode XML Web service method again with the
postal code 02703.
You should see no dentists.
9. Close the browser window.

Results: After this exercise, you have created the GetDentistsByPostalCode XML Web
Service method.

Exercise 3: Consuming the GetAllDentists XML Web Service


Method
In this exercise, you will call the GetAllDentists XML Web service method of the
DentalService XML Web service. You will then display the resulting DataSet in a
GridView control.
The main tasks for this exercise are as follows:
1. Consume the DentalService XML Web service.
2. Call the GetAllDentists XML Web service method.

f Task 1: Consume the DentalService XML Web service


1. From the E:\Labfiles\Starter\DentistsWebForm\CS or
E:\Labfiles\Starter\DentistsWebForm\VB folder, add the dental.aspx Web
Form to the Benefits Web site.
2. In the Benefits Web site, add a Web reference to the DentalService XML Web
service:
Consuming and Creating XML Web Services 13-23

MCT USE ONLY. STUDENT USE PROHIBITED


a) In Solution Explorer, right-click the Benefits Web site, and then click Add
Web Reference.
b) In the Add Web Reference dialog box, in the Start Browsing for Web
Services pane, click Web services in this solution.
c) In the Web Services in this Solution pane, click DentalService1.
d) In the Web reference name box, type DentalWebRef and then click Add
Reference.
A new folder named App_WebReferences is automatically created in the
Benefits Web site.
3. In Solution Explorer, expand App_WebReferences, expand DentalWebRef,
and then examine the files in the DentalWebRef folder.

f Task 2: Call the GetAllDentists XML Web service method


1. Open the dental.aspx Web Form in Design view.
There are already TextBox, Button, and GridView controls on the page.
2. Open the dental.aspx code-behind page, and in the
GetAllDentistsButton_Click event procedure, locate the following comment.

TODO Lab 13: call the XML Web service method GetAllDentists

3. Write the code to consume the GetAllDentists XML Web service method:
a) Create a DentalService proxy named getAllDentistsProxy.
b) Create a DataSet named allDentistsDataSet.
c) Call the GetAllDentists XML Web service method and save the results in
allDentistsDataSet.
d) In the dentistsGridView control, set the data source to
allDentistsDataSet.
e) Call the DataBind method of the dentistsGridView control.
4. Save your changes.
5. View the dental.aspx page in the browser.
6. In the browser, click Get All Dentists.
You should see all the dentists in the GridView.
13-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


7. Close the browser window.

Results: After this exercise, you have consumed the GetAllDentists XML Web Service
method.

Exercise 4: Consuming the GetDentistsByPostalCode XML


Web Service Method
In this exercise, you will call the GetDentistsByPostalCode XML Web service
method of the Dentists.asmx XML Web service. You will use a GridView to display
the resulting DataSet of the dentists for a specified postal code.
The main task for this exercise is as follows:
• Call the GetDentistsByPostalCode XML Web service method.

f Task 1: Call the GetDentistsByPostalCode XML Web service method


1. Open the dental.aspx code-behind page and in the submitButton_Click event
procedure, locate the following comment.

TODO Lab 13: call the XML Web service method GetDentistsByPostalCode

2. Write the code to consume the GetDentistsByPostalCode XML Web service


method:
a) Create a DentalService proxy named getDentistsByPostCodeProxy.
b) Create a DataSet named dentistsByPostCodeDataSet.
c) Call the GetDentistsByPostalCode XML Web service method, and pass to
it the content of the postalCodeTextBox box, and then save the resulting
DataSet in the DataSet dentistsByPostCodeDataSet.
d) Set the data source of the dentistsGridView control to
dentistsByPostCodeDataSet.
e) Call the DataBind method of the dentistsGridView control.
3. Save your changes.
4. View the dental.aspx page in the browser.
5. In the Postal Code box, type 98052 and then click Submit.
You should see all of the dentists for the postal code 98052 in the GridView.
Consuming and Creating XML Web Services 13-25

MCT USE ONLY. STUDENT USE PROHIBITED


6. In the Postal Code box, type 94111 and then click Submit.
You should see all of the dentists for the postal code 94111 in the GridView.
7. Close the browser window.

Results: After this exercise, you have consumed the GetDentistsByPostalCode XML
Web Service method.
13-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. Does an XML Web service have a user interface?
2. How can you quickly test an XML Web service to see what Web methods and
parameters are available?
3. How do you access an XML Web service from a Web Form?
4. How do you check to see if an XML Web service is available for use at
runtime?
5. What attribute do you add to methods that you want to be exposed to the
Web from your XML Web service?

Common Issues related to XML Web service error handling


Identify the causes for the following common issues related to XML Web service
error handling and fill in the troubleshooting tips. For answers, refer to relevant
lessons in the module.
Consuming and Creating XML Web Services 13-27

MCT USE ONLY. STUDENT USE PROHIBITED


Issue Troubleshooting tip

An XML Web service is unavailable


from an ASP.NET Web Form.

An XML Web service is unable to


process a request.

Real-world Issues and Scenarios


1. You need to find existing XML Web services to add to your Web site. How can
you do this?
2. How can you add information to a Web service?
Managing State 14-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 14
Managing State
Contents:
Lesson 1: State Management 14-3
Lesson 2: Application and Session Variables 14-9
Lesson 3: Cookies and Cookieless Sessions 14-15
Lab: Storing Application and Session Data 14-20
14-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

Microsoft® ASP.NET enables you to manage state in a Web application. State is the
ability of a Web application to retain user information.
This module explains how to manage state in an ASP.NET Web application.
Managing State 14-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
State Management

The connection that is established between a user (the client computer) and a Web
server is called a session. Sessions can span multiple Web pages and are tracked by
using state management. State management is the process by which you maintain
the same information throughout multiple requests for the same or different Web
pages.
In this lesson, you will begin to understand in detail what state management is and
why it is important to manage state. This lesson explains server-side state
management and client-side state management and describes the Global.asax file.
14-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is State Management?

Key Points
ASP.NET provides state management that saves information on the server between
page requests and postbacks; this helps to maintain the continuity of user
information (state) throughout a visit to a Web site.
If state is maintained between pages, you can reuse the information so that users
do not have to reenter the same information multiple times. This is particularly
useful during the postback process when a user fills out a long or complicated
form.

Question: If you do not use state management, what happens to user details after
they are provided by a user on an initial logon page?
Managing State 14-5

MCT USE ONLY. STUDENT USE PROHIBITED


Types of State Management

Key Points
ASP.NET provides two types of state management:
• Server-side state management options use server resources to store state
information. These options provide higher security than client-side state
management.
• Client-side state management does not use server resources to store state
information and therefore offers fast server performance. However, it can be
unreliable and pose a security risk if you want to store sensitive information.

Question: What are the differences between server-side and client-side state
management?
14-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Server-Side State Management

Key Points
Application state is a global storage mechanism that is accessible from all of the
pages in the Web application. It enables you to store user information between
server round trips and between pages.
Session state is similar to application state except that it is limited to the current
browser session. If multiple users access a Web application, each user has a
different session state.

Question: How does ASP.NET provide application state and session state?
Managing State 14-7

MCT USE ONLY. STUDENT USE PROHIBITED


Client-Side State Management

Key Points
Most Web applications use cookies for client-side state management. A cookie
contains page-specific information that is stored either in a text file on the file
system of the client computer or in-memory in the client-browser session.
Cookies can expire when the browser session ends or they can exist indefinitely on
the client computer. Cookies are not as secure as server-side state management
options.

Question: Why are cookies less secure than server-side state management
options?
14-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


The Global.asax File

Key Points
The Global.asax file is an optional declarative file that you can use to handle events
while your Web application is running.
Every ASP.NET Web application supports one Global.asax file per Web
application; the Global.asax file is stored in the virtual root of the Web application.

Question: What are the types of events that the Global.asax file supports?
Managing State 14-9

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Application and Session Variables

You can use application and session variables to share information between the
pages of an ASP.NET Web application. This lesson explains how to initialize and
use application and session variables. It also demonstrates how to specify the
duration for application and session variables and describes how application and
session variables impact scalable storage. Finally, it explains how to save
application and session variables in a database.
14-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Initializing Application and Session Variables

Key Points
You initialize session and application variables in the Start event procedures of the
Application and Session objects in the Global.asax file.
• Application object. Shares state information among all of the users of a Web
application.
• Session object. Stores the information that you require for a particular user
session.

Question: When is an Application object created and when is it destroyed?


Managing State 14-11

MCT USE ONLY. STUDENT USE PROHIBITED


Accessing Application and Session Variables

Key Points
To set a session variable, you must provide a key that identifies the item that you
want to store. You must also set a value.
To set an application variable, you must prevent multiple users or applications
from updating the data simultaneously by using a simple set of locking methods.
To use a session or application variable in an ASP.NET page, you can read the
value from the Session or Application object.

Question: When you set application variables, why must you use the locking
methods of the Application object?
14-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Application and Session Variable Duration

Key Points
By default, a session times out when a user has not requested a page for more than
20 minutes. If the same user requests a page after 20 minutes, that user is treated
as a new user. You can modify the session duration in the web.config file.

Question: What must you set in the web.config file to modify the session
duration?
Managing State 14-13

MCT USE ONLY. STUDENT USE PROHIBITED


Scalable Storage of Application and Session Variables

Key Points
By default, session state is managed in-process so all of the information that is
added to a session state is stored in the same Web server that runs the ASP.NET
Web application. However, this limits the scalability of your Web site.
You can store session state out-of-process by managing session state with a
Microsoft SQL Server™ database or a separate state server. To store session state
out-of-process, you must modify the Web.config file to set the sessionState
element. The main advantage of out of process management is that is provides
scalability for your Web site.

Question: If you want to store session state out of process, what values must you
set for the sessionState element?
14-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Saving Application and Session Variables in a Database

Key Points
To save application and session variables in a SQL Server database or in a state
server:
1. Configure the session state in the Web.config file of your Web server.
2. Configure the SQL Server database or the state server.

Question: What must you modify in the Web.config file to configure the session
state?
Managing State 14-15

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Cookies and Cookieless Sessions

Cookies are a means by which the Web application that runs on the Web server
can cause a client to return information to the Web server with each HTTP request.
You can use the returned information to maintain state with the client across
multiple requests. Cookies are sent to the client as part of the Hypertext Transfer
Protocol (HTTP) header in a client request or are sent in a server response.
This lesson explains how to use cookies to store session data and how to retrieve
that data from a cookie. It also describes cookieless sessions and explains how to
set up cookieless sessions.
14-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Storing Session Date by Using Cookies

Key Points
You can create cookies by using the Cookies collection of the Response and
Request objects. The Cookies property represents a collection of cookies and is an
instance of the HttpCookieCollection class.
If you set the expiration time of a cookie, the cookie changes from a temporary
cookie to a persistent cookie. Persistent cookies are saved as text files to the hard
disk.

Question: How do you set the expiration time of a cookie?


Managing State 14-17

MCT USE ONLY. STUDENT USE PROHIBITED


Retrieving Information from a Cookie

Key Points
To retrieve information from a cookie, you read the cookie and retrieve the
key/value pairs from the cookie.
A cookie is returned to the server by the client in an HTTP "Cookie:" header.
Multiple cookies, separated by semicolons, can appear in this header.
You can read an existing cookie by accessing the Cookies collection of the Request
object.
14-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Cookieless Sessions

Key Points
Cookieless sessions enable you to take advantage of session state even with
browsers that have cookie support disabled. The SessionID that identifies the
active session is included in the URL instead of a cookie.

Question: What are the limitations of cookieless sessions?


Managing State 14-19

MCT USE ONLY. STUDENT USE PROHIBITED


Setting Up Cookieless Sessions

Key Points
To enable cookieless sessions, in the <sessionState> section of the Web.config file,
set the cookieless attribute to true.
14-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Storing Application and Session Data

Exercise 1: Implementing Session Variables


Scenario
Coho Winery offers several benefits to its employees. In the labs for this course,
you will create a Web site that enables employees to select and set up their chosen
benefits.
In this lab, you will use session and application variables to enhance the
experience for users when they browse the Benefits Web site.
In the current Web site, users must enter redundant information on multiple
pages. For example, users must supply their name and birth date on both the
medical page and the life insurance page. To simplify the user experience of the
Web site, you will use a cookie to store this information in session variables so that
users must enter this information only once.
In this exercise, you will store the user’s name and birth date in session variables.
Both the namedate.ascx user control and the life.aspx page will search for the
session variables and then fill the appropriate text boxes with the information if it
Managing State 14-21

MCT USE ONLY. STUDENT USE PROHIBITED


is available. If the session variables do not yet exist, either page will create the
session variables.
The main tasks for this exercise are as follows:
1. Open the Benefits Web site.
2. Get and set session variables in the life.aspx page.
3. Get and set session variables in the namedate.ascx code-behind page.
4. Test the code.

f Task 1: Open the Benefits Web site


1. Open Microsoft Visual Studio® 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.

f Task 2: Get and set session variables in the life.aspx page


1. Open the life.aspx code-behind file.
2. In the Page_Load event procedure, create a page postback check, and then
add code to perform the following tasks:
a) Get the Name and Birth session variables.
b) Set the Text property of the nameTextBox control to the content of the
Name session variable, and set the Text property of the birthTextBox box
to the content of the Birth session variable. Cast variables to the string
data type.
3. In the saveButton_Click event procedure, add the following code to the
Page.IsValid check:
a) Set the Name session variable to the text of the nameTextBox control.
b) Set the Birth session variable to the text of the birthTextBox control.
14-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 3: Get and set session variables in the namedate.ascx code-
behind page
1. Open the namedate.ascx code-behind file.
This is the user control that displays the name and birth date on the
medical.aspx Web Form.
2. In the nameDate class, create a Page_Load event procedure if one does not
exist.
3. In the Page_Load event procedure, create a page postback check, and then
add the following code:
a) Get the Name and Birth session variables.
b) Set the Text property for the nameTextBox control to the content of the
Name session variable, and set the Text property of the birthTextBox
control to the content of the Birth session variable.
4. In the nameDate class, in the Get statement for the public property
EmpName, add a line of code preceding the Return statement that sets the
Name session variable to the text of the nameTextBox control.
5. In the nameDate class, in the Get statement for the public property EmpDOB,
add a line of code preceding the Return statement that sets the Birth session
variable to the text of the birthTextBox control.

f Task 4: Test the code


1. Save your changes.
2. View life.aspx in a browser.
3. In the browser:
a) In the Name box, type your name.
b) In the Birth Date box, type your birth date.
c) In the Coverage box, type 400 and then click Save.
4. At the top of the page, click the Medical link.
In the medical.aspx Web Form, your name and birth date appear. These values
are obtained from the session variables.
5. In the Name box, change your name, and then click Save.
Managing State 14-23

MCT USE ONLY. STUDENT USE PROHIBITED


6. At the top of the page, click the Life Insurance link, and then verify that your
name has changed in the life.aspx Web Form.
7. Close the browser.

Results: After this exercise, you have stored the user’s name and birth date in session
variables. You have also added code to the life.aspx page and the namedate.ascx user
control to search for the session variables and fill the appropriate boxes with the
information if it is available.

Exercise 2: Implementing Cookies


Scenario
Before users complete the Benefits Web site registration process, they must be able
to see their selections on a single page. The Default.aspx page lists the selected
benefits. You will show all of the selected benefits on the Default.aspx page by
using a persistent cookie.
For both the medical.aspx and life.aspx pages, you will add code that reads the
existing values from the cookie and then updates the values and rewrites the
cookie.
In this exercise, you will use cookies to store all of a user’s benefits selections.
When a user returns to the Default.aspx page, the page lists the selected benefits
for the user.
The main tasks for this exercise are as follows:
1. Configure the home page.
2. Store the doctor selection.
3. Store the life insurance selections.
4. Test the cookie.

f Task 1: Configure the home page


1. Open the Default.aspx page.
2. In the Toolbox, drag two Label controls and two TextBox controls to the
bottom of the Web Form.
3. In the Editor window, individually select the following controls, and then in
the Properties window, set the following property for each control.
14-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Control Property

Label Text: Life Insurance

TextBox ID: lifeTextBox, Width: 300

Label Text: Doctor

TextBox ID: doctorTextBox, Width: 300

4. Arrange the new controls so that your Web Form resembles the following
illustration.

5. In the code-behind file, at the end of the Page_Load event procedure, after the
existing Page.IsPostBack check, add the following code:
a) Read a cookie named Benefits.
b) Declare two string variables named doctor and life to hold the doctor and
life values from the Benefits cookie.
Managing State 14-25

MCT USE ONLY. STUDENT USE PROHIBITED


c) If the cookie exists and is not empty, set the Text property of the
doctorTextBox control to doctor, and set the Text property of
lifeTextBox control to life.
Your code should resemble the following example.

[Visual C#]
HttpCookie getCookie = Request.Cookies["Benefits"];
string doctor = "";
string life = "";

if (getCookie != null)
{
doctor = getCookie.Values["doctor"];
life = getCookie.Values["life"];
doctorTextBox.Text = doctor;
lifeTextBox.Text = life;
}

[Visual Basic]
Dim getCookie As HttpCookie = Request.Cookies("Benefits")
Dim doctor As String = ""
Dim life As String = ""

If Not getCookie Is Nothing Then


doctor = getCookie.Values("doctor")
life = getCookie.Values("life")
doctorTextBox.Text = doctor
lifeTextBox.Text = life
End If

6. Save your changes.

f Task 2: Store the doctor selection


In this task, you only have to read the life string because you do not want to
overwrite it. You update the cookie with the life string and the new doctor
information; the current cookie is destroyed when it is recreated. The doctor string
is set from the doctorTextBox control; you do not have to read this information
because it is the new information that you want to store.
1. Open the medical.aspx code-behind file.
14-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


2. In the saveButton_Click event procedure, add code that retrieves all of the
information from the Benefits cookie if the cookie exists and contains
information.
Your code should include two string variables that hold the doctor and life
insurance values from the cookie.
3. In the saveButton_Click event procedure, add code to perform the following
tasks:
a) Update the value of the doctor variable to the text of the doctorTextBox
control.
b) Create a new cookie object, newCookie, with a cookie name of Benefits.
This replaces the existing Benefits cookie with a new cookie that contains
the updated information.
c) Set the expiration date for the Benefits cookie to 30 days from the present
date.
d) Add string two values, named doctor and life, to the cookie. These values
will hold doctor and life respectively.
e) Write the newCookie cookie.
4. Add code to the saveButton_Click event procedure that redirects the user
back to the Default.aspx page.
5. Save your changes.

f Task 3: Store the life insurance selections


When you update the life information, you must read the doctor information from
the cookie if it exists. When the cookie is recreated, the current doctor information
is destroyed.
1. In Solution Explorer, right-click life.aspx, and then click View Code.
2. In the saveButton_Click event procedure, inside the Page.IsValid check, add
code that retrieves all of the information from the Benefits cookie if the cookie
exists and it is not empty.
This code is identical to the code that you added to medical.aspx.
3. In Windows Explorer, open the file E:\Labfiles\Starter\CS\stringCS.txt or
E:\Labfiles\Starter\VB\stringVB.txt.
4. Copy the content of the file and then close the text file.
Managing State 14-27

MCT USE ONLY. STUDENT USE PROHIBITED


5. In Visual Studio 2008, in the saveButton_Click event procedure, paste the
content of the file beneath the previous code in the procedure.
This code builds a string that includes the selected life insurance options and
the value for the coverage amount.
6. Add code to create and write the Benefits cookie.
This code is identical to the code that you added to the medical.aspx page.
7. Add code to redirect the page back to the Default.aspx page.

Note: You can copy and paste this code from the starter text file
E:\LabFiles\Starter\CS\lifeCS.txt or E:\LabFiles\Starter\VB\life_VB.txt.

8. Save your changes.

f Task 4: Test the cookie


1. In Solution Explorer, right-click Default.aspx, and then click View in
Browser.
2. In the browser, click the Life Insurance link.
3. Fill in the required information, select one or both of the term coverage
options, and then click Save.
The browser returns you to the Default.aspx page; the page now contains the
life insurance information.
4. In the browser, click the Medical link.
5. Select a doctor, and then click Save.
The browser returns you to the Default.aspx page; the page now contains the
doctor information.
6. Close the browser.

Results: After this exercise, you have used cookies to store all of a user’s benefits
selections and when a user returns to the Default.aspx page, the page lists the selected
benefits for the user.
14-28 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Exercise 3: Implementing Application Variables
Scenario
You want to provide a quick and easy way for management to see how many
employees access the new Benefits Web site. Therefore, you decide to implement a
page counter on the retirement.aspx page by using an application variable. You
want to ensure that the counter is not increased when a page postback occurs but
only counts unique visits to the page.
In this exercise, you will add a page counter to the retirement.aspx page.
The main tasks for this exercise are as follows:
1. Add user interface (UI) components.
2. Add the code.
3. Test the application variable.

f Task 1: Add user interface (UI) components


1. In Solution Explorer, right-click retirement.aspx, and then click View
Designer.
2. In the Toolbox, drag a Label control to the bottom of the Web Form.
3. In the Properties window, set the ID property of the control to visitsLabel.

f Task 2: Add the code


1. On the View menu, click Code.
2. In the Page_Load event procedure, when the page is not a postback, add the
following code:
a) Lock the application.
b) Increment the value of the application variable Visits by one.
c) Unlock the application.
You must lock the application variable before you increment it. If you do not
lock the application, two clients can simultaneously attempt to increment the
visitor counter.
Managing State 14-29

MCT USE ONLY. STUDENT USE PROHIBITED


In Microsoft Visual Basic®, you can also use the += operator to increment
application variables. In Microsoft Visual C#®, you cannot increment
application variables by using the += operator.
3. At the end of the Page_Load event procedure, add code to set the Text
property of the visitsLabel control to a concatenation of the following items:
a) "This page has been visited "
b) The value of the Visits application variable.
c) " times."
When complete, the Page_Load event procedure should resemble the
following example.

[Visual C#]
if (!Page.IsPostBack)
{
DataSet retirementDataSet = new DataSet();
retirementDataSet.ReadXml(Server.MapPath("mutual_funds.xml"));
retirementGridView.DataSource = retirementDataSet;
retirementGridView.DataBind();

Application.Lock();
Application["Visits"] =
Convert.ToInt16(Application["Visits"]) + 1;
Application.UnLock();
}

visitsLabel.Text = "This page has been visited " +


Application["Visits"].ToString() + " times.";

[Visual Basic]
If Not Page.IsPostBack Then

Dim retirementDataSet As New DataSet()


retirementDataSet.ReadXml(Server.MapPath("mutual_funds.xml"))
retirementGridView.DataSource = retirementDataSet
retirementGridView.DataBind()

Application.Lock()
Application("Visits") = CInt(Application("Visits")) + 1
Application.UnLock()
End If

visitsLabel.Text = "This page has been visited " & _


CStr(Application("Visits")) & " times."
14-30 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Application variables can produce a null reference exception. It is advisable to
create and initialize application variables in the Application_Start event of the
Global.asax file.

f Task 3: Test the application variable


1. Save your changes.
2. In Solution Explorer, right-click retirement.aspx, and then click View in
Browser.
3. Press F5 to refresh the browser.
The page counter increases with each refresh of the page.
4. Close the browser.

Results: After this exercise, you have added a page counter to the retirement.aspx
page.

Exercise 4: Storing Session Variables in a Database


Scenario
To prepare your Web site for deployment on a Web farm, you want to store the
session variables in a central location. You want to use a SQL Server database for
this short-term storage solution.
In this exercise, you will store the Name and Birth session variables in a SQL
Server database.
The main tasks for this exercise are as follows:
1. Configure web.config.
2. Install and configure the databases.
3. Test the Web application.

f Task 1: Configure web.config


1. In Solution Explorer, double-click web.config.
2. In the web.config file, in the system.web element, create a sessionState child
element.
Managing State 14-31

MCT USE ONLY. STUDENT USE PROHIBITED


3. In the sessionState element, set the following attributes.

Attribute Value

Mode SQLServer

sqlConnectionString data source=LONDON\SqlExpress;Integrated Security=SSPI

cookieless false

Timeout 20

When complete, the sessionState element should resemble the following


example.

<sessionState
mode="SQLServer"
sqlConnectionString=
"data source=LONDON\SqlExpress;Integrated Security=SSPI"
cookieless="false"
timeout="20"/>

Because the web.config file is an XML file, proper capitalization of the element
and attribute names is critical.
4. Save your changes.

f Task 2: Install and configure the databases


Session variables are stored in two preconfigured databases named ASPState and
TempDB. This task installs and configures the databases.
1. Open a Visual Studio 2008 Command Prompt window.
2. At the command prompt, type the following command, and then press
ENTER.

aspnet_regsql -S LONDON\SQLExpress -E -ssadd

The Command Prompt window displays a series of messages and then returns
to the command prompt. The ASPState and TempDB databases have been
restored.
14-32 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 3: Test the Web application
1. In Visual Studio 2008, in Solution Explorer, right-click Default.aspx, and then
click View in Browser to test the Benefits Web site.
2. In the browser, click the Medical link, enter the necessary information, and
then click Save.
3. In the browser, click the Life Insurance link.
4. Verify that the session variables that contain your name and birth date work
properly.
5. Select a doctor and then click Save.
6. Close Internet Explorer.

Results: After this exercise, you have stored the user name and birth date session
variables in a SQL Server database.
Managing State 14-33

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. How do you set up a Web application to use cookieless sessions?
2. What are the three categories of events that are handled in the Global.asax file?
3. Why must you initialize application variables?
4. Where can you initialize application variables?
5. Can there be more than one Global.asax file for a single Web application?

Best Practices related to state management


Supplement or modify the following best practices for your own work situations:
• The following table lists client-side state management options and describes
situations when you must implement each option.
14-34 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Option Recommendation
Cookies Use when you need to store small amounts of information
on the client and security is not an issue.

View state Use when you need to store small amounts of information
for a page that will post back to itself. The ViewState
property provides functionality with basic security.

Query string Use when you need to transfer small amounts of


information from one page to another and security is not an
issue.

• The following table lists server-side state management options and describes
situations when you must implement each option.

Option Recommendation
Application state Use when you need to store global information for many
users and security is not an issue. Do not store large
quantities of information in application state.

Session state Use when you need to store short-term information that is
specific to an individual session and security is an issue. Do
not store large quantities of information in session state.

Profile properties Use when you need to store user-specific information that
needs to be persisted after the user session is expired and
then retrieved again on subsequent visits to your
application.

Database support Use when you need to store large amounts of information,
manage transactions, or maintain the information over
application and session restarts. Data mining is a concern
and security is an issue.

Tools

Tool Use for Where to find it


Aspnet_regsql • Creates a SQL Server database Command prompt
and adds or removes options
from an existing database.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 15
Configuring, Optimizing, and Deploying a
Microsoft® ASP.NET Web Application
Contents:
Lesson 1: Implementing the Cache Object 15-3
Lesson 2: ASP.NET Output Caching 15-8
Lesson 3: Configuring an ASP.NET Web Application 15-13
Lesson 4: Deploying an ASP.NET Web Application 15-21
Lab: Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web
Application 15-26
15-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

After you finish development of your Microsoft® ASP.NET Web application, you
can deploy it on a production server. However, before deployment, you may want
to optimize the Web application to improve performance.
This module describes how to configure the Cache object and the output cache to
optimize response times for the Web application. It also describes how to organize
the application settings in the Machine.config and web.config files to both support
and protect the Web site. Finally this module explains how to deploy the Web site
to a production server.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Implementing the Cache Object

One of most effective ways to increase the performance of an ASP.NET Web


application is to use the ASP.NET Cache object. The Cache object enables you to
place items in server memory so that you can quickly retrieve them.
This lesson describes how to set up the Cache object to optimize the response
times for a Web application.
15-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


What Is the Cache Object?

Key Points
The following process describes how the Cache object works:
1. A page requests an item that is stored in the Cache object.
2. ASP.NET checks the Cache object and uses the cached version if it is available.
If a cached version is not available, ASP.NET recreates the item, uses that item,
and then stores that item in the Cache object for future use.

Question: What are some possible uses for the Cache object in your own
applications?
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-5

MCT USE ONLY. STUDENT USE PROHIBITED


Advantages of the Cache Object

Question: How can the Cache object help to increase the speed of your
application?
15-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


How to Use the Cache Object

Key Points
You can write an item into a Cache object implicitly or you can use the explicit
Insert method with parameters. To retrieve a value from the cache, you provide the
correct key to hold the retrieved value and cast the object to the correct data type.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-7

MCT USE ONLY. STUDENT USE PROHIBITED


Removing Items from the Cache Object

Key Points
To influence how the Cache object saves and removes items, define time limits,
dependencies, and priorities for items, as shown in the following code example:

[Visual C#]
Cache.Insert("MyBook.CurrentBook", CurrentBook, new CacheDependency
(Server.MapPath("Books.xml")), DateTime.Now.AddMinutes(5),
TimeSpan.FromSeconds(30), CacheItemPriority.High, onRemove);

[Visual Basic]
Cache.Insert("MyBook.CurrentBook", CurrentBook, new CacheDependency _
(Server.MapPath("Books.xml")), DateTime.Now.AddMinutes(5), _
TimeSpan.FromSeconds(30), CacheItemPriority.High, onRemove)
15-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
ASP.NET Output Caching

One factor that you must consider when you create high-performance Web
applications is how to minimize the response time to page requests. You can store
a page, or parts of a page in memory on the Web server the first time they are
requested and then use that stored page, or parts of that page, for later requests.
This enables you to avoid the processing time required to recreate the page.
This lesson describes how to set up the output cache to minimize page response
times for a Web application.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-9

MCT USE ONLY. STUDENT USE PROHIBITED


Multimedia: Output Caching

In this animation, you will see how the page output cache affects server response
times when an ASP.NET Web Form is requested more than once.
15-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Output Cache Types

Key Points
Page output caching enables you to store entire Web Forms and user controls in
server memory. You can cache portions of a page by creating the section as a user
control and then caching the user control with the page output cache.
For a Web service, you can specify the number of seconds that the results for the
XML Web service method will remain in the output cache.

Question: How can your own applications benefit from page output caching?
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-11

MCT USE ONLY. STUDENT USE PROHIBITED


Implementing Page Output Caches

Key Points
You can implement the page output cache:
• Declaratively by using the @ OutputCache directive.
• Programmatically by using the SetCacheability method on the Cache property
of the Response object.
• In a configuration file by using the OutputCache and OutputCacheSettings
elements.
15-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Implementing Control Caching

Key Points
Control caching enables you to separate certain portions of a page from the rest of
the page.
Items that are good candidates for control caching include headers, footers, and
lists that are used by multiple pages.
You can set the caching policies for a user control declaratively by using the @
OutputCache directive or programmatically by using the PartialCachingAttribute
class.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-13

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Configuring an ASP.NET Web Application

Before you can deploy your ASP.NET Web application, you must organize the Web
application settings in the Machine.config and web.config files. This lesson
explains how to configure an ASP.NET Web application.
15-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Overview of Configuration Files

Key Points
Configuration information for ASP.NET resources is contained in a collection of
configuration files. Each configuration file contains a nested hierarchy of XML
elements with attributes that specify the configuration settings.

Question: How many web.config files does your application use?


Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-15

MCT USE ONLY. STUDENT USE PROHIBITED


Configuring a Web Server by Using Machine.config

Key Points
The Machine.config file is located in the following directory:
C:\WINDOWS\Microsoft .NET \Framework\version\CONFIG\Machine.config
• Advantages of the Machine.config file. Storing settings in the Machine.config
file can make your system easier to maintain because you have only one
configuration file to search, edit, and maintain.
• Disadvantages of the Machine.config file. When you deploy a Web application
to a new server, the Web application settings that are in the Machine.config file
are not copied to the new Web server.
15-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Configuring an Application by Using Web.config

Key Points
You use the web.config file to share information and settings between Web pages.
A single web.config file is typically located in the root folder of the Web
application. You can place additional web.config files in the folder of the virtual
directory to which they belong.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-17

MCT USE ONLY. STUDENT USE PROHIBITED


Configuration Inheritance

Key Points
The settings in the Machine.config file apply to all ASP.NET directories and
subdirectories. Additional configuration information is contained in the web.config
configuration files, which are located in the same directories as the application
files. Child directories inherit the settings of the parent directories unless the
settings are overridden by a web.config file in the child directory.
15-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Configuration Inheritance

In this demonstration, you will see how configuration settings are inherited from
one web.config file by a second web.config file that is located in a subdirectory.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-19

MCT USE ONLY. STUDENT USE PROHIBITED


Web Site Administration Tool

Key Points
The Web Site Administration Tool enables you to configure your ASP.NET Web
site by using a Web page. The Tool contains three sections as follows:
• The Security tab enables you to manage security settings.
• The Application tab enables you to manage several application-wide settings.
• The Provider tab enables you to specify where and how to store administration
data used by your Web site such as membership data.

Question: In what situations may you have to take a Web application offline?
15-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Retrieving Data from Web.config

Key Points
The WebConfigurationManager class provides the AppSettings and
ConnectionStrings properties, which you use to access the key-value pairs in the
<appSettings> and <connectionStrings> sections of the web.config file.
For other sections in the configuration file, the WebConfigurationManager class
provides the GetSection method.

Question: In which situations may you want to access the configuration settings
of your Web application programmatically?
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-21

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 4
Deploying an ASP.NET Web Application

After you set up caching and organize the Web application settings between the
Machine.config and web.config files, you are ready to deploy your ASP.NET Web
application.
This lesson describes how to select the files that are necessary to run the Web
application and then use XCOPY or file transfer protocol (FTP) to copy these files
to the production directory.
15-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Web Application Deployment

Key Points
You can choose from several deployment options for your Web application. Before
you can deploy a Web application to a production directory, the folder to which
you will deploy your Web application must be configured as an application in
Internet Information Services (IIS).
The files that are required on the production server include:
• The bin folder and the DLL files that are in it.
• All Web Form, user control, and XML Web service files (.aspx, .ascx, .asmx).
• Files, including web.config configuration files and global.asax.
• Any additional support files that are in the directory (such as XML files).
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-23

MCT USE ONLY. STUDENT USE PROHIBITED


Deploying a Web Application by Using the Publish Web
Site Utility

Key Points
An advantage of the Publish Web Site utility is that the source code is removed
from the Web site prior to deployment. However, if you do not select the option
Allow this precompiled site to be updatable, you must recompile the site if you
want to make changes.

Question: How can the Publish Web Site utility be useful to you when you
develop your own Web applications?
15-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Sharing Assemblies in the Global Assembly Cache

Key Points
You can use one of the following methods to install an assembly into the global
assembly cache (GAC):
• Use an installer application such as Microsoft Windows® Installer. This is the
preferred option for deployment scenarios.
• Use the Global Assembly Cache application (Gacutil.exe) provided by the
Windows Software Development Kit (SDK).
• Use Windows Explorer to drag assemblies into the cache.

Question: How do you make use of the GAC in your own applications?
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-25

MCT USE ONLY. STUDENT USE PROHIBITED


Updating Your Web Application

Key Points
After you deploy your Web application to a production directory, you can update
the Web application at any time. This update does not require you to restart the
server, IIS, or the Web application.
15-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Configuring, Optimizing, and Deploying a
Microsoft ASP.NET Web Application

Exercise 1: Caching a DataSet by Using the Cache Object


Scenario
Coho Winery offers several benefits to its employees. In the labs for this course,
you create a Web site that enables employees to select and set up their chosen
benefits. In this lab, you will optimize and then deploy the Benefits Web site.

In this exercise, you will use the Cache object to cache the DataSet object doctors.
Placing a DataSet in cache reduces the number of times that a Web Form must
connect to the data source to fill the GridView.
Because the GridView uses DataViews that are based on the city name selected
from the list, you will implement caching in the Page_Load event procedure and in
the list’s SelectedIndexChanged event procedure.
The GridView also implements paging. To reduce the amount of code that you
add in this lab, you will disable this feature of the GridView.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-27

MCT USE ONLY. STUDENT USE PROHIBITED


The main tasks for this exercise are as follows:
1. Open the Benefits Web site and DentalService Web service.
2. Turn off paging.
3. Cache the DataSet in the Page_Load event procedure.
4. Cache the DataSet in the citiesList_SelectedIndexChanged event procedure.
5. Test the doctors page.
6. If time permits add a new row to the doctors table.

f Task 1: Open the Benefits Web site and DentalService Web service
1. Open Microsoft Visual Studio® 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.
3. Add the DentalService project from E:\Labfiles\Starter\CS\DentalService or
E:\Labfiles\Starter\VB\DentalService to the solution.

f Task 2: Turn off paging


1. Open the doctors.aspx file in Design view.
2. View the properties of the doctorsGridView control.
3. Set the AllowPaging property to False.
This will disable paging for the GridView. All data that is returned from the
data source will be displayed.

f Task 3: Cache the DataSet in the Page_Load event procedure


1. Open the doctors.aspx.vb or doctors.aspx.cs file.
2. In the CreateDataSet procedure, locate the following code.
15-28 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual C#]
doctorsSqlDataAdapter.Fill(doctorsDataSet);

[Visual Basic]
doctorsSqlDataAdapter.Fill(doctorsDataSet)

3. Immediately before this line, add code that checks the cache for a key named
doctors. The code must check to see if this key is empty or does not exist.
4. If the doctors cache key is empty or does not exist, fill the DataSet object
doctorsDataSet by using the existing DataAdapter object
doctorsSqlDataAdapter, and then insert a new doctors key into the cache that
contains the new DataSet. Use the information in the following table to write
your code.

Property Visual Basic Value Visual C# Value


Key name doctors doctors

Value doctorsDataSet doctorsDataSet

Dependencies Nothing null

Absolute Expiration 4 4

Sliding Expiration Nothing Caching.Cache.NoSlidingExpiration

Your code should resemble the following example.

[Visual C#]
if (Cache["doctors"] == null)
{
doctorsSqlDataAdapter.Fill(doctorsDataSet);
Cache.Insert("doctors", doctorsDataSet, null,
DateTime.Now.AddMinutes(4),
System.Web.Caching.Cache.NoSlidingExpiration);
}

[Visual Basic]
If (Cache("doctors") Is Nothing) Then
doctorsSqlDataAdapter.Fill(doctorsDataSet)
Cache.Insert("doctors", doctorsDataSet, Nothing, _
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-29

MCT USE ONLY. STUDENT USE PROHIBITED


DateTime.Now.AddMinutes(4), Nothing)
End If

5. In the Page_Load event procedure, locate the following line of code.

[Visual C#]
doctorsGridView.DataSource = SqlDataSource1;

[Visual Basic]
doctorsGridView.DataSource = SqlDataSource1

6. Modify the code to set the DataSource property of doctorsGridView to the


cached DataSet.
7. In the Page_Load event procedure, move the call to the CreateDataSet
method to the line before the code that you amended in the previous step.
This step ensures that the DataSet is created and cached as the first action
when the page loads.

f Task 4: Cache the DataSet in the citiesList_SelectedIndexChanged


event procedure
1. In the doctors.aspx.cs or doctors.aspx.vb files, locate the
citiesList_SelectedIndexChanged event procedure.
2. In the citiesList_SelectedIndexChanged event procedure, modify the code to
set the DataSource property of doctorsGridView to the cached DataSet.
3. Change the argument for the DataView object to refer to the doctors cache
key and convert it to a DataSet type.

f Task 5: Test the doctors page


1. Save your changes.
2. View the doctors.aspx page in the browser.
3. Test the list of city names by selecting different city names.
4. Close the browser window.
15-30 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 6: If time permits add a new row to the doctors table
1. In Server Explorer, add a data connection to the doctors database.
2. View the doctors.aspx page in the browser.
3. In the City list, select All.
4. In Server Explorer, open the doctors table.
5. Add a new row to the doctors table. You must include a value for the dr_id,
dr_fname, and dr_lname columns.
6. In the browser window, refresh the doctors.aspx page.
Note that the new item does not appear in the GridView.
7. Select any city in the list, and then select All.
Note that the new item still does not appear in the GridView.
8. Wait at least four minutes, and then repeat Step 5.
Note that the new row now displays in the GridView.
9. Delete the row that you added to the database.
Note that the deleted item still appears in the GridView. If you wait four
minutes and then refresh the page, the deleted item no longer displays.
10. Close the browser window.

Results: After this exercise, you have used the Cache object to cache the DataSet
object doctors.

Exercise 2: Reducing Response Times by Using the Page


Output Cache
The medical.aspx page displays the user’s name, birth date, and the doctor that the
user has selected from the doctors.aspx page. To reduce response times for this
page, you will cache the entire page by using page output caching.
In this exercise, you will cache a Web Form by using the OutputCache directive.
You will also alter the VaryByParam attribute.
The main tasks for this exercise are as follows:
1. Cache the medical.aspx page.
2. Use the VaryByParam attribute.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-31

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 1: Cache the medical.aspx page
1. Open the medical.aspx page, and then switch to Hypertext Markup Language
(HTML) view.
2. Add an OutputCache directive that enables output caching for the entire page.
The page must remain in the cache for two minutes and must not be updated
based on the parameters that are passed to the page.
3. Save the medical.aspx page.
4. View the medical.aspx page in the browser.
5. Click the Select a doctor link.
6. In the doctors.aspx page, in the GridView, select a doctor and then click
Submit.
You are returned to the medical.aspx page, but the selected doctor’s name does not
appear next to the Primary Care Physician box.

f Task 2: Use the VaryByParam attribute


1. Return to the HTML view for the medical.aspx page.
2. Edit the OutputCache directive that you added. Change the code to create a
new cached version of the page when a different doctor is selected from the
doctors.aspx page.
You code should resemble the following example.

<%@ OutputCache Duration="120" VaryByParam="pcp"%>

3. View the medical.aspx page in Design view.


4. Set the width of the doctorTextBox to 200 pixels.
5. View the code of the medical.aspx page.
6. In the Page_Load event procedure, locate the following line of code.

[Visual C#]
doctorTextBox.Text = Request.QueryString["pcp"];
15-32 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


[Visual Basic]
doctorTextBox.Text = Request.QueryString("pcp")

7. Modify the code to display the current time in addition to the content of the
pcp parameter.
Your code should resemble the following example

[Visual C#]
doctorTextBox.Text = Request.QueryString["pcp"] + " "
+ DateTime.Now.ToLongTimeString();

[Visual Basic]
doctorTextBox.Text = Request.QueryString("pcp") & " " _
& DateTime.Now.ToLongTimeString()

The purpose of this code is to enable you to establish when you are viewing a
cached version of the page.
8. Save your changes.
9. View the medical.aspx page in the browser.
10. Click the Select a doctor link.
11. In doctors.aspx, in the GridView, select a doctor and then click Submit.
You are returned to medical.aspx, and the selected doctor’s name appears next
to the Primary Care Physician box, along with the current time.
12. Note the time next to the doctor's name.
13. Click Select a doctor.
14. In the GridView, select a different doctor and then click Submit.
When you are returned to medical.aspx, the Primary Care Physician box now
shows the newly selected doctor’s name.
15. Note the time next to the second doctor's name.
16. Click Select a doctor.
17. In the GridView, select the first doctor again and then click Submit.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-33

MCT USE ONLY. STUDENT USE PROHIBITED


As long as you perform this selection within two minutes, the time will not
have changed because you are viewing a cached version of the page.
18. Close the browser window.

Results: After this exercise, you have cached a Web Form by using the OutputCache
directive.

Exercise 3: Partial-Page Caching


The user control header.ascx displays a banner at the top of each page in your
Web application. Because this information typically does not change and is
required for every page request, you will cache the information for quick retrieval.
In this exercise, you will use the page output cache to cache the user control
header.ascx. You will first add a time stamp to the header to verify that the cache
is working properly.
The main tasks for this exercise are as follows:
1. Add a time stamp to the header.
2. Add caching to the header file.

f Task 1: Add a time stamp to the header


1. Open the header.ascx file in Design view.
2. In the Toolbox, drag a label control to the right of the text Benefits Selection
Site. Name the new label control timeLabel.
3. In the code-behind page for header.ascx, at the end of the Page_Load event
procedure, add code to make the timeLabel control show the current time.
4. Save the header.ascx page, and then build the Benefits Web site.
5. View the doctors.aspx page in the browser.
Because header.ascx cannot be viewed in a browser, you must view a page that
uses the user control.
6. Refresh the browser several times.
Note that the time displayed in header.ascx changes with every refresh of the
doctors.aspx page.
15-34 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


7. Close the browser window.

f Task 2: Add caching to the header file


1. Open header.ascx, and then switch to HTML view.
2. Add an Output Cache directive to the page that enables page caching with a
duration of two minutes. The cache must not change based on any parameters
that are passed.
3. Save the header.ascx page, and then build the Benefits Web site.
4. View the doctors.aspx page in the browser.
5. Refresh the browser several times.
Notice that the time in header.ascx does not change with each refresh. If time
permits, wait more than two minutes and then refresh the page once more.
The header will display the current time.
6. Close the browser window.

Results: After this exercise, you have used the page output cache to cache the user
control header.ascx.

Exercise 4: Deploying Your Site


In this exercise, you will deploy your Web site by using the Publish Web Site utility
in Visual Studio 2008 and then test the deployed site.
The main tasks for this exercise are as follows:
1. Prepare the project for deployment.
2. Publish the DentalService Web service.
3. Recreate the Web reference to the DentalService Web service.
4. Publish the Benefits Web site.
5. Test the deployment.

f Task 1: Prepare the project for deployment


1. In Solution Explorer, select Solution 'Benefits'.
2. On the Standard toolbar, in the Solution Configurations list, click Release.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-35

MCT USE ONLY. STUDENT USE PROHIBITED


3. On the Build menu, click Rebuild Solution.
4. Click Start, point to All Programs, expand the Microsoft Visual Studio 2008
folder, expand the Visual Studio Tools folder, and then click Visual Studio
2008 Command Prompt.
A Command Prompt window opens.
5. At the command prompt, type the following command, and then press
ENTER.

aspnet_regsql -S LONDON\SQLExpress -E -ssadd

You must perform this step because the ASPState database does not exist in
the virtual machine for this lab.
6. Close the command prompt window.

f Task 2: Publish the DentalService Web service


1. In Solution Explorer, click the DentalService project.
2. On the Build menu, click Publish DentalService.
3. In the Publish Web dialog box, in the Target location box, type
E:\DentalService and then click Publish.
4. On the Start menu, in the Start Search box, type inetmgr and then press
ENTER.
5. In the User Account Control dialog box, click Continue.
The Internet Information Services Manager dialog box opens.
6. In the Internet Information Services Manager dialog box, expand the local
computer, and then expand Web Sites.
7. Right-click Default Web Site, and then click Add Application.
8. In the Add Application dialog box, in the Alias box, type DentalService
9. In the Physical path box, type E:\DentalService and then click OK.
10. Minimize the Internet Information Services Manager dialog box.
11. Open Microsoft Internet Explorer®.
15-36 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


12. In the Address bar, type
http://localhost/DentalService/DentalService1.asmx and then press
ENTER.
13. Verify that the description page for DentalService1 appears.
14. Close the browser window.

f Task 3: Recreate the Web reference to the DentalService Web service


1. In Solution Explorer, in the Benefits Web site, expand App_WebReferences.
2. Right-click DentalWebRef, and then click Delete.
3. In the confirmation dialog box, click OK.
4. In Solution Explorer, right-click the Benefits Web site, and then click Add
Web Reference.
5. In the Add Web Reference dialog box, in the URL box, type
http://localhost/DentalService/DentalService1.asmx and then click Go.
6. In the Web reference name box, type DentalWebRef and then click Add
Reference.
7. In Solution Explorer, right-click the Benefits Web site, and then click Build
Web Site.

f Task 4: Publish the Benefits Web site


1. In Solution Explorer, click the Benefits Web site.
2. On the Build menu, click Publish Web Site.
3. In the Publish Web Site dialog box, in the Target location box, type
E:\Benefits
4. Clear the Allow this precompiled site to be updatable check box and then
click OK.
5. Restore the Internet Information Services Manager dialog box.
6. In the Internet Information Services Manager dialog box, right-click Default
Web Site, and then click Add Application.
7. In the Add Application dialog box, in the Alias box, type Benefits
8. In the Physical path box, type E:\Benefits and then click OK.
Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-37

MCT USE ONLY. STUDENT USE PROHIBITED


9. Examine the files of the deployed applications, Benefits and DentalService.
10. Minimize the Internet Information Services Manager dialog box.

f Task 5: Test the deployment


1. Open Internet Explorer.
2. In the Address bar, type http://localhost/Benefits/Default.aspx and then
press ENTER.
3. Verify that the home page for the Benefits Web site appears.
4. Test the different pages on the Benefits Web site.
5. Close the browser window.

Results: After this exercise, you have deployed your Web site by using the Publish
Web Site utility in Visual Studio 2008.
15-38 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. What is the difference between the Cache object and page output caching?
2. What sort of caching would you use to place a DataSet into cache?
3. Which files can you use to configure an ASP.NET Web application?
4. What options can you use to deploy an ASP.NET Web application?

Common Issues related to building high-performance Web applications


Identify the causes for the following common issues related to building high-
performance Web applications and fill in the troubleshooting tips. For answers,
refer to relevant lessons in the module.

Issue Troubleshooting tip

Requirement to avoid duplication


Configuring, Optimizing, and Deploying a Microsoft® ASP.NET Web Application 15-39

MCT USE ONLY. STUDENT USE PROHIBITED


Issue Troubleshooting tip

Minimize the response time to page


requests

Tools

Tool Use for Where to find it


Web Site • Enables you to configure your In Visual Studio 2008,
Administration Tool ASP.NET Web site by using a on the Website menu,
Web page. click ASP.NET
Configuration.
Securing a Microsoft ASP.NET Web Application 16-1

MCT USE ONLY. STUDENT USE PROHIBITED


Module 16
Securing a Microsoft ASP.NET Web Application
Contents:
Lesson 1: Web Application Security Overview 16-3
Lesson 2: Windows-Based Authentication 16-10
Lesson 3: Forms-Based Authentication 16-13
Lab: Securing a Microsoft ASP.NET Web Application 16-19
Course Evaluation 16-32
16-2 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Overview

Securing Web applications is a critical and a complex matter for Web developers. A
secure system requires careful planning, and Web site administrators and
developers must have an unambiguous understanding of the options that are
available to them when they secure their Web applications.
Microsoft® ASP.NET synchronizes with the Microsoft .NET Framework and
Internet Information Services (IIS) to provide Web application security. This
module explains the various Web application security methods.
Securing a Microsoft ASP.NET Web Application 16-3

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 1
Web Application Security Overview

By definition, Web applications provide user access to a central Web server and
other database servers. If you understand and implement suitable security
measures for your Web application, you can protect your own resources; you can
also provide a secure environment that is easy for your users to work in.
This lesson provides an overview of different security concepts: authentication,
authorization, and IIS authentication mechanisms. It also explains Secure Sockets
Layer (SSL).
16-4 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Authentication vs. Authorization

Key Points
The two fundamental security concepts are as follows:
• Authentication. Obtains user credentials and validates those credentials
against some authority such as a database.
• Authorization. Determines if the authenticated user has access to a specified
resource. You can limit access rights by granting or denying specific
permissions to an authenticated identity.

Question: Does authentication occur before or after authorization or do they both


occur at the same time?
Securing a Microsoft ASP.NET Web Application 16-5

MCT USE ONLY. STUDENT USE PROHIBITED


What Are the ASP.NET Authentication Methods?

Key Points
ASP.NET implements authentication by using three types of authentication
method:
• Microsoft Windows®–based authentication. The ASP.NET Web application
relies on the Windows operating system to authenticate the user.
• Forms-based authentication. Non-authenticated requests are redirected to an
authentication form by using client-side redirection.
• Microsoft Passport authentication. Users are authenticated to access Web sites
by using a single Passport account.

Question: Which authentication method(s) also use IIS authentication?


16-6 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Comparing the ASP.NET Authentication Methods

Key Points
Windows-based authentication is appropriate when you have a fixed number of
users with existing Windows user accounts; however, it is not suitable for most
Internet applications.
Forms-based authentication is appropriate when you want to set up a custom user
registration system; however, it utilizes cookies to determine the identity of the
user.
Microsoft Passport authentication enables a user to sign in to multiple Webs sites
by using a single set of credentials; however, there is a subscription fee and it is
based on cookies.

Question: Why is Windows-based authentication not suitable for most Internet


applications?
Securing a Microsoft ASP.NET Web Application 16-7

MCT USE ONLY. STUDENT USE PROHIBITED


What Are the IIS Authentication Mechanisms?

Key Points
When you use Windows-based authentication, you must first configure the
authentication mechanisms in IIS:
• Anonymous access. When IIS receives a request from an anonymous user, IIS
in turn makes the request to Windows by using the default
IUSR_machinename account.
• Basic authentication. Supported by most browsers; users without credentials
are prompted to supply a user name and password.
• Digest authentication. Similar to Basic authentication, but it uses an encoded
hash to send user information to the server. However, it works only with
Active Directory® directory service domain accounts.
• Integrated Windows security. IIS can pass on the credentials of Windows
users as an encrypted token when a request is made to access a resource.
However, it is not practical in environments with firewalls.

Question: How can you improve the security of Basic authentication?


16-8 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: IIS Authentication Mechanisms

Question: How can you enable and disable the authentication mechanisms in IIS?
Securing a Microsoft ASP.NET Web Application 16-9

MCT USE ONLY. STUDENT USE PROHIBITED


What Is Secure Sockets Layer?

Key Points
SSL is a protocol that you can use to transmit data securely across a network.
SSL secures data communication by using data encryption, server authentication,
and data integrity.

Question: How can you prevent one Web site from impersonating another?
16-10 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 2
Windows-Based Authentication

You can use Windows-based authentication to secure Web applications when you
know which users access your Web site.
This lesson explains how to use Windows-based authentication to secure your
Web applications.
Securing a Microsoft ASP.NET Web Application 16-11

MCT USE ONLY. STUDENT USE PROHIBITED


Enabling Windows-Based Authentication

Key Points
Securing Web applications by using Windows-based authentication is a four-step
process:
1. Configure IIS to use one or more of its three authentication mechanisms.
2. Set up authentication in the <authentication>, <authorization>, and
<identity> sections of the web.config file.
3. Set up authorization for each secure page in the <location> sections of the
web.config file.
4. IIS requests logon information from your users and grants access if the
credentials are valid.

Question: How can you allow or deny users access to a page?


16-12 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Reading User Information

Key Points
When Windows-based authentication is complete, the Web server can read the
user identity from any Web page of the Web application. You can use the
User.Identity object to ascertain the user identity, the IIS authentication
mechanism, or if the user is authenticated.

Question: What properties of the User.Identity object can you use to ascertain
the user identity, the IIS authentication mechanism, or if the user is authenticated?
Securing a Microsoft ASP.NET Web Application 16-13

MCT USE ONLY. STUDENT USE PROHIBITED


Lesson 3
Forms-Based Authentication

The most common authentication method to secure ASP.NET Web applications is


Forms-based authentication.
This lesson describes Forms-based architecture and explains the steps that you use
to enable Forms-based authentication. It also demonstrates how to set up security
in the web.config file and create a logon page.
16-14 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Overview of Forms-Based Authentication

Key Points
When a user requests a Web page that is protected by Forms-based authentication,
the request must first go through IIS. Therefore, you must set IIS authentication to
Anonymous access.
Securing a Microsoft ASP.NET Web Application 16-15

MCT USE ONLY. STUDENT USE PROHIBITED


Multimedia: Forms-Based Authentication

Key Points
In this animation, you will see the implementation of Forms-based authentication
with a non-authenticated client and with an authenticated client.
16-16 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Enabling Forms-Based Authentication

Key Points
To enable Forms-based authentication for your Web application:
1. Enable Forms-based authentication by configuring IIS to use Anonymous
authentication so that the user is authenticated by ASP.NET and not by IIS.
2. Set up authentication in the <authentication> section of the web.config file.
3. Set up authorization in the <authorization> section of the web.config file.
4. Create a logon Web Form.

Question: How do you configure the <authentication> and <authentication>


sections?
Securing a Microsoft ASP.NET Web Application 16-17

MCT USE ONLY. STUDENT USE PROHIBITED


Creating a Logon Page

Key Points
You can easily create a logon page by using the Login control.
ASP.NET provides other login controls that you can access from the Toolbox in
Microsoft Visual Studio®.

Question: What ASP.NET login controls can you add to a Web Form?
16-18 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Demonstration: Forms-Based Authentication

Question: How can you configure Forms-based authentication?


Securing a Microsoft ASP.NET Web Application 16-19

MCT USE ONLY. STUDENT USE PROHIBITED


Lab: Securing a Microsoft ASP.NET Web
Application

Exercise 1: Securing Your Web Site by Using Windows-


Based Authentication
Scenario
Coho Winery offers several benefits to its employees.
Now that you have implemented all of the benefits, you want to allow only
registered users to access the Web site. In this lab, you will first secure the site by
using Windows-based authentication. You will then change the Web site to use
Forms-based authentication. Finally, you will implement the registration page to
enable users to register with your Web site.
In this exercise, you will set up IIS to use Basic authentication to gain access to
secure pages and use Anonymous authentication to gain access to non-secured
pages. You will then edit the web.config file to deny non-authenticated users access
to the medical.aspx and doctors.aspx pages. Finally, you will deny non-
authenticated users access to any page of the Coho Winery Web site.
16-20 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


The main tasks for this exercise are as follows:
1. Open the Benefits Web site and DentalService Web service.
2. Add a page to output the security information.
3. Configure security in the web.config file for two of the pages in the Benefits
project.
4. Prepare the project for deployment.
5. Publish the DentalService Web service.
6. Recreate the Web reference to the DentalService Web service.
7. Publish the Benefits Web site
8. Configure IIS authentication.
9. Test Windows-based authentication for two pages.
10. Configure the security for the Benefits Web site folder in the web.config file.
11. Test Windows-based authentication for the entire site.

f Task 1: Open the Benefits Web site and DentalService Web service
1. Open Microsoft Visual Studio® 2008.
2. Open the Benefits Web site from E:\Labfiles\Starter\CS\Benefits or
E:\Labfiles\Starter\VB\Benefits.
Visual Studio 2008 opens the Benefits solution. This solution contains a Web
site also named Benefits.
3. Add the DentalService project from E:\Labfiles\Starter\CS\DentalService or
E:\Labfiles\Starter\VB\DentalService to the solution.

f Task 2: Add a page to output the security information


1. Add the securitytest.aspx file from the E:\Labfiles\Starter\CS\ or
E:\Labfiles\Starter\VB\ folder to the Web site.
2. Open the code-behind file for the securitytest.aspx page, and then examine its
contents.
In the Page_Load event procedure, the code sets two labels to display the
identity (username or domain\username) of the authenticated user and the
authentication mechanism that authenticates the user.
Securing a Microsoft ASP.NET Web Application 16-21

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 3: Configure security in the web.config file for two of the pages
in the Benefits project
1. Open the web.config file for the Benefits Web site.
2. In the web.config file, locate the <authentication> section, and then verify that
the mode is set to Windows authentication.
3. Deny access to anonymous users for the medical.aspx and the doctors.aspx
pages. At the end of the web.config file, enter your configuration after the
</system.webServer> tag but before the </configuration> tag.

f Task 4: Prepare the project for deployment


1. In Solution Explorer, select Solution 'Benefits'.
2. On the Standard toolbar, in the Solution Configurations list, click Release.
3. On the Build menu, click Rebuild Solution.
4. In the Save File As dialog box, click Save.
5. Click Start, point to All Programs, expand the Microsoft Visual Studio 2008
folder, expand the Visual Studio Tools folder, and then click Visual Studio
2008 Command Prompt.
A Command Prompt window opens.
6. At the command prompt, type the following command, and then press
ENTER.

aspnet_regsql -S LONDON\SQLExpress -E -ssadd

You must perform this step because the ASPState database does not exist in
the virtual machine for this lab.
7. Close the command prompt window.

f Task 5: Publish the DentalService Web service


1. In Solution Explorer, click the DentalService project.
2. On the Build menu, click Publish DentalService.
3. In the Publish Web dialog box, in the Target location box, type
E:\DentalService and then click Publish.
16-22 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


4. On the Start menu, in the Start Search box, type inetmgr and then press
ENTER.
5. In the User Account Control dialog box, click Continue.
The Internet Information Services (IIS) Manager dialog box opens.
6. In the Internet Information Services (IIS) Manager dialog box, expand the
local computer, and then expand Web Sites.
7. Right-click Default Web Site, and then click Add Application.
8. In the Add Application dialog box, in the Alias box, type DentalService
9. In the Physical path box, type E:\DentalService and then click OK.
10. Minimize the Internet Information Services (IIS) Manager dialog box.

f Task 6: Recreate the Web reference to the DentalService Web service


1. In Solution Explorer, in the Benefits Web site, expand App_WebReferences.
2. Right-click DentalWebRef, and then click Delete.
3. In the confirmation dialog box, click OK.
4. In Solution Explorer, right-click the Benefits Web site, and then click Add
Web Reference.
5. In the Add Web Reference dialog box, in the URL box, type
http://localhost/DentalService/DentalService1.asmx and then click Go.
6. In the Web reference name box, type DentalWebRef and then click Add
Reference.
7. In Solution Explorer, right-click the Benefits Web site, and then click Build
Web Site.

f Task 7: Publish the Benefits Web site


1. In Solution Explorer, click the Benefits Web site.
2. On the Build menu, click Publish Web Site.
3. In the Publish Web Site dialog box, in the Target location box, type
E:\Benefits
4. Clear the Allow this precompiled site to be updatable check box and then
click OK.
Securing a Microsoft ASP.NET Web Application 16-23

MCT USE ONLY. STUDENT USE PROHIBITED


5. Restore the Internet Information Services Manager dialog box.
6. In the Internet Information Services Manager dialog box, right-click Default
Web Site, and then click Add Application.
7. In the Add Application dialog box, in the Alias box, type Benefits
8. In the Physical path box, type E:\Benefits and then click OK.

f Task 8: Configure IIS authentication


1. In Internet Information Services (IIS) Manager:
• Verify that Anonymous Authentication is enabled and Windows
Authentication is disabled for the Benefits Web site.
• Enable Basic Authentication for the Benefits Web site.
2. Minimize Internet Information Services (IIS) Manager.

Security Note: Anonymous access is enabled so that you can have both secure and
non-secure pages in the same Web application. For this exercise, Basic
authentication has been enabled without the use of Secure Sockets Layer (SSL);
therefore, passwords are sent by using clear text. In a real-world scenario, to be
secure, you must obtain a server certificate and implement SSL when you use Basic
authentication.

f Task 9: Test Windows-based authentication for two pages


1. In a new browser, browse to http://localhost/Benefits/default.aspx.
2. In the browser, click Life Insurance, and then verify that the life.aspx page
opens and does not request your user credentials.
3. In the Address bar of the browser, change the page name from life.aspx to
securitytest.aspx, and then press ENTER.
No authentication information is displayed on this page because you are not
yet authenticated.
4. In the Address bar of the browser, change the page name from
securitytest.aspx to medical.aspx, and then press ENTER.
The Connect to localhost dialog box appears.
16-24 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


5. Enter your user name and your classroom password.
You are now able to browse the medical.aspx page.
6. In the Address bar of the browser, change the page name from medical.aspx
to securitytest.aspx, and then press ENTER.
The page now displays your authentication information. If your authentication
information is not displayed, refresh the page.
7. Close the browser.

f Task 10: Configure the security for the Benefits Web site folder in the
web.config file
1. Open the web.config file for the Benefits Web site.
2. Deny access to anonymous users of the entire Benefits Web site by
commenting out the two <location> elements that you previously added in the
web.config file and creating a new <authorization> element just after the
<authentication> element.

f Task 11: Test Windows-based authentication for the entire site


1. Build the Web site and publish it to E:\Benefits.
2. In a new browser, browse to http://localhost/Benefits/default.aspx.

Note: Ensure that you open a new browser. If you are still on the previous
authenticated session, you will not be able to test if the security works.

When you first browse the Web site, a dialog box prompts you for your
credentials because all of the pages are secure, including Default.aspx.
3. Enter your user name and your classroom password.
You can now browse all of the pages of the Benefits Web site.

Results: After this exercise, you have used Basic authentication to gain access to secure
pages, used Anonymous authentication to gain access to non-secured pages, and
denied non-authenticated users access to any page of your Web site.
Securing a Microsoft ASP.NET Web Application 16-25

MCT USE ONLY. STUDENT USE PROHIBITED


Exercise 2: Securing Your Web Site by Using Forms-Based
Authentication
Scenario
In this exercise, you will reconfigure IIS to use Anonymous authentication only.
You will then use Forms-based authentication to manage access to secure pages in
the Benefits Web site. You will configure the web.config file to use Forms-based
authentication by denying non-authenticated users access to any page of the
Benefits project folder. Finally, you will create the login.aspx page and validate user
credentials for users of your Web site.
The main tasks for this exercise are as follows:
1. Configure IIS to use only Anonymous authentication.
2. Configure Forms-based authentication in the web.config file.
3. Add a login.aspx Web Form to enter the credentials.
4. Test Forms-based authentication.

f Task 1: Configure IIS to use only Anonymous authentication


1. Switch to Internet Information Services (IIS) Manager.
2. In Internet Information Services (IIS) Manager for the Benefits Web site:
• Verify that Anonymous Authentication is enabled.
• Disable Basic Authentication.
3. Close the Computer Management console.

f Task 2: Configure Forms-based authentication in the web.config file


1. Switch to Visual Studio 2008.
2. Open the web.config file.
3. In the web.config file, locate the <authentication> section, and then modify it
to use Forms-based authentication. You must create a cookie named
.ASPXAUTH and redirect the user to a page named login.aspx if the user is not
authenticated.
16-26 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 3: Add a login.aspx Web Form to enter the credentials
1. Add the login.aspx file from the E:\Labfiles\Starter\CS\ or
E:\Labfiles\Starter\VB\ folder to the Web site.
This page contains a title for the Web site and a hyperlink to redirect the user
to a page that creates a new user.
2. Add a Login control named benefitsLogin to the center of the Web Form.

f Task 4: Test Forms-based authentication


1. Build the Web site and publish it to E:\Benefits.
2. In a new browser, browse to http://localhost/Benefits/default.aspx.
You are redirected to the login.aspx page because all of the pages are secure,
including Default.aspx.
3. Investigate the URL in the browser.
The requested page (Default.aspx) is added to the URL. This additional
information in the URL is used to redirect an authenticated user to the
requested page (Default.aspx in this scenario) after the user enters the
necessary credentials.
4. Enter your classroom user name and password, and then click Log In.
Because you are not a user of the Web site, you are denied access. In the next
exercise, you will add functionality to register new users with the Web site.
5. Close the browser.

Security Note: When you use Forms-based authentication, the password that that is
entered in the login page is sent in plain text over the network. In a real-world
scenario, to prevent the possibility of someone obtaining the password, you must
use an SSL connection.

Results: After this exercise, you have used Anonymous authentication and Forms-
based authentication to manage access to secure pages in your Web site.
Securing a Microsoft ASP.NET Web Application 16-27

MCT USE ONLY. STUDENT USE PROHIBITED


Exercise 3: Registering New Users
Scenario
In this exercise, you will add a register.aspx page to enable users to register with
your Web site.
The main tasks for this exercise are as follows:
1. Add a register.aspx Web Form to register new users.
2. Attempt to register a new user.
3. Configure the security for the register.aspx page in the web.config file.
4. Test authorized access to the register.aspx page.

f Task 1: Add a register.aspx Web Form to register new users


1. Add the register.aspx file from the E:\Labfiles\Starter\CS\ or
E:\Labfiles\Starter\VB\ folder to the Web site.
This page contains a title for the Web site.
2. Add a CreateUserWizard control named benefitsCreateUserWizard to the
center of the Web Form.
3. Create a CreatedUser event handler for the benefitsCreateUserWizard
control.
4. In the benefitsCreateUserWizard_CreatedUser event handler, write code to
authenticate users, create a temporary (non-persistent) authentication cookie
by using the UserName property of the control, and then redirect the user to
the Default.aspx page.
5. Consider why you call the SetAuthCookie method here and not
RedirectFromLoginPage.
You call the SetAuthCookie method because you want to redirect users to the
Default.aspx Web Form. Usually, the register.aspx Web Form is called from a
link in the login.aspx Web Form. The RedirectFromLoginPage method
redirects a newly registered and authenticated user to the login.aspx Web
Form, which makes no sense.
16-28 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


f Task 2: Attempt to register a new user
1. Build the Web site and publish it to E:\Benefits.
2. In a new browser, browse to http://localhost/Benefits/default.aspx.
You are promptly redirected to the login.aspx page because all of the pages are
secure; therefore, Default.aspx is a secure page.
3. In the browser, click the Register New User link to open the register.aspx
page to register a new employee.
You remain on the login.aspx page because the register.aspx page is also
declared as a secure page in the web.config file. Non-authenticated employees
are denied access to all pages. However, access to the login.aspx page is
authorized because you declared it in the <authentication> section as the
login page when you configured Windows authentication.
To enable users to access the register.aspx page, you must authorize access to
the register.aspx page in the web.config file.
4. Close the browser.

f Task 3: Configure the security for the register.aspx page in the


web.config file
1. Open the web.config file for the Benefits Web site.
2. Enter the configuration information to authorize everyone to access the
register.aspx page. Place this information at the end of the web.config file, just
after the </system.webServer> tag but before the </configuration> tag.

f Task 4: Test authorized access to the register.aspx page


1. Build the Web site and publish it to E:\Benefits.
2. In a new browser, browse to http://localhost/Benefits/default.aspx.
You are redirected to the login.aspx page.
3. In the browser, click Register New User to open the register.aspx Web Form
and register a new employee.
The register.aspx Web Form appears.
4. Enter the details to register yourself as a new employee, and then click Create
User.
Securing a Microsoft ASP.NET Web Application 16-29

MCT USE ONLY. STUDENT USE PROHIBITED


You are redirected to the Default.aspx page and can browse all of the pages.
5. In the browser, click the Life Insurance link, and then verify that the life.aspx
page opens and does not request your user credentials.
6. In the Address bar of the browser, change the page name from life.aspx to
securitytest.aspx, and then press ENTER.
The page displays your user name and shows that you are authenticated with
Forms-based authentication.
7. Close the browser.
8. In a new browser, browse to http://localhost/Benefits/default.aspx.
9. On the login.aspx page, log on with your credentials.
10. Close the browser.

Results: After this exercise, you have added a page to enable users to register with
your Web site.
16-30 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Module Review and Takeaways

Review Questions
1. What authentication methods does ASP.NET provide?
2. What is the difference between authentication and authorization?
3. What must you do when you use Basic authentication?
4. What happens to unauthenticated users when they attempt to access a secure
page, and where is the originally requested URL stored?

Best Practices related to security


Supplement or modify the following best practices for your own work situations:
• You can configure multiple authentication mechanisms in IIS. If you use
multiple IIS authentication mechanisms and Anonymous authentication fails,
the Web server attempts to use Basic, Digest, or Integrated Windows security
authentication, according to what you have selected.
Securing a Microsoft ASP.NET Web Application 16-31

MCT USE ONLY. STUDENT USE PROHIBITED


• Forms-based authentication sends user passwords over the network in clear
text. It is important to use SSL to encrypt these passwords. You can also use
SSL to prevent one Web site from impersonating another.
• If you want your Web application to be compatible with Netscape browsers,
you should use Basic authentication. If you do not use a firewall or proxy
server, you can use Integrated Windows security.
• It is not advisable to authorize users individually or hard code users in the
web.config file.

Tools

Tool Use for Where to find it


Internet Information • Provides scalable and secure Computer
Services (IIS) Web server capabilities over an Management console
intranet, the Internet, or an or command prompt
extranet.
16-32 Developing Web Applications Using Microsoft® Visual Studio® 2008

MCT USE ONLY. STUDENT USE PROHIBITED


Course Evaluation

Your evaluation of this course will help Microsoft understand the quality of your
learning experience.
Please work with your training provider to access the course evaluation form.
Microsoft will keep your answers to this survey private and confidential and will
use your responses to improve your future learning experience. Your open and
honest feedback is valuable and appreciated.

You might also like