2310CK-En Developing Web Apps VS2008-TrainerManual2
2310CK-En Developing Web Apps VS2008-TrainerManual2
2310C
Developing Web Applications
Using Microsoft® Visual Studio®
2008
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.
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
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
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
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
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.
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.
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
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
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
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
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
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
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
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
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
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.
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
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
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.
[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
doctorsConnection.Open()
citiesSqlDataReader = citiesSqlCommand.ExecuteReader()
citiesList.DataSource = citiesSqlDataReader
citiesList.DataTextField = "city"
citiesList.DataBind()
citiesSqlDataReader.Close()
doctorsConnection.Close()
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
Note: You can copy some of the preceding code from the lines that you previously
commented out.
[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()
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.
[Visual C#]
CreateDataSet();
string drID;
drID = doctorsGridView.SelectedRow.Cells[1].Text;
9-24 Developing Web Applications Using Microsoft® Visual Studio® 2008
[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
[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
[Visual C#]
SqlDataReader specialtiesSqlDataReader;
doctorsConnection.Open();
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader();
[Visual Basic]
Dim specialtiesSqlDataReader As SqlDataReader
doctorsConnection.Open()
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader()
DataSource specialtiesSqlDataReader
DataTextField "Specialty"
[Visual C#]
specialtiesListBox.DataSource = specialtiesSqlDataReader;
specialtiesListBox.DataTextField = "Specialty";
specialtiesListBox.DataBind();
[Visual Basic]
specialtiesListBox.DataSource = specialtiesSqlDataReader
specialtiesListBox.DataTextField = "Specialty"
specialtiesListBox.DataBind()
[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
[Visual Basic]
specialtiesSqlDataReader.Close()
doctorsConnection.Close()
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.
Note: You can copy these lines of code from the commented-out lines in the event
procedure.
[Visual C#]
string drID;
drID = doctorsGridView.SelectedRow.Cells[1].Text;
if (specialtiesListBox.Items.Count != 0)
{
specialtiesListBox.Visible = true;
specialtiesLabel.Visible = true;
}
[Visual Basic]
Dim drID As String
drID = doctorsGridView.SelectedRow.Cells.Item(1).Text
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
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?
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
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
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
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.
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
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.
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
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
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: How can you tell that the XML data is nested?
10-12 Developing Web Applications Using Microsoft® Visual Studio® 2008
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
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.
Key Points
You can synchronize a DataSet with an XmlDataDocument by storing XML data
in an XmlDataDocument or a DataSet in 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
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.
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
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
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
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.
Results: After this exercise, you have implemented an Xml control to read, transform,
and display a prospectus for a sp mutual fund.
[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
[Visual C#]
//myDataRelation1.Nested = true;
[Visual Basic]
'myDataRelation1.Nested = True
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
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.
Results: After this exercise, you have experimented with nested XML data from a SQL
Server database.
Reading and Writing XML Data 10-29
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?
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
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
Question: What benefits can ASP.NET AJAX provide for your own Web
applications?
11-6 Developing Web Applications Using Microsoft® Visual Studio® 2008
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
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
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
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
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
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
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
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.
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
Results: After this exercise, you have implemented partial-page rendering in the
doctors.aspx page.
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.
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
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?
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).
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
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.
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.
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
Key Points
Visual Studio 2008 provides templates that you can use to create Silverlight
applications and class libraries.
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.
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
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.
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.
Height 70 60
12-16 Developing Web Applications Using Microsoft® Visual Studio® 2008
Width 100 60
Canvas.Left 20 40
Canvas.Top 15 20
4. Add two TextBlock objects to the Canvas, and then set the properties as
follows.
FontSize 50 30
Canvas.Left 55 150
Canvas.Top 20 30
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
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
[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 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.
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
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
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?
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
dentistsConnection SqlConnection
dentistsDataSet DataSet
dentistsSqlDataAdapter SqlDataAdapter
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.
Attribute Value
Namespace http://microsoft.com/webservices/
Description This XML Web service contains information about the dentists
[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
Results: After this exercise, you have created and tested the GetAllDentists Web
service method.
Note: You can copy and paste this code from the file
E:\Labfiles\Starter\DentistsPoCodeCS.txt or E:\Labfiles\Starter\DentistsPoCodeVB.txt.
Results: After this exercise, you have created the GetDentistsByPostalCode XML Web
Service method.
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
Results: After this exercise, you have consumed the GetAllDentists XML Web Service
method.
TODO Lab 13: call the XML Web service method GetDentistsByPostalCode
Results: After this exercise, you have consumed the GetDentistsByPostalCode XML
Web Service method.
13-26 Developing Web Applications Using Microsoft® Visual Studio® 2008
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?
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
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
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
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
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
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
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
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
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.
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
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
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
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
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
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.
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
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.
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
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.
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
[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 = ""
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.
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
[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();
}
[Visual Basic]
If Not Page.IsPostBack Then
Application.Lock()
Application("Visits") = CInt(Application("Visits")) + 1
Application.UnLock()
End If
Results: After this exercise, you have added a page counter to the retirement.aspx
page.
Attribute Value
Mode SQLServer
cookieless false
Timeout 20
<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.
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
Results: After this exercise, you have stored the user name and birth date session
variables in a SQL Server database.
Managing State 14-33
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?
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.
• 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
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
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
Question: How can the Cache object help to increase the speed of your
application?
15-6 Developing Web Applications Using Microsoft® Visual Studio® 2008
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
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
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
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
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
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
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
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
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.
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
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
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
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
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
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
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
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
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
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
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
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
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.
[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.
Absolute Expiration 4 4
[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
[Visual C#]
doctorsGridView.DataSource = SqlDataSource1;
[Visual Basic]
doctorsGridView.DataSource = SqlDataSource1
Results: After this exercise, you have used the Cache object to cache the DataSet
object doctors.
[Visual C#]
doctorTextBox.Text = Request.QueryString["pcp"];
15-32 Developing Web Applications Using Microsoft® Visual Studio® 2008
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
Results: After this exercise, you have cached a Web Form by using the OutputCache
directive.
Results: After this exercise, you have used the page output cache to cache the user
control header.ascx.
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.
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
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?
Tools
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
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
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.
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.
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.
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 enable and disable the authentication mechanisms in IIS?
Securing a Microsoft ASP.NET Web Application 16-9
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
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
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.
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
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
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
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.
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
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.
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.
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 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.
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
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
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
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?
Tools
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.