Professional Documents
Culture Documents
Course 10267A Introduction To Web Development With Microsoft Visual Studio 2010 Trainer Handbook
Course 10267A Introduction To Web Development With Microsoft Visual Studio 2010 Trainer Handbook
10267A
Introduction to Web
Development with Microsoft®
Visual Studio® 2010
Volume 1
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for
any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory,
regarding these manufacturers or the use of the products with any Microsoft technologies. The
inclusion of a manufacturer or product does not imply endorsement of Microsoft of the
manufacturer or product. Links may be provided to third party sites. Such sites are not under the
control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link
contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for
webcasting or any other form of transmission received from any linked site. Microsoft is providing
these links to you only as a convenience, and the inclusion of any link does not imply endorsement
of Microsoft of the site or the products contained therein.
© 2010 Microsoft Corporation. All rights reserved.
Microsoft, Microsoft Press, Access, Active Directory, Azure, Excel, Expression, Expression Blend,
Hyper-V, IntelliSense, Internet Explorer, Jscript, MS, MSDN, Outlook, PerformancePoint, PowerPoint,
SharePoint, Silverlight, SQL Server, Verdana, Visio, Visual Basic, Visual C#, Visual C++, Visual J#,
Visual Studio, Windows, Windows Azure, Windows Live, Windows Server, and Windows Vista are
either registered trademarks or trademarks of Microsoft Corporation in the United States and/or
other countries.
Released: 07/2010
MICROSOFT LICENSE TERMS
OFFICIAL MICROSOFT LEARNING PRODUCTS - TRAINER
EDITION – Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They
apply to the Licensed Content named above, which includes the media on which you received it, if any. The
terms also apply to any Microsoft
• updates,
• supplements,
• Internet-based services, and
• support services
for this Licensed Content, unless other terms accompany those items. If so, those terms apply.
By using the Licensed Content, you accept these terms. If you do not accept them, do not use
the Licensed Content.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Academic Materials” means the printed or electronic documentation such as manuals,
workbooks, white papers, press releases, datasheets, and FAQs which may be included in the
Licensed Content.
b. “Authorized Learning Center(s)” means a Microsoft Certified Partner for Learning Solutions
location, an IT Academy location, or such other entity as Microsoft may designate from time to time.
c. “Authorized Training Session(s)” means those training sessions authorized by Microsoft and
conducted at or through Authorized Learning Centers by a Trainer providing training to Students
solely on Official Microsoft Learning Products (formerly known as Microsoft Official Curriculum or
“MOC”) and Microsoft Dynamics Learning Products (formerly know as Microsoft Business Solutions
Courseware). Each Authorized Training Session will provide training on the subject matter of one
(1) Course.
d. “Course” means one of the courses using Licensed Content offered by an Authorized Learning
Center during an Authorized Training Session, each of which provides training on a particular
Microsoft technology subject matter.
e. “Device(s)” means a single computer, device, workstation, terminal, or other digital electronic or
analog device.
f. “Licensed Content” means the materials accompanying these license terms. The Licensed
Content may include, but is not limited to, the following elements: (i) Trainer Content, (ii) Student
Content, (iii) classroom setup guide, and (iv) Software. There are different and separate
components of the Licensed Content for each Course.
g. “Software” means the Virtual Machines and Virtual Hard Disks, or other software applications that
may be included with the Licensed Content.
h. “Student(s)” means a student duly enrolled for an Authorized Training Session at your location.
i. “Student Content” means the learning materials accompanying these license terms that are for
use by Students and Trainers during an Authorized Training Session. Student Content may include
labs, simulations, and courseware files for a Course.
j. “Trainer(s)” means a) a person who is duly certified by Microsoft as a Microsoft Certified Trainer
and b) such other individual as authorized in writing by Microsoft and has been engaged by an
Authorized Learning Center to teach or instruct an Authorized Training Session to Students on its
behalf.
k. “Trainer Content” means the materials accompanying these license terms that are for use by
Trainers and Students, as applicable, solely during an Authorized Training Session. Trainer Content
may include Virtual Machines, Virtual Hard Disks, Microsoft PowerPoint files, instructor notes, and
demonstration guides and script files for a Course.
l. “Virtual Hard Disks” means Microsoft Software that is comprised of virtualized hard disks (such as
a base virtual hard disk or differencing disks) for a Virtual Machine that can be loaded onto a single
computer or other device in order to allow end-users to run multiple operating systems concurrently.
For the purposes of these license terms, Virtual Hard Disks will be considered “Trainer Content”.
m. “Virtual Machine” means a virtualized computing experience, created and accessed using
Microsoft® Virtual PC or Microsoft® Virtual Server software that consists of a virtualized hardware
environment, one or more Virtual Hard Disks, and a configuration file setting the parameters of the
virtualized hardware environment (e.g., RAM). For the purposes of these license terms, Virtual Hard
Disks will be considered “Trainer Content”.
n. “you” means the Authorized Learning Center or Trainer, as applicable, that has agreed to these
license terms.
2. OVERVIEW.
Licensed Content. The Licensed Content includes Software, Academic Materials (online and
electronic), Trainer Content, Student Content, classroom setup guide, and associated media.
License Model. The Licensed Content is licensed on a per copy per Authorized Learning Center
location or per Trainer basis.
3. INSTALLATION AND USE RIGHTS.
a. Authorized Learning Centers and Trainers: For each Authorized Training Session, you
may:
i. either install individual copies of the relevant Licensed Content on classroom Devices only for
use by Students enrolled in and the Trainer delivering the Authorized Training Session, provided
that the number of copies in use does not exceed the number of Students enrolled in and the
Trainer delivering the Authorized Training Session, OR
ii. install one copy of the relevant Licensed Content on a network server only for access by
classroom Devices and only for use by Students enrolled in and the Trainer delivering the
Authorized Training Session, provided that the number of Devices accessing the Licensed
Content on such server does not exceed the number of Students enrolled in and the Trainer
delivering the Authorized Training Session.
iii. and allow the Students enrolled in and the Trainer delivering the Authorized Training Session to
use the Licensed Content that you install in accordance with (ii) or (ii) above during such
Authorized Training Session in accordance with these license terms.
i. Separation of Components. The components of the Licensed Content are licensed as a single
unit. You may not separate the components and install them on different Devices.
ii. Third Party Programs. The Licensed Content may contain third party programs. These license
terms will apply to the use of those third party programs, unless other terms accompany those
programs.
b. Trainers:
i. Trainers may Use the Licensed Content that you install or that is installed by an Authorized
Learning Center on a classroom Device to deliver an Authorized Training Session.
ii. Trainers may also Use a copy of the Licensed Content as follows:
A. Licensed Device. The licensed Device is the Device on which you Use the Licensed Content.
You may install and Use one copy of the Licensed Content on the licensed Device solely for
your own personal training Use and for preparation of an Authorized Training Session.
B. Portable Device. You may install another copy on a portable device solely for your own
personal training Use and for preparation of an Authorized Training Session.
4. PRE-RELEASE VERSIONS. If this is a pre-release (“beta”) version, in addition to the other provisions
in this agreement, these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not
contain the same information and/or work the way a final version of the Licensed Content will. We
may change it for the final, commercial version. We also may not release a commercial version.
You will clearly and conspicuously inform any Students who participate in each Authorized Training
Session of the foregoing; and, that you or Microsoft are under no obligation to provide them with
any further content, including but not limited to the final released version of the Licensed Content
for the Course.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, you give to
Microsoft, without charge, the right to use, share and commercialize your feedback in any way and
for any purpose. You also give to third parties, without charge, any patent rights needed for their
products, technologies and services to use or interface with any specific parts of a Microsoft
software, Licensed Content, or service that includes the feedback. You will not give feedback that is
subject to a license that requires Microsoft to license its software or documentation to third parties
because we include your feedback in them. These rights survive this agreement.
c. Confidential Information. The Licensed Content, including any viewer, user interface, features
and documentation that may be included with the Licensed Content, is confidential and proprietary
to Microsoft and its suppliers.
i. Use. For five years after installation of the Licensed Content or its commercial release,
whichever is first, you may not disclose confidential information to third parties. You may
disclose confidential information only to your employees and consultants who need to know
the information. You must have written agreements with them that protect the confidential
information at least as much as this agreement.
ii. Survival. Your duty to protect confidential information survives this agreement.
iii. Exclusions. You may disclose confidential information in response to a judicial or
governmental order. You must first give written notice to Microsoft to allow it to seek a
protective order or otherwise protect the information. Confidential information does not
include information that
• becomes publicly known through no wrongful act;
• you received from a third party who did not breach confidentiality obligations to
Microsoft or its suppliers; or
• you developed independently.
d. Term. The term of this agreement for pre-release versions is (i) the date which Microsoft informs
you is the end date for using the beta version, or (ii) the commercial release of the final release
version of the Licensed Content, whichever is first (“beta term”).
e. Use. You will cease using all copies of the beta version upon expiration or termination of the beta
term, and will destroy all copies of same in the possession or under your control and/or in the
possession or under the control of any Trainers who have received copies of the pre-released
version.
f. Copies. Microsoft will inform Authorized Learning Centers if they may make copies of the beta
version (in either print and/or CD version) and distribute such copies to Students and/or Trainers. If
Microsoft allows such distribution, you will follow any additional terms that Microsoft provides to you
for such copies and distribution.
5. ADDITIONAL LICENSING REQUIREMENTS AND/OR USE RIGHTS.
a. Authorized Learning Centers and Trainers:
i. Software.
ii. Virtual Hard Disks. The Licensed Content may contain versions of Microsoft XP, Microsoft
Windows Vista, Windows Server 2003, Windows Server 2008, and Windows 2000 Advanced
Server and/or other Microsoft products which are provided in Virtual Hard Disks.
A. If the Virtual Hard Disks and the labs are launched through the Microsoft
Learning Lab Launcher, then these terms apply:
Time-Sensitive Software. If the Software is not reset, it will stop running based upon the
time indicated on the install of the Virtual Machines (between 30 and 500 days after you
install it). You will not receive notice before it stops running. You may not be able to
access data used or information saved with the Virtual Machines when it stops running and
may be forced to reset these Virtual Machines to their original state. You must remove the
Software from the Devices at the end of each Authorized Training Session and reinstall and
launch it prior to the beginning of the next Authorized Training Session.
B. If the Virtual Hard Disks require a product key to launch, then these terms
apply:
Microsoft will deactivate the operating system associated with each Virtual Hard Disk.
Before installing any Virtual Hard Disks on classroom Devices for use during an Authorized
Training Session, you will obtain from Microsoft a product key for the operating system
software for the Virtual Hard Disks and will activate such Software with Microsoft using such
product key.
C. These terms apply to all Virtual Machines and Virtual Hard Disks:
You may only use the Virtual Machines and Virtual Hard Disks if you comply with
the terms and conditions of this agreement and the following security
requirements:
o You may not install Virtual Machines and Virtual Hard Disks on portable Devices or
Devices that are accessible to other networks.
o You must remove Virtual Machines and Virtual Hard Disks from all classroom Devices at
the end of each Authorized Training Session, except those held at Microsoft Certified
Partners for Learning Solutions locations.
o You must remove the differencing drive portions of the Virtual Hard Disks from all
classroom Devices at the end of each Authorized Training Session at Microsoft Certified
Partners for Learning Solutions locations.
o You will ensure that the Virtual Machines and Virtual Hard Disks are not copied or
downloaded from Devices on which you installed them.
o You will strictly comply with all Microsoft instructions relating to installation, use,
activation and deactivation, and security of Virtual Machines and Virtual Hard Disks.
o You may not modify the Virtual Machines and Virtual Hard Disks or any contents
thereof.
o You may not reproduce or redistribute the Virtual Machines or Virtual Hard Disks.
ii. Classroom Setup Guide. You will assure any Licensed Content installed for use during an
Authorized Training Session will be done in accordance with the classroom set-up guide for the
Course.
iii. Media Elements and Templates. You may allow Trainers and Students to use images, clip
art, animations, sounds, music, shapes, video clips and templates provided with the Licensed
Content solely in an Authorized Training Session. If Trainers have their own copy of the
Licensed Content, they may use Media Elements for their personal training use.
iv. iv Evaluation Software. Any Software that is included in the Student Content designated as
“Evaluation Software” may be used by Students solely for their personal training outside of the
Authorized Training Session.
b. Trainers Only:
i. Use of PowerPoint Slide Deck Templates. The Trainer Content may include Microsoft
PowerPoint slide decks. Trainers may use, copy and modify the PowerPoint slide decks only for
providing an Authorized Training Session. If you elect to exercise the foregoing, you will agree
or ensure Trainer agrees: (a) that modification of the slide decks will not constitute creation of
obscene or scandalous works, as defined by federal law at the time the work is created; and
(b) to comply with all other terms and conditions of this agreement.
ii. Use of Instructional Components in Trainer Content. For each Authorized Training
Session, Trainers may customize and reproduce, in accordance with the MCT Agreement, those
portions of the Licensed Content that are logically associated with instruction of the Authorized
Training Session. If you elect to exercise the foregoing rights, you agree or ensure the Trainer
agrees: (a) that any of these customizations or reproductions will only be used for providing an
Authorized Training Session and (b) to comply with all other terms and conditions of this
agreement.
iii. Academic Materials. If the Licensed Content contains Academic Materials, you may copy and
use the Academic Materials. You may not make any modifications to the Academic Materials
and you may not print any book (either electronic or print version) in its entirety. If you
reproduce any Academic Materials, you agree that:
• The use of the Academic Materials will be only for your personal reference or training use
• You will not republish or post the Academic Materials on any network computer or
broadcast in any media;
• You will include the Academic Material’s original copyright notice, or a copyright notice to
Microsoft’s benefit in the format provided below:
Form of Notice:
© 2010 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.
Welcome!
Thank you for taking our training! We’ve worked together with our Microsoft Certified Partners
for Learning Solutions and our Microsoft IT Academies to bring you a world-class learning
experience—whether you’re a professional looking to advance your skills or a
student preparing for a career in IT.
We wish you a great learning experience and ongoing success in your career!
Sincerely,
Microsoft Learning
www.microsoft.com/learning
1
IDC, Value of Certification: Team Certification and Organizational Performance, November 2006
Introduction to Web Development with Microsoft® Visual Studio® 2010 xiii
Acknowledgement
Microsoft Learning would like to acknowledge and thank the following for their
contribution towards developing this title. Their effort at various stages in the
development has ensured that you have a good classroom experience.
Contents
Module 1: Exploring Microsoft ASP.NET Web Applications in Microsoft Visual
Studio 2010
Lesson 1: Introduction to the .NET Framework 1-3
Lesson 2: Overview of ASP.NET 1-15
Lesson 3: Overview of the Lab Application 1-32
Course Description
This five-day instructor-led course provides knowledge and skills on developing
Web applications by using Microsoft® Visual Studio® 2010.
Audience
This course is intended for Web developers who are beginners, and have
knowledge of Hypertext Markup Language (HTML) or Dynamic HTML (DHTML),
along with some knowledge of a scripting language such as Microsoft Visual Basic®
Scripting Edition or Microsoft JScript®.
Students are required to have the following skills:
• Ability to construct a simple Web page by using a Microsoft application, or by
using a third party tool. For example, create or customize a Web page on a
Microsoft SharePoint® 2010 site.
Student Prerequisites
Students should have at least one month of experience in Microsoft .NET
technologies. In addition to their professional experience, students who attend this
training should have the following technical knowledge:
• Knowledge of HTML or DHTML, including:
• Tables
• Images
• Forms
• Programming experience using Visual Basic .NET or Microsoft Visual C#®
.NET, including:
• Declaring variables
• Using loops
• Using conditional statements
About This Course ii
Course Objectives
After completing this course, students will be able to:
• Explore Microsoft ASP.NET Web applications in Visual Studio 2010.
• Create Web applications by using Visual Studio 2010 and Microsoft .NET–
based languages.
• Create an ASP.NET Web Form.
• Add functionality to an ASP.NET Web Form.
• Implement master pages and user controls.
• Validate user input.
• Debug ASP.NET 4.0 Web applications.
• Manage data in an ASP.NET 4.0 Web application.
• Manage data access tasks by using language-integrated query (LINQ).
• Manage data by using ASP.NET Dynamic Data.
• Create an ASP.NET Ajax application.
• Consume Windows Communication Foundation (WCF) services.
• Manage state in Web applications.
• Configure and deploy an ASP.NET Web application.
• Secure an ASP.NET Web application.
• Implement new technologies supported by Visual Studio 2010 for Web
development.
About This Course iii
Course Outline
This section provides an outline of the course:
Module 1, “Exploring Microsoft ASP.NET Web Applications in Microsoft Visual
Studio 2010” explains the key features of the Microsoft .NET Framework and
Microsoft ASP.NET. This module helps you view the complete Web application
that you build in the labs throughout this course.
Module 2, “Creating Web Applications by Using Microsoft Visual Studio 2010 and
Microsoft .NET–Based Languages” describes the different programming languages
that are available when you develop Microsoft .NET Framework applications. This
module explains the fundamental aspects of writing code and creating
components by using two of the .NET Framework–based languages, Visual Basic
and Visual C#. It also provides an overview of Microsoft Visual Studio 2010, and
explains how to create a simple Web application.
Module 3, “Creating a Microsoft® ASP.NET Web Form” explains how to create
Web Forms, and then populate them with server controls.
Module 4, “Adding Functionality to a Microsoft ASP.NET Web Form” describes the
various methods that you can use to add code to your Microsoft ASP.NET Web
application. It explains how to use Web server controls, event handlers, code-
behind files, and components. In addition, it explains how to use page events,
especially the Page_Load event.
Module 5, “Implementing Master Pages and User Controls” explains how to create
and implement master pages, and how to implement user controls in a Web
application.
Module 6, “Validating User Input” provides an overview of user input validation. It
covers information on adding, positioning, and configuring validation controls on
a Web Form. In addition, it covers information on validating Web Forms.
Module 7, “Troubleshooting Microsoft ASP.NET Web Applications” describes the
steps required to enable tracing and debugging, including how you can use tracing
and debugging in a Web application.
Module 8, “Managing Data in a Microsoft ASP.NET 4.0 Web Application” provides
an overview of Microsoft ADO.NET. It explains how to programmatically work
with data by using ADO.NET, and how to create a connection to access the data
that is stored in a Microsoft SQL Server database. In addition, it explains how to
use the DataSet and DataReader objects to support the local data storage and data
manipulation requirements of Web Forms.
About This Course iv
Module 9, “Managing Data Access Tasks by Using LINQ” explains what LINQ is,
and how you can use it to manage both XML data and Microsoft SQL Server® data
in an ASP.NET Web application by using Web Server controls and code.
Module 10, “Managing Data by Using Microsoft ASP.NET Dynamic Data” provides
an overview of ASP.NET Dynamic Data, and covers information on applying
ASP.NET Dynamic Data. This module also explains how to customize ASP.NET
Dynamic Data applications.
Module 11, “Creating a Microsoft ASP.NET Ajax-Enabled Web Forms Application”
provides an overview of ASP.NET Ajax, and 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 a Web application.
Module 12, “Consuming Microsoft Windows Communication Foundation
Services” provides an overview of WCF services. It describes how to discover and
consume useful WCF services within their Web applications. Students will also
learn why and when to create their own WCF services.
Module 13, “Managing State in Web Applications” explains how to manage state in
an ASP.NET Web application.
Module 14, “Configuring and Deploying a Microsoft ASP.NET Web Application”
explains how to configure and deploy an ASP.NET Web application by using the
machine.config and web.config files.
Module 15, “Securing a Microsoft ASP.NET Web Application” explains the various
Web application security functionalities. It also covers information on the
infrastructure that is required to build and deploy various Web application security
functionalities.
Module 16, “Implementing Advanced Technologies Supported by Microsoft Visual
Studio 2010 for Web Development” describes the MVC and Microsoft Silverlight®
technologies. The student will see demonstrations of powerful technologies that
more advanced or sophisticated Web applications are implementing.
About This Course v
Course Materials
The following materials are included with your kit:
• Course Handbook. A succinct classroom learning guide that provides all the
critical technical information in a crisp, tightly-focused format, which is just
right for an effective in-class learning experience.
• Lessons: Guide you through the learning objectives, and provide the key
points that are critical to the success of the in-class learning experience.
• Labs: Provide a real-world, hands-on platform for you to apply the
knowledge and skills learned in the module.
• Course CD. Provides additional resources pertaining to this course.
• Resources: Include well-categorized additional resources that give you
immediate access to the most up-to-date premium content on TechNet,
MSDN®, Microsoft Press®
• Lab Answer Keys: Include answer keys in digital form to use during lab
time and also as PDFs for you to print.
• Virtual Machine Build Guide: Provides the step-by-step information
needed recreate the Virtual Machine/Server images with appropriate
configuration.
• Send Us Your Feedback Instructions: Provide you with an opportunity to
send feedback on the all aspects of the course.
• Student Course Files: Include the Allfiles.exe, a self-extracting executable
file that contains all the files required for the labs and demonstrations.
Note: To open the Web page, insert the Course CD into the CD-ROM drive, and
then in the root directory of the CD, double-click StartCD.exe.
• Course evaluation. At the end of the course, you will have the opportunity to
complete an online evaluation to provide feedback on the course, training
facility, and instructor.
Software Configuration
The following software is installed on each virtual machine:
• Visual Studio 2010 Professional (including .NET Framework 4.0)
• Ajax Control Toolkit
• Microsoft Silverlight 4
• Microsoft Silverlight 4 Tools for Visual Studio 2010
• Windows® Internet Explorer® 8
Course Files
There are files associated with the labs in this course. The lab files are located on
the student computers.
Classroom Setup
Each classroom computer will have the same virtual machine configured in the
same way.
Module 1
Exploring Microsoft® ASP.NET Web
Applications in Microsoft Visual Studio® 2010
Contents:
Lesson 1: Introduction to the .NET Framework 1-3
Lesson 2: Overview of ASP.NET 1-15
Lesson 3: Overview of the Lab Application 1-32
1-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
Microsoft® Visual Studio® 2010 helps you develop powerful Web applications
without an overwhelming need for coding. The Microsoft .NET Framework
provides components that modularize and simplify distributed applications
development, including Web applications. Microsoft ASP.NET is one of the
numerous technologies that are part of the .NET Framework, which you can use to
develop your Web applications.
In this module, you will learn about the key features of the .NET Framework, and
ASP.NET. You will also view a sample of the complete Web application that you
will build in the labs throughout this course.
Module Objectives
After completing this module, you will be able to:
• Describe the .NET Framework.
• Describe ASP.NET.
• Describe the lab application.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-3
Lesson 1
Introduction to the .NET Framework
You need to be aware of the terms and concepts associated with Web development
to better appreciate the choice of using Visual Studio 2010 for Web application
development. Developers face several challenges when they create Web
applications, and the .NET Framework resolves many of these problems.
In this lesson, you will learn about the .NET Framework 4, mainly in the context of
developing Web applications. You will also learn about Visual Studio 2010, the
development tool that you can use to create Web applications.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe Microsoft .NET.
• List the benefits of using the.NET Framework.
• Describe the components of the .NET Framework.
• Identify the key features of Visual Studio 2010.
1-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
The goal of Microsoft .NET is to simplify the development of Windows®
applications, Web applications, custom applications, and services. This includes
mobile applications, applications hosted in the cloud by Windows Azure™, and
applications hosted by Microsoft SQL Server® 2008. (Cloud, or cloud computing
refers to Internet based computing, where software and data is provided on
demand.) The .NET Framework is the infrastructure of Microsoft .NET.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-5
Question: What is the biggest advantage to using the .NET Framework to develop
your application?
1-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
During the early years of Windows-based application development, most
applications were developed using the Windows application programming
interface (API), and typically by using the C or C++ programming languages.
Desktop applications were created for office productivity, home computing, and
gaming. With the introduction of Microsoft Visual Basic® and the Internet,
developers had to specialize in the type of applications that they developed. For
example, developers had to specialize in developing applications in C or C++,
Visual Basic, or Visual Basic scripting for use with classic Active Server Pages (ASP).
Today, with the .NET Framework, you can use your skills to develop any type of
application, and choose the programming language of your choice.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-7
The .NET Framework provides several benefits for developing applications and
services. These benefits include:
• Web standards and practices. The .NET Framework fully supports
existing Internet technologies, including HTML, Extensible Hypertext Markup
Language (XHTML), Hypertext Transfer Protocol (HTTP), XML, Simple
Object Access Protocol (SOAP), Extensible Stylesheet Language
Transformation (XSLT), XML Path Language (XPath), and other Web
standards.
• Unified application models. The functionality of a .NET type is available to all
.NET-based applications, whether Windows-based or Web-based.
• Ease of use. The .NET Framework organizes code in hierarchical namespaces
and classes, and provides a common type system that any .NET-compatible
language can use.
• Extensible classes. The hierarchy of the .NET Framework classes is open to the
developer. You can access and extend .NET classes through inheritance,
interfaces, or extensions.
• By providing a comprehensive and consistent programming model and a
common set of APIs, the .NET Framework helps you to build applications that
work the way you want, in the programming language you prefer, across
platforms, software, services, and devices.
• Easier installation of commercial applications. Many applications from
Microsoft and third-party vendors use the .NET Framework to support their
core functionality. If you have the .NET Framework installed on your local
computer, these applications are easier to install.
• Easier updates. The Windows Update service updates the .NET Framework
automatically. If you receive Automatic Updates from Windows Update, the
version of the .NET Framework that is installed on the computer will be
updated with the latest fixes and service packs.
1-8 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Device support. The .NET Framework has two separate editions that are built
to run on different devices: The .NET Compact Framework
(http://go.microsoft.com/fwlink/?LinkID=192006&clcid=0x409) is a
hardware-independent environment that supports building and running
managed applications on resource-constrained computing devices.
The .NET Micro Framework (http://go.microsoft.com/fwlink
/?LinkID=192007&clcid=0x409) provides support for smaller devices. You
can now extend your applications and services uniformly—from very small
devices, to servers, to the cloud—by using the same programming model and
tool chain throughout.
Question: What are the main advantages of using the .NET Framework to develop
Web applications?
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-9
Key Points
The .NET environment consists of various components that help you build and
run .NET–based applications.
• Operating system. The .NET Framework must run on an operating system.
• Common language runtime. The common language runtime (CLR) is the
virtual machine component of the .NET Framework that provides core services
such as memory management, thread management, exception handling,
garbage collection, and security. The CLR component manages code at run
time, and enforces security by awarding varying degrees of trust to a
component, depending on a number of factors—such as the origin of the
component. It promotes robustness by implementing a strict type-and-code-
verification infrastructure called the common type system. Managed code is run
under the management of CLR, while unmanaged code does not target the
common language runtime.
1-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: For more information about ADO.NET, see Module 8, "Managing Data in a
Microsoft ASP.NET 4.0 Web Application."
Note: For more information about WCF, see Module 12, "Consuming Windows
Communication Foundation Services."
Application Hosting
The CLR manages the execution of code for a variety of applications and services.
However, each type of application requires a runtime host to start it. The runtime
host loads the runtime into a process, creates the application domains within the
process, and loads user code into the application domains. The .NET Framework
not only provides several runtime hosts, it also supports the development of third-
party runtime hosts. Microsoft-provided runtime hosts are listed in the following
table.
ASP.NET Loads the common language runtime into the process that is to
handle the Web request. ASP.NET also creates an application
domain for each Web application that will run on a Web server.
Windows Internet Creates application domains to run managed controls. The .NET
Explorer® Framework supports the download and execution of browser-
based controls. The runtime interfaces with the Internet Explorer
extensibility mechanism by using a Multipurpose Internet Mail
Extension (MIME) filter to create application domains to run the
managed controls. By default, one application domain is created
for each Web site.
Shell executables Invokes runtime hosting code to transfer control to the runtime
each time an executable is started from the shell.
Question: What are the two main components of the .NET Framework 4?
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-13
Key Points
Visual Studio 2010 constitutes the core of Microsoft .NET development. Visual
Studio 2010 is a complete development environment in which you can design,
develop, debug, and deploy your .NET applications and services.
Lesson 2
Overview of ASP.NET
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the client-server interaction.
• Describe ASP.NET.
• Describe the components of an ASP.NET Web application.
1-16 Introduction to Web Development with Microsoft® Visual Studio® 2010
Client-Server Interaction
Key Points
Developing applications for use over HTTP is very different from creating desktop
applications such as Windows Forms applications. The HTTP protocol is stateless
by nature, which means that communication works in a disconnected manner.
This means that there is no connection between a client and a Web server.
• When a client requests a page by typing an address—also known as a Uniform
Resource Locator (URL)—in a Web browser, the Web server responds by
sending the HTML (and potentially client-side code for the requested resource,
such as a page or file), back to the client.
• The connection between the client and the server opens when the request
comes in, and the connection closes after the response has been sent to the
client. This can make it difficult to make a Web application appear as a
connected application. However, the Web server can be made to recognize a
user as they make repeated requests. This involves state management; it is
possible, therefore, to recognize a user and any information they have included
on a Web page, from one request to the next.
1-18 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: State management is covered in detail in Module 13, “Managing State in Web
Applications.”
• On the client side, after loading a page, the user submits the page to the server,
effectively triggering what is called a postback. This happens by using
functionality of the HTTP protocol, including POST and GET methods. In
HTML, a typical submit function can be triggered by exposing an HTML input
element of type submit to the user, who can then click this element, which is
rendered as a button on the Web page.
You can use the client-side code on the client to work with information and
controls without submitting to the server; the client-side code can also be used to
trigger a postback, programmatically. Server-side code runs only on the server, but
it can be used to inject client-side code into the page that is rendered on the client.
ASP.NET makes the client-server interaction seem trivial, because of the event-
driven programming that you can use over HTTP.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-19
What Is ASP.NET?
Key Points
Prior to the .NET Framework and ASP.NET, Web developers who used Microsoft
technologies implemented dynamic Web sites by using classic ASP technology.
Classic ASP is interpreted code, unlike ASP.NET, which is compiled code.
ASP.NET—unlike ASP—offers performance optimizations, strong typing, and early
binding.
What Is ASP.NET?
Microsoft ASP.NET is a set of Web application development technologies.
ASP.NET enables programmers to build dynamic Web sites, Web applications, and
Web-based WCF services. Because ASP.NET is part of the .NET Framework, you
can develop ASP.NET Web applications in any .NET-based language. The following
are some key aspects of ASP.NET:
• The fundamental component of ASP.NET is the Web Form. A Web Form is the
Web page that users view in a browser. It is a dynamic page that the Web
server processes, and that can access server resources. A typical ASP.NET Web
application consists of one or more Web Forms.
1-20 Introduction to Web Development with Microsoft® Visual Studio® 2010
You can also use JavaScript, VBScript, jQuery, or Ajax to process various user
actions on the client. In other words, a traditional HTML Web page can run
script on the client to perform basic tasks. However, an ASP.NET Web Form
can also run server-side code to access a database, generate additional Web
Forms, or take advantage of the built-in security on the server.
• ASP.NET is device-independent, and allows you to develop a single Web Form
that you can view on most devices that have Internet access and a Web
browser.
• You can use Visual Studio 2010 to build and run an ASP.NET Web
application. This results in a simplified development process, because you can
test the application without creating an external hosting environment.
• The built-in Windows authentication and Forms authentication helps keep
Web applications and any associated data, secure.
• A deployed ASP.NET application runs as a process in the Internet Information
Services (IIS) Web server.
• The ASP.NET technology also supports Web-based WCF services. Web-based
WCF services are distributed applications that use XML and SOAP to transfer
information between clients, applications, and also other Web-based WCF
services.
Note: For more information about WCF Services, see Module 12, "Consuming Windows
Communication Foundation Services."
Feature Description
(continued)
Feature Description
Health monitoring and ASP.NET includes features that enable you to monitor the
performance features health and performance of your ASP.NET application.
ASP.NET health monitoring provides reporting of key
events and information about the health of an
application, and about error conditions.
ASP.NET Dynamic ASP.NET Dynamic Data is a framework that lets you easily
Data create data-driven ASP.NET Web applications. This is
done by automatically discovering data-model metadata
at run time, and deriving UI behavior from it. ASP.NET
Dynamic Data is covered in Module 10.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-23
Key Points
An ASP.NET Web application contains different components. When you create a
Web application, you must understand how to implement and use all of the
components.
• Code-behind files. Code-behind files are associated with Web Forms, and
contain the server-side code for the Web Form. You can also create a single-file
ASP.NET page, which contains both the page markup and the .NET
Framework code in the same file. This means that the code and the page
markup share a single file.
• Configuration files. Configuration files are XML files that define the settings for
the Web application and the Web server. Every Web application has one or
more web.config configuration files, and each Web server has only one
machine.config file.
• Global.asax file. The Global.asax application file contains code for responding
to application-level events that are raised by ASP.NET, such as unhandled
errors.
• WCF service references. WCF service references allow the Web application to
send and receive data from a Web-based WCF service.
• Database connectivity. Database connectivity allows the Web application to
transfer data to and from database sources.
• Additional items. Additional files that you can include in a Web application
include HTML files for static content, text files, XML files, and XSLT files.
• CSS. The CSS files and the contained styles are used to design the Web
application, both with regard to element positioning on a Web Form, and for
specifying fonts, colors, and text.
Question: What are the tools in Visual Studio 2010 that make application
development faster, easier, and more reliable?
1-26 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
You can create your applications in Visual Studio 2010 by adding markup and
code to your Web pages. However, during compilation, compilers work on your
markup and code to generate markup and code that will display and behave
correctly on the clients. This means that the markup adheres to certain standards
that the browsers of the intended clients can render correctly.
Note: The following description is for working with an ASP.NET Web Site project, and
not the ASP.NET Web application project. You will learn more about differences between
the two project types in later modules.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-27
• First, as part of the deployment to the Web server on which the Web site will
run, all files in the Web site are copied to the destination Web server. This
Web server may be local or remote. ASP.NET compiles the files when a user
accesses the Web site.
The ASP.NET compiler manages the compilation process dynamically, on an
individual basis. The Web site content is parsed, and the actual compilation of
each item is handed over to the appropriate compiler, such as the Visual Basic
or Visual C# compiler.
This ASP.NET compiler is called the ASP.NET just in time (JIT) compiler. This
means that both inline code and code-behind files are compiled. The Web
Forms or User Controls are turned into a class definition with methods for
rendering the page or control.
• When compiling the application, the application is compiled into one or more
assemblies in the Temporary ASP.NET Files folder when the first page is
requested. The first page can be any page—not just the home page or default
page. The assemblies are located in a subfolder with a name derived from a
special naming convention that allows dynamic and random directory names.
This makes it easy to locate the assemblies when requested.
This compilation model can be very convenient. Developers can open a
Web Form or a corresponding code-behind file and make modifications to it—
even on the live server—and changes are effective immediately. Although the
source code is available on the Web server, it does not imply that a Web site
user can access the source code and markup; this is restricted by the Web
server. However, the source code is accessible to any user on your network
who has the correct access permissions to the folders on the Web server.
If the visibility of the source code is of concern to you, you can either utilize
the Web application project instead of the Web site project, or you can use the
precompilation model.
1-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
ASP.NET Web pages and code files use dynamic compilation by default when a
user requests a resource for the first time. The compiled resources are then cached,
which ensures that subsequent requests are performed efficiently.
Dynamic compilation execution allows you to modify your source code without
having to explicitly compile your code before deploying the Web application.
In this model, you will learn how dynamic compilation in ASP.NET works to send
information to a requesting client.
First Request
When a client requests a Web page for the first time, the following events occur:
1. The client browser issues a GET HTTP request to the server.
2. The ASP.NET parser interprets the source code.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-29
Note: MSIL is an assembly-level programming language that gets executed at run time.
The various compilers, such as those for Visual Basic and Visual C#, compile the Visual
Basic and Visual C# code into MSIL, which is then run.
Second Request
When the user requests the same Web page for the second time, the following
events take place:
1. The client browser issues a GET HTTP request to the server.
2. The runtime loads and immediately runs the MSIL code that was already
compiled during the first request of the page.
Note: The .aspx content may still be parsed, particularly if the content page has changed.
Precompilation
You can choose to precompile an entire site before you make it available to users.
The advantages of precompilation include:
• Improved response time for users, because pages and code files do not require
compilation on first request.
• Ability to identify compilation errors before users access the site.
• Ability to deploy the Web site to a production server without the source code.
Key Points
There are a number of frameworks within the .NET Framework that provide
specific functionality for ASP.NET. Two of these frameworks are ASP.NET Ajax,
and ASP.NET Dynamic Data.
Developers familiar with the ASP.NET server-side programming model can use
ASP.NET Ajax server-side controls to add Ajax functionality to an ASP.NET
application without writing any JavaScript code.
The client-side ASP.NET Ajax library helps you build rich client-side applications.
The jQuery library is an open source JavaScript library.
Note: For more information about ASP.NET Ajax, see Module 11, "Creating a Microsoft
ASP.NET Ajax-Enabled Web Forms Application."
Note: For more information about ASP.NET Dynamic Data, see Module 10, "Managing
Data by Using Microsoft ASP.NET Dynamic Data."
1-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 3
Overview of the Lab Application
In this lesson, you will explore the lab application that you will build throughout
the remainder of this course. You will also explore a complete version of the lab
application, and understand some of its functionality.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the lab scenario.
• Describe the lab application setup.
• Explore the .NET Framework.
• Explore Visual Studio 2010.
• View the components of an ASP.NET 4.0 Web application project.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-33
Lab Scenario
You are a junior developer in Contoso, Ltd. As part of your job, you need to create
a Customer Management Web application for managing your customers
electronically from anywhere within the intranet, without installing any extra
software on the client. The Web application will also be made available over the
Internet to employees in remote locations who are not connected to the intranet.
To do this, you need to select a development tool and platform that will enable you
to create a simple Web application with the minimum amount of coding.
The senior developer has advised you to become familiar with the features
and functionalities of both the .NET Framework 4 and Visual Studio 2010, by
viewing a Web application or solution that could potentially be a prototype for a
new project.
1-34 Introduction to Web Development with Microsoft® Visual Studio® 2010
This lab solution walkthrough will help build the Customer Management Web
application, to enable the sales staff of Contoso, Ltd to maintain customer and
country items.
Application Requirements
The application must meet the functional and UI requirements listed in the
Functional Requirements and User Interface Requirements sections.
Functional Requirements
• Provide logon abilities.
• Store customer rows.
• Create new customer rows.
• Edit existing customer rows.
• Display information about a single customer.
• Display all customer names in a spreadsheet-like view.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-35
Application Building
A single application will be built throughout the modules, even if the lab exercises
in the first few modules only introduce the concepts to be used in later modules.
Functionality Description
Breadcrumb
The breadcrumb displays the current location in the application, and the path to
the page or Web Form.
Customers Page
Customer rows are stored in the CustomerManagement database in the Customers
table. The Customers page displays the following information.
Field Description
First Name The first name of the customer is limited to 50 characters. This
field is mandatory.
Last Name The last name of the customer is limited to 30 characters. This
field is mandatory.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-37
(continued)
Field Description
Address This is the address of the customer, which consists of street name,
house and door number, and is limited to 50 characters. This field
is mandatory.
Zip Code This is the zip code for the customer, and is limited to 10
characters. This field is mandatory.
City This is the name of the city in which the customer lives, and is
limited to 30 characters. This field is mandatory.
State This is the name of the state or region in which the customer lives,
and is limited to 30 characters.
Country This is the unique ID of the country in which the customer lives.
This field is mandatory.
E-mail Address This is the e-mail address of the customer, and is limited to 50
characters.
Web Address This is the Web address (URL) of the customer, and is limited to
80 characters.
Credit Limit This is the credit limit assigned to the customer. This field only
accepts numeric characters 0–9, and is mandatory.
Created Date This is the date when the customer row is created in the
application, and it is automatically assigned. This field is read-
only.
Input Validation
The Customers Web Form provides input validation by using various techniques.
The input validation, which must take place at both the client-side and server-side,
includes the following functionalities:
• You will be required to add information to the First Name, Last Name,
Address, Zip Code, City, Country, and Web Address fields when adding
or editing a customer row. A message will display if any mandatory
information is left blank, or when saving or updating customer information.
• The textbox for the Credit Limit field only accepts numeric characters, and
only numbers less than or equal to 50,000.
• The E-mail Address field must contain a valid e-mail address, if filled in.
• The Web Address field must contain a valid Web address (URL).
Countries Page
Country rows are stored in the Contoso database in the Countries table. The
Countries page displays the information listed in the following table.
Field Description
Phone No. Format This is the format for displaying and entering a phone number,
and is limited to 30 characters. The formatting will be applied
to the user input when this field has been specified in the
database.
Dialing Country This is the international dialing code when dialing from outside
Code the country, such as 1 for Canada and United States, 45 for
Denmark, 44 for Great Britain, 353 for Ireland, and 34 for Spain.
This is often displayed as +1 or +45 to indicate the prefix that
must be used to dial outside the country from where the call
originates. This field is mandatory.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-39
(continued)
Field Description
International This is the code or number that must be used to dial a number
Dialing Code outside the country from where the call originates, such as 011
for the United States, and 00 for member countries of the
European Union. This field is mandatory.
Internet Top Level This is the country-specific Top-Level Domain (TLD) for Internet
Domain domains, such as .dk for Denmark, .de for Germany, .ie for
Ireland, .no for Norway, or .au for Australia. This field is
mandatory.
Input Validation
The Countries Web Form provides input validation when creating or editing
countries by using various techniques. The input validation—which must take place
on both client-side and server-side—includes the following functionalities:
• You will be required to add information to the Name, Internet Top Level
Domain, and International Dialing Code fields when adding or editing a
country. A message will display if any information has been left out, when
saving or updating country information.
• The text box for the International Dialog Code field only accepts numeric
characters in the format 999.
Login
The user must log in, and the standard ASP.NET login controls must be visible on
all pages. Using the standard ASP.NET Login controls, the user can see who has
logged in. The user logs out by clicking the appropriate link. The user names and
passwords are stored in the standard ASPNETDB profile database that is created in
SQL Server 2008 Express Edition.
Login Page
The Login page to which nonauthenticated users are automatically redirected
allows a user to type the user name and password to access the application. The
Login page displays the following information:
• User name: The user name of the user trying to authenticate.
1-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Password: The password associated with the given user name. The value in
this field must be case sensitive.
• Login: The Login button, which will start the process of authenticating the
given user credentials.
Input Validation
The Login Web Form provides input validation when authenticating as a user. The
input validation—which must take place on both client-side and server-side—
includes the following:
• You will be required to add information to the User name and Password fields
when authenticating. A message will display if any information has been left
out, once the user clicks the Login button.
Database
The CustomerManagement database is a SQL Server 2008 database with two
tables: Customers and Countries.
The Customers table includes the following fields.
Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description
(continued)
Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description
(continued)
Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description
CreatedDate smalldatetime N/A Yes getdate() This is the date that the
customer row is created
in the application. It is
automatically assigned
by the database.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-43
Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description
(continued)
Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description
Existing Countries
On a monthly basis, an update to the country rows is sent electronically to
Contoso, Ltd, and these country rows are all placed in a single XML file. This data
must be imported into the Countries table, but only those countries with a value
for the PhoneNoFormat field should be imported.
Key Points
In this demonstration you will examine the .NET Framework in the context of
Web application development, and explore the ASP.NET framework extensions,
including the Ajax Extensions, Ajax Library, and Dynamic Data.
Demonstration Steps
The main tasks are as follows:
1. Open Visual Studio 2010.
• On the Start menu of 10267A-GEN-DEV, point to All Programs, click
Microsoft Visual Studio 2010, and then click Microsoft Visual Studio
2010.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-47
Note: You will learn more about the features offered by Ajax Extensions and the Ajax
Library in Module 11, “Creating a Microsoft® ASP.NET Ajax-Enabled Web Forms
Application."
Note: You will learn more about how Dynamic Data works in Module 10, "Managing
Data by Using Microsoft ASP.NET Dynamic Data."
Result: At the end of this demonstration, you will have a basic understanding of
the.NET Framework 4 features in the context of Web application development,
including some the new functionalities, such as Ajax, and Dynamic Data.
1-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
In this demonstration you will learn how to use Visual Studio 2010 as a single tool
for building Web applications by exploring views, designing Web Forms, adding
code, and using components and controls.
Demonstration Steps
The main tasks are as follows:
1. Open Microsoft Visual Studio 2010.
Result: At the end of this demonstration, you will understand the advantages of using
Visual Studio 2010 for developing ASP.NET applications.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-51
Demonstration Steps
The main tasks are as follows:
1. Examine the solution and project files, and the references.
• In Solution Explorer, notice the solution and project files, and identify
where project references go.
2. Examine the ASP.NET folders.
• In Solution Explorer, review the ASP.NET folders, and if time allows create
a new one.
1-52 Introduction to Web Development with Microsoft® Visual Studio® 2010
3. Examine the Web Forms, designer code files, code-behind files, and class files.
• In Solution Explorer, review the various files.
4. Examine the assembly info file and the web.config files.
• In Solution Explorer, review the various files.
Result: At the end of this demonstration, you will have identified and examined the
functionality and importance of the components of an ASP.NET 4.0 Web application.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-53
Lab Review
Tools
Tool Purpose Where to find it
Module 2
Creating Web Applications by Using Microsoft®
Visual Studio® 2010 and Microsoft .NET–Based
Languages
Contents:
Lesson 1: Choosing a Programming Language 2-3
Lesson 2: Overview of Visual Studio 2010 2-15
Lesson 3: Creating a Simple Web Application 2-32
Lab: Creating Web Applications by Using Microsoft
Visual Studio 2010 and Microsoft .NET–Based Languages 2-53
2-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
Lesson 1
Choosing a Programming Language
Key Points
To create your Web applications, you have a wide choice of programming
languages. For many years, the programmer’s choice of the programming language
was based on the available platform, framework, and integrated development
environment (IDE), although some programmers did choose a programming
language purely because they liked the syntax of that programming language.
However, all this changed when the .NET Framework was introduced, because it is
programming language-independent. This is because the Microsoft intermediate
language (MSIL) that is executed at runtime gets converted into machine code
when the program is run by the .NET common language runtime (CLR).
2-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the features of Visual Basic.
• Describe the features of Visual C#.
• Describe the scenarios for mixed-language environments.
• Describe the considerations for choosing between Visual Basic and Visual C#
for an application.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-5
Key Points
While the current Visual Basic 10.0 version is designed around the .NET
Framework, if you are used to developing applications in the Component Object
Model (COM)–based Visual Basic 6.0 or earlier, you will find Visual Basic 10.0 easy
to use. While Visual Basic 6.0 was mostly used for creating COM components and
Windows®-based applications, Visual Basic 10.0 can be used for developing any
type of .NET Framework application or service, including Web applications,
Windows Forms applications, Windows Communication Foundation (WCF)
services, Asynchronous JavaScript and XML (Ajax)–based Web applications, device
applications, and Microsoft Silverlight® applications.
If you have worked in a previous version of Visual Basic, you will find that not
much has changed, although many additions have been made. For example, there
are changes to the COM-based deterministic finalization, which has now been
replaced by the garbage collection feature of CLR, thus eliminating deterministic
finalization and helping to reduce memory waste from unclaimed objects.
2-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Features of Visual C#
Key Points
Visual C# has always targeted the .NET Framework, and there are no remnant
features from previous versions that are targeted at other platforms. The current
Visual C# 4.0 version has many newly added features, and the syntax has been
enhanced significantly since version 1.0. Visual C# 4.0 can be used for developing
any type of .NET Framework application or service, including Web applications,
Windows Forms applications, WCF services, Ajax–based Web applications, device
applications, and Silverlight applications.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-9
When creating new types by using the Visual C# Text Editor, the default
namespace will be added automatically as you type the code.
There are a number of code-refactoring options in the Visual C# Text Editor. You
can invoke an option by right-clicking a keyword or selected text, and then
selecting the appropriate action from the context menu. Actions include:
• Renaming variables.
• Promoting a local variable to a parameter in a method.
• Extracting a method, which involves copying existing text for inclusion in a
new method.
2-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
if () {}
switch () {}
for () {}
foreach () {}
void {}
class {}
namespace {}
// Single line
/* Multi
line */
Key Points
When working in a programming environment with many developers, you will
encounter projects and solutions that are in different .NET Framework–based
programming languages, such as Visual Basic and Visual C#. Therefore, as a
developer, you need to at least understand both languages, because it is very likely
that you will work with both. You might need to copy some functionality written in
a programming language other than the one you master the best. Depending on
the amount of code, you will either copy some lines of code, and then translate
them into a programming language of choice, or you will add a project to your
current solution.
If you add a project to your current solution, then you have a solution made up of
at least two projects, written in two different programming languages. This is an
everyday reality for many .NET developers. Thus, even if you do not master the
two languages, you should at least be able to read and understand the code written
in either language.
Key Points
Visual Studio 2010 comes with both Visual Basic and Visual C# compilers and
editors, giving you a choice of programming languages. However, this also requires
you to choose a programming language when starting a new project.
Sometimes you are allowed to choose the programming language for a new
project.. However, sometimes the decision is already made by an architect or team
lead, and you need to work with the team and their decision. On smaller projects,
you may get to make the choice if the company or department you are working for
has not yet decided to use one of the programming languages exclusively. If this
happens, there are things to consider before determining which programming
language will best fit your project.
Both Visual Basic and Visual C# are popular programming languages that are used
by developers worldwide. Because there are no rules on choosing either language,
you can make a decision based on the following considerations.
2-14 Introduction to Web Development with Microsoft® Visual Studio® 2010
Another factor that may influence your choice is whether you prefer the verbose
syntax in Visual Basic, or the more terse composition of Visual C#, and its use of
braces. This is quite often the first factor that new .NET developers look at,
especially if their background is not one of Microsoft Visual C++® or classic Visual
Basic.
Ultimately, the choice is generally a matter of preference.
Question: What are the possible issues that you might need to handle in a mixed-
language environment?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-15
Lesson 2
Overview of Visual Studio 2010
Visual Studio 2010 is a comprehensive tool for creating all types of .NET
Framework–based applications, including Web applications and services. It
consists of an IDE, integration of the .NET Framework, and the building of
applications and services based on .NET Framework versions 2.0, 3.0, 3.5, and 4.
Visual Studio 2010 IDE consists of a common user interface (UI), and set of tools
that you can use for all the project types and programming languages that Visual
Studio 2010 supports.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the advantages of using Visual Studio 2010.
• Identify the available project templates.
• Describe the features of IDE.
• Identify the elements of a Visual Studio 2010 Start page.
2-16 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
Visual Studio 2010 simplifies the development of powerful and reliable enterprise
Web solutions, and increases developer efficiency by providing a familiar, shared
development environment. When you start Visual Studio 2010 for the first time,
you are prompted to specify the settings for your development environment.
Visual Studio 2010 provides prebuilt components, programming wizards, and the
ability to reuse components that are written in any programming language. This
helps significantly reduce development time. IntelliSense–based code completion
enables you to quickly produce accurate code. Powerful, end-to-end, cross-
language debugging support helps you to make your applications more robust.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-17
Single IDE
Visual Studio 2010 has a single IDE that provides a consistent look and feel,
regardless of the programming language that you use or the application type that
you develop. Visual Studio 2010 supports development in several.NET
Framework–based programming languages. This support enables you to work in
your own preferred programming language, because you no longer have to learn a
new programming language for each new project. You can also use the IDE in the
design and testing phase of the development life cycle. For example, Visual Studio
2010 provides class diagrams and unit testing.
Integrated Browser
Visual Studio 2010 contains a built-in browser that is based on Windows Internet
Explorer®. The browser is integrated into IDE, and you can access it from multiple
windows and menus. This browser accessibility enables you to view your Web site
during the development cycle, instead of having to use another program.
Debugging Support
Visual Studio 2010 supports debugging from your initial code, through to the
application’s release. Debugging support includes breakpoints, break expressions,
watch expressions, and the ability to step through the code, one statement or one
procedure at a time.
Deployment Support
After you have finished developing a Web site, you can deploy it to a Web server.
The Web server can be either a test server or a production server. Visual Studio
2010 provides the following options for deploying a Web site:
• Copy Web Site. The Copy Web Site tool copies the current Web site to a target
server.
• Publish Web Site. The Publish Web Site utility compiles a Web site into a set of
executable files that can be copied to the target server.
Deployment can happen to the local file system, an Internet Information Services
(IIS)–based site, or an FTP server. The latter two can be local and remote.
Note: You must use IIS to host the deployed Web application. IIS is a Microsoft Web
server that is bundled with both client and server implementations of the Windows
operating system. File Transfer Protocol (FTP) is a network protocol that is used to
exchange and manipulate files over a network, which generally means you want to open
the target Web site with the Web Development server.
Question: Which Web server is the default server when creating your Web
applications in Visual Studio 2010?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-19
Key Points
Visual Studio 2010 provides templates that support the creation of a number of
common project types. These templates contain all the required files, and ensure
that the IDE has the correct configuration for the selected project.
When you use these templates, you do not have to set up the infrastructure, which
means the template automatically creates the folders and files that are required for
the specific type of project. Therefore, you can focus on adding functions to your
projects.
You can use the Solution Explorer—which provides a graphical view of your
solution—to organize and manage all of your application projects and files.
Project Templates
Visual Studio 2010 includes multiple project templates that are sorted by language
and type. To select the correct template, you must first specify the language in
which you want to work.
The following table lists some of the available Visual Basic and Visual C# project
templates.
Class library Creates reusable classes and components that you can share
with other projects.
ASP.NET Web Creates an ASP.NET Web application with the basic server
application files that you require for your application.
ASP.NET Web site Creates an ASP.NET Web site with the basic server files that
you require for your Web site.
WCF service application Creates a WCF service that can be consumed by other WCF
services or applications on a network.
WCF services are components that are available over the
Internet, and are designed to interact only with other Web
applications.
ASP.NET server control Creates custom ASP.NET server controls. This template adds
the necessary project items that you require to create the
control.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-21
(continued)
ASP.NET Ajax server Creates custom ASP.NET Ajax server controls. This template
control adds the necessary project items that you require to create
the control.
Empty project Creates your own project type. This template creates the
necessary file structure that you require to store application
information. You must manually add any references, files, or
components.
ASP.NET Dynamic Data Creates an ASP.NET Web site with the basic server files that
Entities Web site you require for your Web site, along with support for
Dynamic Data based on an Entity Data Model.
ASP.NET Dynamic Data Creates an ASP.NET Web site with the basic server files that
LINQ To SQL Web site you require for your Web site, along with support for
Dynamic Data based on a LINQ To SQL Data Model.
Question: What are some of the additional project templates that are available in
Visual Studio 2010?
2-22 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
The Visual Studio 2010 IDE contains multiple windows that provide a variety of
tools and services. Many of the features of Visual Studio 2010 are available from
several of the IDE windows, menus, and toolbars. You can move or hide IDE
windows, depending on your personal preference. You can use the View menu to
select the windows that you want to display. You can click the Auto Hide button to
turn static windows into pull-out windows.
• In the Design mode, you can use the editor to move controls and graphic
elements around the window by using a drag-and-drop operation. When you
add a control to a Web page in Design mode, Visual Studio 2010 adds the
supporting code and default properties to the Web Form. You can then switch
to the Source mode and edit that code.
• In the Source mode, Visual Studio 2010 highlights your code so that the
different elements—such as variable names and keywords—are instantly
identifiable. The IntelliSense feature provides you with auto-completion
suggestions, and enables you to build functions by simply selecting from the
list of available syntax.
• In the Split mode, the editor is split into two windows: one window for the
design surface of the Web page, and the other window for the source code of
the Web page.
When you use the Editor window in the Source mode, two drop-down lists appear
at the upper part of the window—the Class Name list on the left, and the Method
Name list on the right. The Class Name list shows all the controls on the
associated form. If you click a control name in the list, the Method Name list
shows all the events for that control. Events are actions that the control can
perform and your application can interpret. By using the Class Name and Method
Name lists together, you can quickly locate and edit the code in your application.
2-24 Introduction to Web Development with Microsoft® Visual Studio® 2010
This feature enables you to change properties at the project level or page level.
To view the available options—including adding, building and editing pages—right-
click the file, project, or solution. The following is a list of some the file types that
display in the Solution Explorer pane:
• Project references that list classes that are used by the page and Web controls
• Web Forms in the project
• Code-behind pages that contain the logic that supports the Web Forms,
project-related folders, and sub-items
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-25
Properties Pane
Visual Studio 2010 enables you to adjust the properties of documents, classes, and
controls by using a single Properties window. When you create or select an item,
the Properties pane automatically displays the related properties.
Output Pane
The Output pane displays status messages for various features in IDE. You can
program your own applications to write diagnostic messages to the window at run
time.
Toolbox Pane
The Toolbox pane enables you to use drag-and-drop controls in your application.
The tools are grouped by category in the Toolbox pane, and display only if they
are available to use. Common Web application categories include:
• Standard. Contains standard controls that you can use to build the UI for a
Web page.
• Data. Contains objects that allow your application to connect and access the
data in Microsoft SQL Server® and other databases.
2-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
Question: What are the four views available for editors and designers?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-29
Key Points
The Visual Studio 2010 Start page provides an easy way to access or create
projects, learn about upcoming product releases and conferences, or read the latest
development articles. By default, the Start Page displays when opening Visual
Studio 2010. You can also access it by clicking Start Page on the View menu.
You can change the default Visual Studio 2010 startup settings from the Options
dialog box, to enable one of the following actions at startup:
• Display the home page set in your browser.
• Open the last loaded solution.
• Show the Open Project dialog box.
• Show the New Project dialog box.
• Show an empty environment.
• Show the Start Page.
2-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
In addition to the options mentioned above, there are also two options on the Start
Page that affect how and when the Start Page opens and closes. You can choose
whether or not to Close page after project load, or Show page on startup by
selecting or clearing the corresponding check boxes located in the lower-left corner
of the Start page. These check boxes are both selected by default.
Your changes are implemented the next time you start Visual Studio.
Question: Which area and tab of the Start Page displays a list of Help topics, Web
sites, technical articles, and other resources?
2-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 3
Creating a Simple Web Application
You can use Visual Studio 2010 to build your own ASP.NET Web application from
start to finish. When you work with projects, Visual Studio 2010 creates a number
of files that support your development. In this lesson, you will learn how to create,
build, and view a simple ASP.NET Web application.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe how to develop ASP.NET Web application pages.
• Describe Web application project files and folders in Visual Studio 2010.
• Describe Web site project files and folders in Visual Studio 2010.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-33
Key Points
Visual Studio 2010 contains everything that you require to build your own
ASP.NET Web application or Web site from start to finish. To create an ASP.NET
Web application by using Visual Studio 2010, you must perform the following
steps:
1. Create a design specification. The design specification is the blueprint that
you use to create a Web application. You should take time to design your
application before you write any code. Although Visual Studio 2010 provides
tools to help you quickly develop a solution, you can design your application
more efficiently if you have a clear understanding of user requirements and the
feature set. By using a design specification, you will also save time by
minimizing the potential for rewriting unsuitable or redundant code.
Visual Studio provides the Class Designer, which enables you to visualize the
structure of classes and their relationships. You can easily create new classes,
and refactor current classes by using this visual design environment.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-35
2. Create a new project. When you select a new project template, Visual Studio
2010 automatically creates the files and the default code that are required to
support the project. As part of this initial project creation, you should transfer
the main coding tasks from your design specification into the Visual Studio
2010 Task List. This transfer enables you to track your development against
the specification.
3. Create the interface, and write the code. To create the interface for your Web
application, you must first place controls and objects on the Web pages by
using the Editor window in the Design mode. As you add objects to a form,
you can set their properties by using the table in the Properties window, or by
using code in the Editor window.
Note: For more information about adding controls to an ASP.NET Web Form, see
Module 3, "Creating a Microsoft ASP.NET Web Form."
After you set the initial properties for the ASP.NET Web Form and its objects,
you can write the event procedures that will run when different actions are
performed on a control or object. You may also have to write code to add
business logic, and to access data.
Note: For more information about writing code in ASP.NET Web Forms, see Module 4,
"Adding Functionality to a Microsoft ASP.NET Web Form."
4. Build a project. When you build a project, Visual Studio builds all the code on
the Web pages and other class files into a dynamic-link library (DLL), called an
assembly. Visual Studio 2010 has two build options: debug and release. When
you first develop a project, you build debug versions. When you are ready to
release the project, you create a release build of the project.
You can build, rebuild, or clean an individual project, or the entire solution.
• Build. Visual Studio compiles only those project files and components that
have changed since the last build. You usually build only your project or
solution.
• Rebuild. Visual Studio cleans the project or solution first, and then builds
all project files and components. You must perform a rebuild when the
project versions target out-of-sync components.
2-36 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Clean. Visual Studio deletes any intermediate and output files. Only the
project and component files remain, from which you can build new
instances of the intermediate and output files. This means you really never
have to clean your project or solution.
5. Test and debug. Testing and debugging is not a one-time step, but rather is
iteratively done throughout the development process. Every time you make a
major change to the application code, you must run a debug build of the
application to ensure that the code works as expected. Visual Studio 2010
offers numerous debugging tools that you can use to find and fix errors in
your application.
6. Deploy. When your project is fully debugged, and you have built a release
build, you deploy the necessary files to a Web server.
Note: For more information about deploying an ASP.NET Web application, see
Module 14, "Configuring and Deploying a Microsoft ASP.NET Web Application."
Question: What are the three main phases of the Web application development
process?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-37
Key Points
In Visual Studio 2010, you can create a Web application by using the ASP.NET
Web application project template.
The Web application project offers tighter control than the Web Site project by
explicitly defining resources.
(continued)
Note: The Bin and Obj folders are hidden by default. In Solution Explorer, use the Show
All Files button to display the folders.
When you build an ASP.NET Web application project, Visual Studio 2010 creates
an assembly in the Bin folder of the project. An assembly is one .dll file that is
created from all the code-behind pages that make up a Web application. A solution
file, .sln, is also created. This file has the same name as the project, followed by the
.sln extension, and it contains information about the projects and miscellaneous
non-project-specific files. Initially, the solution file only contains information about
the Web application project. To open a previously created ASP.NET Web
application project, open the solution file in Visual Studio 2010.
2-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
In Visual Studio 2010, you can create a Web site by using the ASP.NET Web site
project template.
The Web site project model generally offers more features and additional flexibility
in the management of Web applications, than that of a Web application project
model.
The Web site project Solution folder contains the subfolders and files listed in the
following table.
About.aspx, and either This is the About Web Form and the corresponding
About.aspx.vb or About.aspx.cs code-behind file. The Web form displays an About
this Web site message.
Default.aspx, and Default.aspx.vb This is the Default Web Form and the
or Default.aspx.cs corresponding code-behind file. The Web Form is
the home page for the Web site.
Site.master, and Site.master.vb or This is the master page and the related code-
Site.master.cs behind file for the Web site.
When you publish a Web site project, Visual Studio 2010 can create multiple
assemblies for the Web site. To open a previously created ASP.NET Web site
project, open the Solution file in Visual Studio 2010. Alternatively, you can open
the file by using the File, Open, Web Site menu command.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-43
Key Points
In Visual Studio 2010, you can create a Web application by using either the
ASP.NET Web application project template, or the ASP.NET Web site project
template.
The choice of a project template depends on your requirements, and your
preferred development workflow. Some developers will find the Web site project
model easy to use, because resources are defined implicitly by being in a folder.
Other developers will prefer to use the Web application project model in which
they have tighter control over their project, because resources are defined explicitly
in the project file.
2-44 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
In Visual Studio 2010, you can create different file types to support the
development of your Web application.
• Classes. Class files use the Visual C# extension, (.cs), or Visual Basic extension
(.vb). For example, the full file name for a class file named Test is Test.cs for a
Visual C# project, or Test.vb for a Visual Basic project.
• JavaScript files (.js). These files are used for containing JavaScript scripts and
methods used in your Web application.
Note: For more information about code-behind pages, see Module 4, "Adding
Functionality to a Microsoft ASP.NET Web Form."
Note: For more information about master pages, see Module 5, "Implementing Master
Pages and User Controls."
• Web.config file. The web.config file contains configuration settings that the
CLR component reads, such as the assembly binding policy and WCF services.
This file also contains settings that the application can read, and the global
application classes that support a project.
• Web.sitemap file. The Web.sitemap file contains XML elements, or items that
can be used to display a Menu or breadcrumb in your Web application.
Question: What are examples of files that are not based on a programming
language, but will have their own extensions?
2-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
In this demonstration, you will see how to create a Web application project.
Demonstration Steps
1. Open Visual Studio 2010.
• On the Start menu of 10267A-GEN-DEV, point to All Programs,
click Microsoft Visual Studio 2010, and then click Microsoft Visual
Studio 2010.
2. Create a Web application project.
a. In the Start Page – Microsoft Visual Studio window, on the File menu,
click New Project.
b. In the New Project dialog box, in the left pane, click either Visual Basic or
Visual C#.
c. In the middle pane, click ASP.NET Web Application, and then click OK.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-49
[Visual Basic]
TextBox1.Text = "You clicked the button"
[Visual C#]
TextBox1.Text = "You clicked the button";
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
If Me.IsPostBack Then
Response.Write("Server roundtrip due to postback")
Else
Response.Write("First time page is loaded")
End If
End Sub
2-50 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
Response.Write("Server roundtrip due to postback");
}
else
{
Response.Write("First time page is loaded");
}
}
Note: If you see a Debugging Not Enabled message box, click OK.
c. Run the application in the debug mode, and step through the lines of code
by pressing the F10 key. When the browser opens after the first debugging
session, click Page on the toolbar, and then click View Source to view the
source in Internet Explorer.
d. Click the Button to post back to the server.
e. In the Default.aspx.vb or Default.aspx.cs code window, step through the
lines of code by pressing F10.
f. In the http://localhost:1186/Default.aspx-Original Source window, click
the Close button.
g. In the http://localhost:1186/Default.aspx window, click the Close button.
Question: When you create a Web site, what folders or files does Solution
Explorer display?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-51
Key Points
After creating and testing your Web application—whether based on the ASP.NET
Web site or the ASP.NET Web application template—you will need to build and
deploy the Web application on a test or production server. Visual Studio 2010
helps you build and deploy your Web application.
Servers
In a development environment, you deploy the Web application on the test server
after you complete the development and personal testing. The application is then
thoroughly tested. There is often more than one test server, all depending on the
various test phases a Web application goes through, including an integration test,
and a user acceptance test (UAT). After the Web application has been fully tested
and released, you can deploy it to the production server.
2-52 Introduction to Web Development with Microsoft® Visual Studio® 2010
IIS
Microsoft provides an IIS Web server for hosting Web applications. IIS supports
most Windows® operating system versions, including all editions of Windows
Server®, and many of the editions of Windows XP, Windows Vista®, and
Windows 7.
Deployment Options
There are a number of deployment options available with Visual Studio 2010.
However, these are covered in later modules.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-53
Note: You can perform tasks in this lab either by using the Visual Basic or Visual C#
programming language. If you are using Visual Basic as your programming language,
refer to the steps provided in Section 1 of the lab page. If you are using Visual C# as
your programming language, refer to the steps provided in Section 2 of the lab page.
Introduction
In this lab, you will create a simple ASP.NET Web site project, then add a server
control, to a Web Form, and then configure its properties. In addition, you will
build and deploy an ASP.NET Web site.
2-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
Objectives
After completing this lab, you will be able to:
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following user name and password:
• User name: Student
• Password: Pa$$w0rd
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-55
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses Microsoft .NET applications to create,
customize, and manage its customer information.
Your organization decides to create a Web site for fast and easy interaction with its
customers. In addition to external Customers Web site, your organization plans to
create a Web site to manage customer data and services in ASP.NET.
You are assigned the task of creating the Web site by using the ASP.NET Web site
template, and then deploying the Web site to an IIS virtual directory.
2-56 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: It may take a few seconds before the Port number property is ready for editing
after setting the Use dynamic ports property.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-57
Results: After completing this exercise, you will have created a file system–based
ASP.NET site, and added styles to the Web site.
2-58 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: The Default Web Form displays in Source view, where you can notice that the
elements such as form, div, and body, are empty.
• Save the changes, and view the default Web Form in a Web browser, by using
the View in Browser context menu command.
Note: You can now view the text that you have entered in the Literal control.
Note: You can now view the changes that you have made to the Literal control.
Result: After completing this exercise, you will have designed the initial version of
the default Web Form for your Web site.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-61
X Task 2: Turn off the virtual machine and revert the changes.
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Result: After completing this exercise, you will have built and deployed the
CustomerManagement Web site to the local IIS.
2-62 Introduction to Web Development with Microsoft® Visual Studio® 2010
Section 2: Visual C#
Exercise 1: Creating an ASP.NET Web Site
The main tasks for this exercise are as follows:
1. Create an empty ASP.NET Web site.
2. Use a static port with the ASP.NET Development server.
3. Save the Solution file.
Note: It may take a few seconds before the Port number property is ready for editing
after setting the Use dynamic ports property.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-63
Results: After completing this exercise, you will have created a file system–based
ASP.NET site, and added styles to the Web site.
2-64 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: The Default Web Form displays in Source view, where you can see the elements
such as form, div, and body, are empty.
Note: You can now view the text that you have entered in the Literal control.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-65
Note: You can now view the changes that you have made to the Literal control.
Results: After completing this exercise, you will have designed the initial version of
the default Web Form for your Web site.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-67
X Task 2: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have built and deployed the
CustomerManagement Web site to the local IIS.
2-68 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Review
Tools
Editor window Displays code for editing and a Visual Studio IDE
graphical interface for control
placement.
Task List Enables you to track the status of Visual Studio IDE
tasks as you develop your
application.
Module 3
Creating a Microsoft® ASP.NET Web Form
Contents:
Lesson 1: Creating Web Forms 3-3
Lesson 2: Adding and Configuring Server Controls in a Web Form 3-12
Lab: Creating a Microsoft ASP.NET Web Form 3-37
3-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
Microsoft® ASP.NET Web Forms are the user interface (UI) elements that give your
Web applications their look and feel. A Web Form presents information to the user
in any type of browser, and it implements application logic by using server-side
code. Microsoft Visual Studio provides an intuitive drag-and-drop interface to help
create the UI for your Web application. In this module, you will learn how to create
Web Forms, and populate them with server controls.
Creating a Microsoft® ASP.NET Web Form 3-3
Lesson 1
Creating Web Forms
Web Forms consist of a combination of markup, code, and controls that run on a
Web server, such as Internet Information Services (IIS). Web Forms are commonly
referred to as ASP.NET pages, or .aspx pages. You can create Web Forms by using
Microsoft Visual Basic® or Microsoft Visual C#®. When creating Web Forms, you
can choose whether or not to place the code in a separate file.
In this lesson, you will learn what a Web Form is, and how to create a Web Form.
You will also learn how to identify the key characteristics of Web Forms.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe an ASP.NET Web Form.
• Explain how to create an ASP.NET Web Form.
3-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
Web Forms are the containers for the text and controls that you want to display in
the browser. Web Forms generate Hypertext Markup Language (HTML), and send
it to the browser. However, controls that run the UI remain on the Web server.
This split between the client-side interface and the server-side code is a crucial
difference between Web Forms and traditional Web pages. On a traditional Web
page, the browser on the client side processes the code. By contrast, Web Forms
send only the markup and any client-side script to the browser, while the page
processing remains on the server. This split between the client-side interface and
the server-side code increases the number of supported browsers, and enhances
the security and functionality of the Web page.
[Visual Basic]
<%@ Page Title="" Language="VB" CodeFile="Default.aspx.vb"
Inherits="_Default" %>
[Visual C#]
<%@ Page Title="" Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
3-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: When you create a Web Form and select the option to place code in a separate
file (which is the default), the CodeFile and Inherits attributes are used in a two-file
configuration. Single-file Web Forms do not use these attributes.
<html>
...
</html>
3-8 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: You can use CSS to describe the look and formatting of a Web Form, or to style
HTML Web pages, by specifying the colors, fonts, borders, and layout. CSS helps separate
the markup from the presentation. This introduces reuse of styles across more than a
single Web Form to cover an entire Web site. Although styles are reused, different styles
will generally be applied to different pages. In Visual Studio 2010, you can use the Apply
Styles window to apply styles to a specific HTML element or Web server control, and you
can use the Manage Styles window to manage and keep track of all the styles in your
Web application. Both of these windows are accessible from the View menu.
Question: What are the two components that make up Web Forms?
3-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
When you create a new, empty Web application or an empty Web site in Visual
Studio 2010, only a web.config file is included.
Visual Studio 2010 creates a new Web Form and adds it to the existing Web
project or Web site.
Question: Which tool can you use to add additional Web Forms if you are
expanding an existing project?
3-12 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 2
Adding and Configuring Server Controls in a
Web Form
ASP.NET server controls run on the server and encapsulate UI and other related
functionalities. These server controls—such as buttons, text boxes, and lists—are
different from standard HTML controls in that the supporting logic runs on the
server, and not in the user's browser.
In this lesson, you will learn how to use ASP.NET server controls.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe an ASP.NET server control.
• Describe the types of server controls.
• Save the View state of server controls.
Creating a Microsoft® ASP.NET Web Form 3-13
Key Points
ASP.NET server controls run on the server and encapsulate the UI. You can use
server controls in ASP.NET Web Forms, and use them to respond to events in
ASP.NET Web Form code-behind classes.
The following is an example of a Button Web server control.
runat="server"
Server controls have a runat attribute, which can only be set to the value of server.
Note: In some situations, server controls require a client script to function correctly. If a
user has disabled scripting in the browser, the controls might not function as you intend.
However, most of the intrinsic controls will work correctly with or without client-side
scripting.
Another feature of server controls is that the View state, the settings, and the user
input for the control are automatically saved when the page passes between the
client and the server. Traditional HTML elements are stateless and revert to their
default settings when the page returns from the server to the client.
Note: For more information about View state, see the “Saving View State" topic later in
this lesson.
Built-in Functionality
The functionality of a server control relates to what happens when the user clicks a
command button or a list box. These processes are called event handlers. As a Web
Form programmer, you need to determine the event handlers that will be
implemented for each server control.
When a user using Internet Explorer 8 accesses this page, the common language
runtime creates the following HTML element, which is customized for Internet
Explorer 8.
Because the server control creates customized HTML for the features that are
available in the client's browser, you can write code for the newest browsers and
not be concerned about browser errors. Your code will work even if users do not
have the latest browser versions.
Key Points
ASP.NET has many different available server controls. Some server controls closely
resemble traditional HTML elements, while other server controls are specific to
ASP.NET. The wide range of controls helps you customize your Web Form to
match your application.
The following table lists some of the most commonly used HTML elements. Both
HTML server controls and Web server controls are rendered as one or more of
these elements.
Element
name Description Example
a An anchor element that <a href="/Page2.aspx"
links to another page, title="Go To Page 2.">Page 2</a>
image, or other resource.
Intrinsic standard Web server controls correspond to simple HTML elements. The
following table describes some of the commonly used intrinsic Web server
controls.
Complex standard controls insert complex functions into your Web Form. The
following table describes some of the complex controls.
Control Function
FileUpload Provides users with a way to upload a file from to the server.
Data Controls
Data controls contain two groups of controls: data-bound controls, and data source
controls:
• Data-bound controls. Data-bound controls are used to display data from a data
source.
• Data source controls. Data source controls are used as an intermediary control
between a data source such as a database or an XML file, and one or more data
controls.
Note: For more information about data controls, see Module 8, "Managing Data in a
Microsoft ASP.NET 4.0 Web Application."
3-22 Introduction to Web Development with Microsoft® Visual Studio® 2010
The following table describes some of the most common data-bound controls.
Control Function
QueryExtender Used to create filters for data that is retrieved from a data
source. The control can be used to filter data in the markup
of a Web page by using a declarative syntax.
The following table describes some of the commonly used data source controls.
Control Function
Note: For more information about LINQ, see Module 9, "Managing Data Access Tasks by
Using LINQ."
Validation Controls
Validation controls are hidden controls that validate user input against
predetermined patterns. If the user input does not conform to the requirements, an
error message displays.
Validation controls incorporate logic that allows you to test user input. To test user
input, you can associate a validation control with the input control, and then
specify the conditions for valid user input.
Note: For more information about validation controls, see Module 6, "Validating User
Input."
3-24 Introduction to Web Development with Microsoft® Visual Studio® 2010
Control Function
Login Controls
Login controls work together to provide a robust login solution that requires very
little code.
Note: For more information about login controls, see Module 15, "Securing a Microsoft
ASP.NET Web Application."
Creating a Microsoft® ASP.NET Web Form 3-25
Control Function
LoginStatus Displays a login link for users who log in, and a logout link
for logged-in users.
Navigation Controls
Navigation controls are used to create navigational aids on ASP.NET Web pages,
including menus and breadcrumbs. The following table describes the navigation
controls.
Control Function
Adding the attribute runat="server" converts the preceding HTML button control
into an HTML server control that will run on the server. Note that in addition to
the runat="server" attribute, you must add an id attribute for the control to
function as a server control.
The following example is of an HTML server control button.
Key Points
One of the difficulties for Web sites is to save the state of controls (settings and
user input) while the HTML is sent back and forth between the client and the
server. It is true for any HTTP-based technology that Web Forms are stateless by
nature, which means that the server does not retain any information between client
requests.
ASP.NET Web Forms saves the state of controls by adding the hidden control
__VIEWSTATE, which records the state of the controls on the Web Form.
Specifically, Web Forms adds __VIEWSTATE to the server-side form element, and
only records the state of controls in this section. As the page travels back and forth
from the client to the server, the server control state is kept with the page and can
be updated at either the client or at the server end of the transaction.
3-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
View state is the method that the ASP.NET page framework uses to preserve page
and control values between round trips. When the HTML markup for the page is
rendered, the current state of the page and values that must be retained during
postback are serialized into base 64-encoded strings. These values are then entered
into the View state hidden field. This process makes it easier for server controls to
automatically retain their values between server round-trips, without any coding.
View state is only useful within the same Web Form as it travels back and forth
between the client and server. You cannot use View state between different Web
Forms. View state lowers the server load, but performance can suffer because of the
increased HTML size, which means that it takes longer to render the page on the
client.
Because the state of the Web page is kept inside the server form, the Web page can
be randomly routed in a Web server farm, and does not have to keep returning to
the same server. The advantage of the View state process is that the programmer
can focus on the page’s design, and does not have to build infrastructure to track
Page state.
You can use View state to persist application data that is specific to a single page,
including a product ID or a user ID. You can also use View state in other scenarios,
such as for statistical reasons if you want to know how many times a user
postbacks the same page in sequence to the server.
To disable the View state for a specific control, set the EnableViewState attribute
of the control to false. The following code illustrates this. Keep in mind that if the
EnableViewState attribute of the Page directive is set to false, you cannot override
this for an individual control on that page.
You can also use the ViewStateMode property to control how View state is
enabled for individual controls, such as when View state is disabled for a page.
You can use the ViewStateMode property to enable View state for an individual
control even if View state is disabled for the page (as shown in the sample code
above), or to disable View state for an individual control when View state is
enabled for the page.
The ViewStateMode property can be set to one of the following values:
Value Description
Inherit Inherits the value of the ViewStateMode property from the parent
control or page.
Enabled Enables View state for this control even if the parent control has View
state disabled.
Disabled Disables View state for this control even if the parent control has View
state enabled.
Control State
ASP.NET control state allows you to store information that is specific to the control
and cannot be disabled.
Controls can have both View state and control state. You use the View state to
maintain the control's content, and the control state to maintain the core behavior
of the control. For controls that must repopulate their content each time the user
requests a page—such as a control that displays a grid of data—you can disable the
View state but not the control state.
3-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
HiddenField Control
You can use the HiddenField Web server control as an additional method to store
a value that you want to persist across posts to the server. You use the Value
property to specify the value of the control, and create an event handler for the
ValueChanged event. This event is called each time the value of the control
changes between posts to the server. The following code shows how to declare a
HiddenField control with a value of 1.
Key Points
HTML controls on a Web Form are not available to the server. By converting
HTML controls to HTML server controls, you can expose them as elements to your
server-side code. This conversion allows you to use the controls to trigger events
that are handled on the server.
HTML server controls include the runat="server" attribute and must reside in a
containing FORM element.
The advantage of HTML server controls is that they help you quickly update
existing pages to Web Forms. In addition, you can optimize the performance of a
page by determining and adjusting the controls so that they work locally on the
browser, but are processed on the server.
3-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
The following code is generated when you use the drag and drop operation to
move the control from the Toolbox to the Web Form.
When rendered to the client, the TextBox control looks like the following code
example.
Question: What are the additional features offered by Web server controls?
Creating a Microsoft® ASP.NET Web Form 3-35
Key Points
When you create ASP.NET pages, you can use HTML elements, HTML server
controls, or Web server controls. You can mix these control types on the same
page to quickly update an HTML page.
As an example of mixing control types, your ASP.NET page might include: an
HTML span element that lists the local time; an HTML server control button
converted from an HTML element; and a Web server control text box that accesses
data from the server. However, the best practice is to avoid HTML server controls.
Web server controls are more capable, and have a richer object model than HTML
server controls.
Note: You can perform tasks in this lab either by using the Visual Basic or Visual C#
programming language. If you are using Visual Basic as your programming language,
refer to the steps provided in Section 1 of the lab page. If you are using Visual C# as
your programming language, refer to the steps provided in Section 2 of the lab page.
Introduction
In this lab, you will add a Web Form to an ASP.NET Web application, then add
server controls to the Web Form, and then configure its properties.
Objectives
After completing this lab, you will be able to:
• Create a new Web Form.
• Apply a style sheet to the Web Form.
• Create a table-style layout in the Web Form.
3-38 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Add a server control to the Web Form and configure its properties.
• Apply styles to the HTML elements and server controls.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• Password: Pa$$w0rd
Creating a Microsoft® ASP.NET Web Form 3-39
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses Microsoft .NET applications to create,
customize, and manage its customer information. Your organization has created a
Web site to manage customer data and services in ASP.NET.
Contoso, Ltd wants to create an application to maintain and update its customer
information. You need to customize the application to meet the specific
requirements of the sales team. Updating the customer information is an ongoing
process for the sales team, and the application requires updates based on the
feedback from senior developers and other stakeholders. You need to build a UI
that meets the defined requirements.
You must create an application and build a user interface that is easy to update and
modify, by using ASP.NET server controls.
3-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
Results: After completing this exercise, you will have opened the existing
CustomerManagement Web site, and added the InsertCustomer Web Form.
Creating a Microsoft® ASP.NET Web Form 3-41
Note: In this exercise, you are creating a two-column table using CSS for holding various
controls used for displaying and managing Customer data.
<div>
<div>
</div>
</div>
3-42 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Add two new div elements from the Toolbox to the newly added div element.
<div>
<div>
<div>
</div>
<div>
</div>
</div>
</div>
• Add 11 more table rows by copying the existing div element with a class
attribute value of customerTableRow.
<div class="customerTableRow">
<div class="customerTableLeftCol">
</div>
<div class="customerTableRightCol">
</div>
</div>
• Append a new div element from the Toolbox to the div element with a class
attribute value of customerTable, placing the new div element immediately
before the closing div tag of the customerTable div element.
<div class="customerTable">
<div class="customerTableRow">
<div class="customerTableLeftCol">
</div>
<div class="customerTableRightCol">
</div>
</div>
...
<div>
</div>
</div>
Note: Notice that two equal-sized columns are added to the div element.
Note: Although you have styled the Web form by using the CSS file, notice that nothing
displays. This is because the div elements are empty.
f Task 3: Add the server controls to the Web Form and configure their
basic properties
• View the InsertCustomer Web Form in Design view.
• Add the Label control from the Toolbox to the first cell of the left column in
the div element, change the (ID) property to CustomerFirstNameLabel, and
then set the Text property to First Name:.
• Add the TextBox control from the Toolbox to the first cell of the right column
in the div element, and change the (ID) property to
CustomerFirstNameTextBox.
• Add the Label control from the Toolbox to the second cell of the left column
in the div element, change the (ID) property to CustomerLastNameLabel,
and then set the Text property to Last Name:.
• Add the TextBox control from the Toolbox to the second cell of the right
column in the div element, and change the (ID) property to
CustomerLastNameTextBox.
• Add the Label control from the Toolbox to the third cell of the left column in
the div element, change the (ID) property to CustomerAddressLabel, and
then set the Text property to Address:.
• Add the TextBox control from the Toolbox to the third cell of the right
column in the div element, and change the (ID) property to
CustomerAddressTextBox.
• Add the Label control from the Toolbox to the fourth cell of the left column in
the div element, change the (ID) property to CustomerZipCodeLabel, and
then set the Text property to Zip Code:.
• Add the TextBox control from the Toolbox to the fourth cell of the right
column in the div element, and change the (ID) property to
CustomerZipCodeTextBox.
• Add the Label control from the Toolbox to the fifth cell of the left column in
the div element, change the (ID) property to CustomerCityLabel, and then
set the Text property to City:.
• Add the TextBox control from the Toolbox to the fifth cell of the right column
in the div element, and change the (ID) property to CustomerCityTextBox.
Creating a Microsoft® ASP.NET Web Form 3-45
• Add the Label control from the Toolbox to the sixth cell of the left column in
the div element, change the (ID) property to CustomerStateLabel, and then
set the Text property to State:.
• Add the TextBox control from the Toolbox to the sixth cell of the right
column in the div element, and change the (ID) property to
CustomerStateTextBox.
• Add the Label control from the Toolbox to the seventh cell of the left column
in the div element, change the (ID) property to CustomerCountryLabel, and
then set the Text property to Country:.
• Add the DropDownList control from the Toolbox to the seventh cell of the
right column in the div element, and change the (ID) property to
CustomerCountryDropDownList.
• Add the Label control from the Toolbox to the eighth cell of the left column in
the div element, change the (ID) property to CustomerPhoneLabel, and then
set the Text property to Phone:.
• Add the TextBox control from the Toolbox to the eighth cell of the right
column in the div element, and change the (ID) property to
CustomerPhoneTextBox.
• Add the Label control from the Toolbox to the ninth cell of the left column in
the div element, change the (ID) property to CustomerEmailAddressLabel,
and then set the Text property to Email Address:.
• Add the TextBox control from the Toolbox to the ninth cell of the right
column in the div element, and change the (ID) property to
CustomerEmailAddressTextBox.
• Add the Label control from the Toolbox to the tenth cell of the left column in
the div element, change the (ID) property to CustomerWebAddressLabel,
and then set the Text property to Web Address:.
• Add the TextBox control from the Toolbox to the tenth cell of the right
column in the div element, and change the (ID) property to
CustomerWebAddressTextBox.
• Add the Label control from the Toolbox to the eleventh cell of the left column
in the div element, change the (ID) property to CustomerCreditLimitLabel,
and then set the Text property to Credit Limit:.
• Add the TextBox control from the Toolbox to the eleventh cell of the right
column in the div element, and change the (ID) property to
CustomerCreditLimitTextBox.
3-46 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Add the Label control from the Toolbox to the twelfth cell of the left column
in the div element, change the (ID) property to
CustomerNewsSubscriberLabel, and then set the Text property to News
Subscriber:.
• Add the CheckBox control from the Toolbox to the twelfth cell of the right
column in the div element, and change the (ID) property to
CustomerNewsSubscriberCheckBox.
• Save the changes, and view the InsertCustomer Web Form in a Web browser.
• Add the Button control from the Toolbox to the footer of the table in the div
element, change the (ID) property to CustomerInsertButton, and then set the
Text property to Insert.
• Add the Button control from the Toolbox to the footer of the table in the div
element, change the (ID) property to CustomerCancelButton, and then set
the Text property to Cancel.
• Save the changes, and view the InsertCustomer Web Form in a Web browser.
• Task 6: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have designed the initial version of the
InsertCustomer Web Form for your Web site.
3-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
Section 2: Visual C#
Exercise 1: Creating a Web Form
The main tasks for this exercise are as follows:
1. Open an existing ASP.NET Web site.
2. Add a Web Form to the Web site.
Results: After completing this exercise, you will have opened the existing
CustomerManagement Web site, and added the InsertCustomer Web Form.
Creating a Microsoft® ASP.NET Web Form 3-49
Note: In this exercise, you are creating a two-column table using CSS for holding various
controls used for displaying and managing Customer data.
<div>
<div>
</div>
</div>
3-50 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Add two new div elements from the Toolbox to the newly added div element.
<div>
<div>
<div>
</div>
<div>
</div>
</div>
</div>
• Add 11 more table rows by copying the existing div element with a class
attribute value of customerTableRow.
<div class="customerTableRow">
<div class="customerTableLeftCol">
</div>
<div class="customerTableRightCol">
</div>
</div>
• Append a new div element from the Toolbox to the div element with a class
attribute value of customerTable, placing the new div element immediately
before the closing div tag of the customerTable div element.
<div class="customerTable">
<div class="customerTableRow">
<div class="customerTableLeftCol">
</div>
<div class="customerTableRightCol">
</div>
</div>
...
<div>
</div>
</div>
Note: Notice that two equal-sized columns are added to the div element.
Note: Although you have styled the Web form by using the CSS file, notice that nothing
displays. This is because the div elements are empty.
3-52 Introduction to Web Development with Microsoft® Visual Studio® 2010
f Task 3: Add the server controls to the Web Form and configure their
basic properties
• View the InsertCustomer Web Form in Design view.
• Add the Label control from the Toolbox to the first cell of the left column in
the div element, change the (ID) property to CustomerFirstNameLabel, and
then set the Text property to First Name:.
• Add the TextBox control from the Toolbox to the first cell of the right column
in the div element, and change the (ID) property to
CustomerFirstNameTextBox.
• Add the Label control from the Toolbox to the second cell of the left column
in the div element, change the (ID) property to CustomerLastNameLabel,
and then set the Text property to Last Name:.
• Add the TextBox control from the Toolbox to the second cell of the right
column in the div element, and change the (ID) property to
CustomerLastNameTextBox.
• Add the Label control from the Toolbox to the third cell of the left column in
the div element, change the (ID) property to CustomerAddressLabel, and
then set the Text property to Address:.
• Add the TextBox control from the Toolbox to the third cell of the right
column in the div element, and change the (ID) property to
CustomerAddressTextBox.
• Add the Label control from the Toolbox to the fourth cell of the left column in
the div element, change the (ID) property to CustomerZipCodeLabel, and
then set the Text property to Zip Code:.
• Add the TextBox control from the Toolbox to the fourth cell of the right
column in the div element, and change the (ID) property to
CustomerZipCodeTextBox.
• Add the Label control from the Toolbox to the fifth cell of the left column in
the div element, change the (ID) property to CustomerCityLabel, and then
set the Text property to City:.
• Add the TextBox control from the Toolbox to the fifth cell of the right column
in the div element, and change the (ID) property to CustomerCityTextBox.
• Add the Label control from the Toolbox to the sixth cell of the left column in
the div element, change the (ID) property to CustomerStateLabel, and then
set the Text property to State:.
Creating a Microsoft® ASP.NET Web Form 3-53
• Add the TextBox control from the Toolbox to the sixth cell of the right
column in the div element, and change the (ID) property to
CustomerStateTextBox.
• Add the Label control from the Toolbox to the seventh cell of the left column
in the div element, change the (ID) property to CustomerCountryLabel, and
then set the Text property to Country:.
• Add the DropDownList control from the Toolbox to the seventh cell of the
right column in the div element, and change the (ID) property to
CustomerCountryDropDownList.
• Add the Label control from the Toolbox to the eighth cell of the left column in
the div element, change the (ID) property to CustomerPhoneLabel, and then
set the Text property to Phone:.
• Add the TextBox control from the Toolbox to the eighth cell of the right
column in the div element, and change the (ID) property to
CustomerPhoneTextBox.
• Add the Label control from the Toolbox to the ninth cell of the left column in
the div element, change the (ID) property to CustomerEmailAddressLabel,
and then set the Text property to Email Address:.
• Add the TextBox control from the Toolbox to the ninth cell of the right
column in the div element, and change the (ID) property to
CustomerEmailAddressTextBox.
• Add the Label control from the Toolbox to the tenth cell of the left column in
the div element, change the (ID) property to CustomerWebAddressLabel,
and then set the Text property to Web Address:.
• Add the TextBox control from the Toolbox to the tenth cell of the right
column in the div element, and change the (ID) property to
CustomerWebAddressTextBox.
• Add the Label control from the Toolbox to the eleventh cell of the left column
in the div element, change the (ID) property to CustomerCreditLimitLabel,
and then set the Text property to Credit Limit:.
• Add the TextBox control from the Toolbox to the eleventh cell of the right
column in the div element, and change the (ID) property to
CustomerCreditLimitTextBox.
3-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Add the Label control from the Toolbox to the twelfth cell of the left column
in the div element, change the (ID) property to
CustomerNewsSubscriberLabel, and then set the Text property to News
Subscriber:.
• Add the CheckBox control from the Toolbox to the twelfth cell of the right
column in the div element, and change the (ID) property to
CustomerNewsSubscriberCheckBox.
• Save the changes, and view the InsertCustomer Web Form in a Web browser.
• Add the Button control from the Toolbox to the footer of the table in the div
element, change the (ID) property to CustomerInsertButton, and then set the
Text property to Insert.
• Add the Button control from the Toolbox to the footer of the table in the div
element, change the (ID) property to CustomerCancelButton, and then set
the Text property to Cancel.
• Save the changes, and view the InsertCustomer Web Form in a Web browser.
f Task 6: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have designed the initial version of the
InsertCustomer Web Form for your Web site.
3-56 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Review
Best Practices
• Web Forms should expose a page title that displays as the browser caption,
and on the tab provided your browser session is tabbed. This makes it easier
for users to identify a specific page.
• Always use the appropriate Web server control for the task—such as using a
Label control instead of a TextBox control—to display read-only text.
• Follow a naming convention when naming your HTML elements and Web
server controls. In this course, a naming convention consisting of what the
control or element contains, and it is suffixed by the control type that is used,
such as FirstNameTextBox for a TextBox control that exposes the first name
of a person. This way, you can also have a FirstNameLabel Label control that
indicates to the user what the TextBox control contains. In general, all HTML
elements and Web server controls should be given a name or id, because you
might need to refer to the controls from other controls, or from either client-
side or server-side code.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-1
Module 4
Adding Functionality to a Microsoft® ASP.NET
Web Form
Contents:
Lesson 1: Working with Code-Behind Files 4-4
Lesson 2: Handling Server Control Events 4-14
Lesson 3: Creating Classes and Components by Using
Visual Studio 2010 4-37
Lesson 4: Handling Page Events 4-61
Lab: Adding Functionality to a Microsoft ASP.NET Web Form 4-72
4-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
You can add code to your Microsoft® ASP.NET Web application by using various
methods that would be based on your requirements. You can use inline code and
mixed code, but using code-behind files is the preferred method in Microsoft®
Visual Studio® 2010 for adding code to Web Forms.
Event handlers are procedures that handle an event, such as when a page is loaded
on the server or when a button is clicked. Event handlers for Web server controls
are usually triggered by user interaction, and provide the functionality for your
application. To create event handlers effectively, you must understand the page life
cycle. You must also be familiar with the page life cycle if you develop custom
controls. This is specifically true if you need to initialize controls, populate control
properties with View state data, and then run any control behavior code.
The code discussed in this module is entirely served-based code. This means the
code runs on the server, and all the code processing happens before a requested
page is returned to the client. This is also true, even when some server controls
automatically emit client-side code so that a user can interact with the control on
the client-side, without a server round-trip.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-3
In this module, you will learn the various methods to add code to your ASP.NET
Web application. You will also learn how to use Web server controls, event
handlers, code-behind files, and components. Finally, you will learn how to use
page events, especially the OnLoad event, which is handled by the Page_Load
event handler.
4-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 1
Working with Code-Behind Files
You can add mixed code to your Web Form in the same file as Web content. You
can also add code in the same file in a separate script section or in a separate file.
Inline code uses both HTML and code in separate sections of a single .aspx file.
Code-behind files contain the programming logic for a single Web page.
In this lesson, you will learn about three methods to add code using Visual Studio
2010. You will also learn about the differences between the methods.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the methods for adding code.
• Describe the difference between mixed code and inline code.
• Describe code-behind files.
• Explain how to use code-behind files to add functionality for Web Forms.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-5
Key Points
You can add code to your Web Form in the following three ways:
• Mixed code. The code is placed in the same file as the Web content,
intermingled with markup.
• Inline code. The code is placed in one or more separate script elements of the
same file as the markup content.
• Code-behind. The code is placed in a separate file from the markup content.
The code file is called a code-behind file. When you use Visual Studio 2010,
the default method is to place all the code in a code-behind file.
4-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Mixed Code
Mixed code is also known as embedded code blocks. Some developers use mixed
code, but this should be avoided because a mixed code file can be difficult to read
and maintain.
Inline Code
Although the default method for implementing server-side code in Visual Studio
2010 is to use a code-behind file, you may encounter pages that use inline code.
When you use inline code for a Web page, the markup and code are in separate
sections of a single .aspx file. This separation is for clarity. Functionally, however,
the code and HTML can exist anywhere on the page. Even if inline code does
separate the code from the markup, the code and markup are still mixed in the
same file, making it hard for two developers to work on markup and code at the
same time.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-7
[Visual Basic]
<html xmlns="http://www.w3.org/1999/xhtml">
...
<asp:Button ID="Button1" runat="server" Text="Button" />
...
</html>
<script Language="VB" runat="server">
Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
...
End Sub
</script>
[Visual C#]
<html xmlns="http://www.w3.org/1999/xhtml">
...
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
...
</html>
Question: How can you use the same method in Visual Basic as in Visual C#,
though the OnClick event is wired up differently for Visual Basic and Visual C#?
4-8 Introduction to Web Development with Microsoft® Visual Studio® 2010
Code-Behind Files
Key Points
The default method for implementing server-side code in Visual Studio 2010 is to
use code-behind files. When you use code-behind files, the programming logic is
kept in a separate file from the visual elements of the page. Separating the logic
from the design enables you to work on the code-behind file, while user interface
(UI) designers work on the ASP.NET page.
Code-behind files contain the programming logic for a single Web Form. Each
Web Form in a Web application has its own code-behind file. By default, a code-
behind file has the same name as the Web Form with which it is associated.
However, the code-behind file has an .aspx.vb or .aspx.cs extension, depending on
the language that is used in the code-behind file. For example, the Web Form,
Form1.aspx, will have a Visual C# code-behind file named Form1.aspx.cs, or a
Visual Basic code-behind file named Form1.aspx.vb.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-9
[Visual Basic]
Partial Public Class _Default
[Visual C#]
public partial class _Default
Note: A code-behind file can only contain code in a single language. You cannot mix
Visual C# and Visual Basic in the same code-behind file. However, you can mix Web
Forms and files of different languages in the same Web site.
The code-behind file is the default way to write code for ASP.NET Web Forms. It is
also the preferred method for many (if not most) developers. A code-behind file
generally contains a single class, with the name of the Web Form used as the name
of the class. The following code shows the Default Web Form (Default.aspx),
where the class is named _Default.
[Visual Basic]
Partial Class _Default
Inherits System.Web.UI.Page
End Class
[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
}
}
4-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
For the Web Forms that are based on code-behind files to work properly, each
.aspx page must be associated with a code-behind file, and that code-behind file
must be compiled before the information is returned to a requesting client
browser.
Each Web Form page consists of two separate files—the .aspx page, and the code-
behind file—that form a single unit when the Web application is run. The code-
behind Web Form can either be precompiled by Visual Studio 2010 when you
build the Web application project, or compiled just in time (JIT) when a user
accesses the page for the first time.
4-12 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: The Inherits attribute is case sensitive in Visual C#, and case insensitive in Visual
Basic.
Note: In Visual C#, the AutoEventWireUp attribute is set to true by default. The
designer automatically generates code to bind events to their event-handler methods. In
Visual Basic, this attribute is set to false by default. The designer performs this event
binding by using the Handles statement in the declaration of the event-handler method.
The following code shows the Page directive for a Web Form named Default.aspx.
[Visual Basic]
<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>
[Visual C#]
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
Adding Functionality to a Microsoft® ASP.NET Web Form 4-13
Precompilation
You can precompile an ASP.NET Web site project into one or more assemblies that
can be deployed, instead of deploying the actual source code. You can do this by
using the Publish Web Site option on the Build menu, or by right-clicking the
Web site in Solution Explorer, and then clicking Publish Web Site.
For more information about Web site deployment, see Module 14,
"Configuring and Deploying a Microsoft ASP.NET Web Application."
4-14 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 2
Handling Server Control Events
Event handlers help you handle user interactions on a Web Form. There are two
types of event handlers: client-side, and server-side. Client-side event handlers are
events that are handled on the computer that requests the Web Form. Server-side
event handlers require information to be sent to the Web server for processing,
and are generally more powerful than client-side event handlers, especially when it
comes to accessing server-side resources, such as a database.
When you develop your ASP.NET applications, you need to use client-side and
server-side event handlers appropriately. To do this, you must know the
advantages and disadvantages of using client-side and server-side event handlers,
so that you can determine the appropriate event type for your ASP.NET
applications. You also need to know how to add event handlers to Web server
controls.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-15
Lesson Objectives
After completing this lesson, you will be able to:
• Describe event handlers.
• Describe client-side event handlers.
• Describe server-side event handlers.
• Explain how client-side and server-side event handlers are processed.
• Describe the process of creating server-side event handlers.
• Explain how to create server-side event handlers.
• Work with Web server controls by using event handlers.
4-16 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
Dynamic and interactive Web Forms respond to user input or events. You can use
event handlers to handle those events that are triggered by user interaction on a
Web Form. ASP.NET is an object-oriented development platform, and objects most
often expose events. These events are triggered when a user starts or closes the
application, clicks a button, or places the pointer over a link in the application.
When an event is raised, it does not automatically trigger an action in the
application; to do this, you must write the code to handle the event.
A user interacting with a Web Form raises an event. You need to design the Web
application to perform appropriate tasks when an event is raised. An event handler
is the action that occurs in response to the raised event. Web Forms are event-
driven, although not in a straight-forward manner, because events do not occur in
the order expected for linear event processing. Events help you separate tasks. For
example, you can make the application perform a sorting task separately from the
main application. If a user cancels the sorting task, the application can catch a
cancel event that instructs the sorting process to stop.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-17
[Visual Basic]
<html>
...
<body>
<form runat="server">
...
<asp:Button ID="Button1" Text="Home" runat="server"/>
...
</form>
</body>
</html>
''' <summary>
''' Redirects to home page
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
' Redirect to home page
Response.Redirect("~/Default.aspx")
End Sub
4-18 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual C#]
<html>
...
<body>
<form runat="server">
...
<asp:Button ID="Button1" Text="Home" OnClick="Button1_Click"
runat="server"/>
...
</form>
</body>
</html>
/// <summary>
/// Redirects to home page
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
// Redirect to home page
Response.Redirect("~/Default.aspx");
}
Key Points
There are two types of event handlers: client-side, and server-side. Client-side event
handlers are events that are handled on the client computer that is requesting the
Web Form. When an event is triggered, information is not sent to the server;
instead, the client browser interprets the code and performs the action.
Client-side event handlers can only be used with HTML elements. You can also
have client-side events for server controls, but only for the portion of the server
control that is rendered, which is always one or more HTML elements. You can
attach client-side event handlers directly to a Web Server control by specifying it in
the event attribute, such as the onmouseover event as shown in the following
code.
4-20 Introduction to Web Development with Microsoft® Visual Studio® 2010
...
<script type="text/javascript">
function changeColor()
{
window.event.srcElement.style.color = "#FF0000";
}
</script>
...
<asp:Button id="Button1" runat="server" text="Button1"
onmouseover="changeColor();" />
You can also assign an event handler programmatically by using the Add method
of the Attributes property, as shown in the following code.
[Visual Basic]
Button1.Attributes.Add("onmouseover", "changeColor();")
[Visual C#]
Button1.Attributes.Add("onmouseover", "changeColor();");
The code requires that the JavaScript function be part of the markup. This can be
either explicit—as shown in the preceding example—or it can be done by registering
it as a server-side script. The JavaScript can also be located in an externally linked
file. Use the ClientScriptManager.RegisterClientScriptBlock method, which is
placed in the Page Load event handler, as shown in the following code.
[Visual Basic]
Dim buttonClientScriptManager As ClientScriptManager = Me.ClientScript
buttonClientScriptManager.RegisterClientScriptBlock(Button1.GetType(),
"changeColorScript",
"function changeColor() { window.event.srcElement.style.color =
'#FF0000'; }", True)
[Visual C#]
ClientScriptManager buttonClientScriptManager = this.ClientScript;
buttonClientScriptManager.RegisterClientScriptBlock(Button1.GetType(),
"changeColorScript",
"function changeColor() { window.event.srcElement.style.color =
'#FF0000'; }", true);
Adding Functionality to a Microsoft® ASP.NET Web Form 4-21
Key Points
Unlike client-side event handlers, server-side event handlers require information to
be sent to the Web server for processing. Although there is a performance penalty
for using server-side event handlers because of the server round-trip, server-side
event handlers are generally more powerful than client-side event handlers,
especially when it comes to directly accessing server-side resources, such as a
database.
[Visual Basic]
<script type="text/VB" runat="server">...</script>
[Visual C#]
<script type="text/C#" runat="server">...</script>
Event Support
There are a limited number of control events types that are supported by server-
side event handlers, because of the round trip to the Web server required by
server-side event handlers. With client-side event handlers, you can include code to
process mouse-key events and onChange events. Although server-side event
handlers support click events and a special version of the onChange event, they
cannot support events that occur frequently, such as mouse-key events. This would
severely hamper Web page performance, and essentially render an application
useless.
The following table shows some of the differences between client-side and server-
side event handlers.
Client-side Server-side
Compiled No Yes
Interpreted Yes No
Key Points
In this animation, you will see how client-side and server-side event handlers are
processed both on the client and on the server.
1. The client requests an ASP.NET Web Forms page from the Web server.
2. The server returns a page containing markup and script to the client. For
example, this page includes a TextBox control and a Submit button. The page
also contains client-side script that validates the contents of the text box.
3. The user enters invalid information in the text box, and the client-side script
generates a message box. Client-side processing reduces network traffic and
improves response times, because no information has been sent to the server.
4. The user corrects the information in the text box, and then clicks the Submit
button.
4-26 Introduction to Web Development with Microsoft® Visual Studio® 2010
5. The information is validated on the client side, and then sent to the server,
where server-side processing takes place.
6. The server repeats the validation, and stores the information from the text box
in a database.
7. Server-side resources can be used for other data processing, because the client-
side script does not directly access server resources.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-27
Key Points
To create a server-side event handler in Visual Studio 2010, you must perform
three steps:
1. Create the control that generates the event on the Web Form.
2. Provide the code for the event handler in the code-behind file that handles the
event.
3. Link the event handler to the control event. These steps can occur in any
order, depending on how you prefer to work.
4-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual Basic]
<form id="form1" method="post" runat="server">
<asp:Button ID="Button1" runat="server"/>
</form>
In the following Visual Basic code that shows the event handler for the Click event,
the Handles keyword indicates that the event handler runs in response to the
Click event of the Button1 control.
[Visual Basic]
Protected Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
...
End Sub
[Visual C#]
<form id="form1" method="post" runat="server">
<asp:Button ID="Button1" onclick="Button1_Click" runat="server"/>
</form>
Adding Functionality to a Microsoft® ASP.NET Web Form 4-29
The onclick attribute is set to the name of the event handler. In the code-behind
file, the Click property of the Button1 variable is handled as follows.
[Visual C#]
protected void Button1_Click(object sender, System.EventArgs e)
{
...
}
If you want more control over the manner in which event handlers are linked to
control events, you can manually create the link setting as follows.
[Visual C#]
Button1.Click += new EventHandler(Button1_Click);
Using this method, you can create multiple event handlers for a single event, or a
single event handler for multiple events.
4-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
In this demonstration, the instructor will show you how to create an event handler
for a button on a Web page that changes the text of a label. You can perform this
demonstration by using either Visual C# or Visual Basic.
Demonstration Steps
1. Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• To log on 10267A-GEN-DEV, use the following user credentials:
• User name: Student
• Password: Pa$$w0rd
2. Create a Web Site by using Visual Studio 2010.
• On the Start menu of 10267A-GEN-DEV, point to All Programs, click
Microsoft Visual Studio 2010, and then click Microsoft Visual Studio
2010.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-31
• In the Start Page – Microsoft Visual Studio window, on the File menu,
click New Web Site.
• In the New Web Site dialog box, in the left pane, click either Visual Basic
or Visual C#, in the middle pane, ensure that ASP.NET Empty Web Site
is selected, and then click OK.
3. Add a new Web Form named Default.aspx to the Web site.
• In Solution Explorer, right-click the Web site, and then click Add New
Item.
• In the Add New Item dialog box, in the middle pane, ensure that Web
Form is selected, in the Name box, type Default.aspx, and then click Add.
4. Add the Button and Label controls to the Web Form.
• In the Default.aspx window, click Design, and then point to Toolbox.
• In Toolbox, expand Standard, and then double-click the Button control.
• In Toolbox, under Standard, double-click the Label control.
5. View the default Click event handler code.
• In the Default.aspx window, double-click the Button control to open the
code-behind file.
• In the Default.aspx.vb or Default.aspx.cs window, view the empty event
handler created by Visual Studio 2010.
[Visual Basic]
Protected Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Button1.Click
...
End Sub
[Visual C#]
protected void Button1_Click(object sender, System.EventArgs
e)
{
...
}
4-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
6. Add the following code in the Click event handler of the Button control.
[Visual Basic]
Label1.Text = "You clicked the button"
[Visual C#]
Label1.Text = "You clicked the button";
[Visual Basic]
Protected Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Button1.Click
[Visual C#]
...
<asp:Button ID="Button1" runat="server" Text="Button"
onclick="Button1_Click"/>
...
8. Save the changes, and view the Web Form in the browser.
• Press the CTRL+SHIFT+S keys.
• In Solution Explorer, right-click the Default.aspx Web Form, and then
click View in Browser.
Note: Open the rendered source by clicking View Source on the Page menu, and notice
that the event handler code is not rendered to the client.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-33
Note: In the Visual Basic programming language, in the code-behind file, notice that the
Handles keyword was updated to reflect the new object name, SubmitButton.Click.
This maintains the binding to the correct event handler. The event handler name has not
been changed, and remains as Button1_Click.
In the Visual C# programming language, in the code-behind file, notice that the new
button name has been changed in the markup. The onclick attribute remains set to
Button1_Click. Visual Studio does not change the event binding to the procedure, but
only the ID property of the control.
Note: Notice that the Click event handler still triggers when you use the new name of
the control.
Key Points
In many Web applications, you need to write code to both read from controls on a
form, and write to controls on the same form. You can do this by using server-side
event handlers.
When the user clicks the button, the text that the user typed into the text box
displays. The following code assigns the string variable greetingString to a
concatenation of the text “Hello”, and the text in the NameTextBox text box.
4-36 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual Basic]
Dim greetingString As String = "Hello " & NameTextBox.Text
[Visual C#]
string greetingString = "Hello " + NameTextBox.Text;
For example, if a user types the text “Shannon” in the NameTextBox control, then
the greetingString variable would contain the text string “Hello Shannon”.
The following server-side code assigns the Text property of the GreetingLabel
Web server control to a text string.
[Visual Basic]
GreetingLabel.Text = "new text"
[Visual C#]
GreetingLabel.Text = "new text";
Lesson 3
Creating Classes and Components by Using
Visual Studio 2010
When you use an object-oriented language to develop an application, you can use
existing types and components. You can also use Visual Studio 2010 to create a
component, which you can then use in other applications.
In this lesson, you will learn about classes and components. You will also learn
how to create a component by using Visual Studio 2010, and then use that
component in other applications.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe types, components, and classes.
• Create a component.
4-38 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
When you use an object-oriented language such as Visual Basic or Visual C# to
develop an application, you can use existing types and components. For example,
the.NET Framework class library consists of many types, such as System.String
and System.Object.
Type Definition
Types are groups of code statements that have no user interface. Types can be
grouped into two distinct categories—structures, and classes. A structure is a value
type that is saved to the stack or in-line, and it is de-allocated when it goes out of
scope. By contrast, a class is a reference type that is saved on the heap, and the
management of the class memory is handled by the garbage collector. In general,
value types are cheaper to allocate and de-allocate.
4-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
Component Definition
Components consist of one or more types that are compiled into a dynamic-link
library (DLL) assembly. Because the component is a unit of deployment, and
usually is a single file, you can reuse it in different parts of an application or even in
different applications. You can reference a component from an application and
access the component's types.
Class
In object-oriented languages, the concept of abstraction is important. Abstraction is
a form of organization in which methods, data, and functions that serve a common
purpose are grouped together. A fundamental component of abstraction is the
creation and use of classes. A class is a template for an object. This template defines
attributes for storing data, and defines operations for manipulating that data. A
class also defines a set of restrictions that you can use to allow or deny access to its
attributes and operations.
You can create a class in any Visual Studio 2010 project. You can also create a new
class library, which by default contains only a single class and its methods, but no
UI. If you create a class in an existing project, the class exists in the project
namespace. If you create a new class library, Visual Studio 2010 creates a default
namespace, and then places the new class in that namespace.
When you create a class in a project, the class file is compiled into the application
assembly and cannot be reused by other applications. If you create a class library,
you create a component that you can reuse.
Question: What are the differences between a structure, class, property, method,
object, and component?
4-42 Introduction to Web Development with Microsoft® Visual Studio® 2010
Creating a Component
f To create a component
1. In Visual Studio 2010, on the File menu, click New Project.
2. In the New Project dialog box, in the left pane, click either Visual Basic or
Visual C#.
3. In the middle pane, click Class Library.
4. In the Name box, type the name of the class library, and then click OK.
5. On the Build menu, click Build Solution to create the component for the new
class.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-43
[Visual Basic]
Namespace YourComponentNamespace
Public Class Class1
End Class
End Namespace
Key Points
In this demonstration, you will see how to create a class library, and then call it
from a Web application.
Demonstration Steps
1. Create a Class Library project named HelloWorld in the Visual Studio 2010
solution.
a. On the Start menu of 10267A-GEN-DEV, point to All Programs, click
Microsoft Visual Studio 2010, and then click Microsoft Visual Studio
2010.
b. On the File menu of Visual Studio 2010, click New Web Site.
c. In the New Web Site box, in the left pane click either Visual Basic or
Visual C#, in the middle pane, ensure that ASP.NET Empty Web Site is
selected, in the Web location list, click File System, in the text box, type
C:\WebSite1, and then click OK.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-45
Note: Notice that a default class (either Class1.vb or Class1.cs), is created in Solution
Explorer and opens in the Code editor window.
[Visual Basic]
Function SayHello() As String
Return "Hi from Visual Basic component."
End Function
[Visual C#]
public string SayHello()
{
return "Hi from C# component.";
}
Key Points
After you create the class, you add the member variables and constants, which are
typically private to the class. Remember that adding member variables and
constants is an ongoing process, as you develop your class. The member variables
are often used as backing fields for public properties, because they store the values
that a property sets or gets. The following examples show the Customer class that
contains three private member variables and constants. The namespace has been
omitted.
[Visual Basic]
Public Class Customer
' The default credit limit
Private Const creditLimit As Integer = 50000
' Current customer ID (nullable)
Private customerID? As Guid = Nothing
' Current customer name
Private customerName As String = Nothing
End Class
4-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual C#]
class Customer
{
// The default credit limit
private const int creditLimit = 50000;
// Current customer ID (nullable)
private Guid? customerID = null;
// Current customer name
private string customerName = null;
}
Note: Adding member variables and constants, constructors, properties, and methods to
a class can be done in any order, and not just the way that they are listed in this topic.
However, constructors, methods, and properties often reference the member variables,
so it makes sense to start with the member variables. Remember that this is an ongoing
and iterative process, especially for larger classes where you may not be clear about the
data and operations to add.
The customerID backing field is a globally unique identifier (GUID) type, but it is
also nullable, which is denoted by using the ? suffix. A GUID is a value type, which
means it always holds a value. This is in contrast to reference types that can be set
to null (Nothing in Visual Basic), in which case, they are set to contain nothing–
they have no value. However, value types can be made nullable, which means they
can be set to null or Nothing, just like reference types. This can make it easy to
determine if a variable of a nullable type has an initial value assigned.
Note: A data type is a value type if it holds the data within its own memory allocation on
the stack. A reference type contains a pointer on the stack to another memory location
on the heap that holds the actual data.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-49
[Visual Basic]
#Region "Member fields"
' The default credit limit
Private Const creditLimit As Integer = 50000
...
#End Region
[Visual C#]
#region Member fields
// The default credit limit
private const int creditLimit = 50000;
...
#endregion
Code often contains constant values that are used throughout a type. Constant
values (often called constants) can also be used to give a friendly name to certain
numbers that are difficult to remember or have no obvious meaning. In such cases,
you can improve the readability of your code and make it easier to maintain by
using constants. A constant is a meaningful name that takes the place of a number
or string that does not change. Constants store values, which, as the name implies,
remain constant throughout the execution of an application.
You declare a constant with the Const/const statement by using the same
guidelines you would for creating a variable name. In Visual Basic, if Option Strict
is On, you must explicitly declare the constant type.
A constant's scope is the same as that of a variable declared in the same location.
To create a constant that exists within the scope of a particular procedure, declare
it inside that procedure. To create a constant that is available throughout an
application, declare it by using the Public keyword in the declarations section of
the class. Although constants resemble variables, you cannot modify them or
assign new values to them, as you can to variables. The constants that you use in
your code can be intrinsic to the object model for controls or components that you
work with, or they can be user-defined.
Key Points
After you have created the class and added the member variables, you can add the
properties for public or private access to those member variables. The following
examples show two properties for the Customer class.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-51
[Visual Basic]
''' <summary>
''' The unique customer ID
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ID() As Guid?
Get
Return Me.customerID
End Get
Private Set(ByVal value As Guid?)
Me.customerID = value
End Set
End Property
''' <summary>
''' The full customer name
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Name() As String
Get
Return Me.customerName
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerName = ""
Else
' Only get the first 50 characters
If (value.Length > 50) Then
Me.customerName = value.Substring(0, 50)
Else
Me.customerName = value
End If
End If
End Set
End Property
4-52 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual C#]
/// <summary>
/// The unique customer ID
/// </summary>
public Guid? ID
{
get
{
return this.customerID;
}
private set
{
this.customerID = value;
}
}
/// <summary>
/// The full customer name
/// </summary>
public string Name
{
get
{
return this.customerName;
}
set
{
// Null value?
if (value == null)
this.customerName = "";
else
// Only get the first 50 characters
if (value.Length > 50)
this.customerName = value.Substring(0, 50);
else
this.customerName = value;
}
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-53
The two read-write properties, ID and Name, are public to any user of the class.
Notice that the setters and getters—which are used to set and get the value of the
property or the property-backing field—can have a different access modifier than
the property itself. For the Name property, no access modifier has been specified
for the getter or setter, so the property access modifier public, is applied. However,
for the ID property, only the getter inherits the access modifier from the property,
whereas the setter is private. Because the setter is private, you can only set the
property from within the class. This helps ensure that the ID is not changed after
the class has been instantiated.
[Visual Basic]
''' <summary>
''' Returns the total order amount for the current customer until
today
''' </summary>
''' <param name="startDate">Start accumulating from this date</param>
''' <returns>The total order amount</returns>
''' <remarks></remarks>
Public Function GetTotalOrderAmount(ByVal startDate As DateTime) As
Double
' Get total order amount from database
Return dbObject.GetOrderTotal(ID, startDate)
End Function
[Visual C#]
/// <summary>
/// Returns the total order amount for the current customer until
today
/// </summary>
/// <param name="startDate">Start accumulating from this date</param>
/// <returns>The total order amount</returns>
public double GetTotalOrderAmount(DateTime startDate)
{
// Get total order amount from database
return dbObject.GetOrderTotal(ID, startDate);
}
4-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
The dbObject is a private object that accesses the Customers table in a database,
passing the ID of the customer and the starting date from which to accumulate the
order amount, and then returning the total order amount for the customer.
If you do not need to control either the naming of the backing field, or how the
value is assigned to a backing through a property, you can use auto-implemented
properties. Auto-implemented properties help you write your code more quickly,
and make your code easier to read. The following is an example of an auto-
implemented property.
[Visual Basic]
Public Property Name() As String
[Visual C#]
public string Name { get; set; }
When the compiler sees the code, it will automatically generate the code for the
backing field and the getters and setters.
Key Points
Any class—unless it is made abstract—needs at least one constructor for
instantiating an instance of the class. Abstract classes cannot be instantiated, and
are primarily created as a generic type from which you must derive or inherit your
own classes. A constructor is used to instantiate and initialize the class. The
following examples show two constructors for the Customer class.
4-56 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual Basic]
''' <summary>
''' Default parameterless constructor
''' </summary>
''' <remarks></remarks>
Public Sub New()
' Initialize member backing fields with default values
Me.ID = Guid.NewGuid()
End Sub
[Visual C#]
/// <summary>
/// Default parameterless constructor
/// </summary>
public Customer()
{
// Initialize member backing fields with default values
this.ID = Guid.NewGuid();
}
Notice how the constructors assign values to the backing fields through the
properties, and does not assign values directly. This is a best practice to follow,
because the properties can contain any logic to restrict values that can be assigned
to the backing fields. You can add the same logic to the constructors, but that
would duplicate the code.
If the same type of code—and potentially large chunks of code (such as generic
constructors)—is used by several developers, it is often a good idea to create and
distribute a code snippet. A code snippet is available from within the Text Editors
and Code Editors within Visual Studio at the appropriate location.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-57
Key Points
Once you create public types in a component, you can make those components
available to other programs. To do this, you must first reference the DLL
component. (The component does not necessarily have to be a .NET Framework
component; it can be another project in your solution, or a Component Object
Model DLL (COM DLL)). Then, to access the methods in the class, you must
instantiate the class object by referencing its namespace and class name.
Note: If you keep the Web application project and the class library project in the same
solution, any changes that you make to the component are automatically reflected by
the reference.
[Visual Basic]
Dim currentCustomer As New ComponentNamespace.Customer
[Visual C#]
ComponentNamespace.Customer currentCustomer = new
ComponentNamespace.Customer();
You can also use the using (Visual C#) statement or Imports (Visual Basic)
statement to import the namespace, and then instantiate the class directly. The
following examples illustrate this.
[Visual Basic]
Imports ComponentNamespace
...
Dim currentCustomer As New Customer
[Visual C#]
using ComponentNamespace;
...
Customer currentCustomer = new Customer();
4-60 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual Basic]
Dim total as Double = currentCustomer.GetTotalOrderAmount(startDate)
[Visual C#]
double total = currentCustomer.GetTotalOrderAmount(startDate);
Adding Functionality to a Microsoft® ASP.NET Web Form 4-61
Lesson 4
Handling Page Events
When an ASP.NET page runs, the page goes through a life cycle in which it
performs a series of processing steps. These include initializing the page and
controls, instantiating controls, restoring and maintaining the state, running the
event handler code, and rendering. You must understand the page life cycle so that
you can write code at the appropriate life-cycle stage for the effect that you intend.
Additionally, if you develop custom controls, you must know the page life cycle to
correctly initialize controls, populate control properties with View state data, and
run any control behavior code.
In this lesson, you will learn how to use page event handlers. You will learn about
the page event life cycle, and the postback process and event order. You will also
learn how to use the Page.IsPostBack property to control code execution when
the page is initially requested.
4-62 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson Objectives
After completing this lesson, you will be able to:
• Describe a page event life cycle.
• Describe the postback process.
• Handle postbacks.
• Explain how to handle page events.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-63
Key Points
When an ASP.NET page is requested, there are a series of page events that occur.
These events always occur in the same order, which is referred to as the page event
life cycle.
The end of the page event life cycle disposes of the page from memory.
Most control events do not occur until the Web Form is posted back to the server.
For example, Change events are handled in a random order on the server after the
form is posted. Conversely, Click events can cause the form to be sent to the server
immediately.
For example, if a user enters text into a number of controls on a form and then
clicks a Submit button, the Change events for the text controls will not be
processed until the form is sent to the server in response to the Click event.
Question: What are the page life cycle events that are used most frequently?
Adding Functionality to a Microsoft® ASP.NET Web Form 4-65
Key Points
To understand the postback process, you need to know how forms work in
ASP.NET, how the code in the Page_Load event handler can be made to run only
the first time a page is displayed, and how controls can be made to post back to the
server immediately.
• The first time that a user requests a page from the server, the test for
Page.IsPostBack in the Page_Load event succeeds and the code in the block
runs.
• The server then returns the page to the user.
• When the user changes the selection in the list box, and then clicks the
Submit button, the information is sent back to the server.
• The server can determine that this is a page that is being posted back to itself.
Therefore, the test for Page.IsPostBack in the Page_Load event fails, and the
code in the block does not run.
4-66 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Instead, the event handlers for the controls on the form (the list box and the
button) run. In this scenario, the list box event handler changes the label to
reflect the new list box selection.
• The server then returns the updated information to the client. The user views
the same page, but the label has now changed to reflect the list box selection.
• If you want the new value of the list box to be sent to the server immediately,
and you do not want to wait for the user to click the Submit button, you can
set the list box control’s AutoPostBack property to True.
• With the AutoPostBack property set to True, as soon as the user changes the
selection in the list box, the information is sent to the server.
• The server updates the label to reflect the change, and then sends the updated
information back to the client.
Question: Which property can be used in all events, and not just the Load event?
Adding Functionality to a Microsoft® ASP.NET Web Form 4-67
Handling Postbacks
Key Points
The Page_Load event runs on every request for a page, whether it is the first
request for the page, or a postback.
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Executes only on initial page load.
}
Key Points
In this demonstration, you will view the order of the page events, including the
event handlers and the page output.
Demonstration Steps
In this next demonstration, you will be shown the order of the page events,
including the event handlers and the page output. You can perform these tasks by
using either Visual Basic or Visual C#.
It is important to understand the order in which events are triggered, and when
you need to distinguish between a postback and a non-postback of a page.
3. Switch to Visual Studio 2010, and view the simple code and the Page_Unload
event handler.
• Switch to the Visual Studio 2010 window by clicking the Visual Studio
taskbar button in the taskbar.
• In Solution Explorer, expand Default.aspx, right-click either
Default.aspx.vb or Default.aspx.cs, and then click Open.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-71
[Visual Basic]
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Unload
If Not Me.IsPostBack Then
NonPostBackEventLabel.Text &= "Unload event<br />"
Else
PostBackEventLabel.Text &= "Unload event<br />"
End If
End Sub
[Visual C#]
protected void Page_Unload(object sender, EventArgs e)
{
if (!this.IsPostBack)
NonPostBackEventLabel.Text += "Unload event";
else
PostBackEventLabel.Text += "Unload event";
}
Question: Describe the use of the Events button in the Properties window.
4-72 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: You can perform the tasks in this lab either by using the Visual Basic or the
Visual C# programming language. If you are using Visual Basic as your programming
language, refer to the steps provided in Section 1 of the lab document. If you are using
Visual C# as your programming language, refer to the steps provided in Section 2 of the
lab document.
Introduction
In this lab, you will implement the code and the event procedures on an ASP.NET
Web site, and then create a component, which you will reference from the Web
application. In addition, you will implement page and server control events on the
Web site.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-73
Objectives
After completing this lab, you will be able to:
• Implement code in a Web application.
• Create event procedures.
• Create an entity component, and then reference it from a Web application.
• Handle page and server control events.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
4-74 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses Microsoft .NET applications to create,
customize, and manage its customer information.
Your organization is using a separate Web site for fast and easy interaction with its
customers. The organization wants to make its Web site dynamic to enable users to
enter and save customer details with minimum turnaround time.
To do this, you need to attach the required code to the UI that enables the
application to respond to user actions and other events. In addition, you need to
ensure that the application achieves a specified performance level by adding the
code in a code-behind class file that is precompiled, thus saving considerable
processing.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-75
Results: After completing this exercise, you will have opened the existing
CustomerManagement Web site, and the InsertCustomer Web Form code-behind
file.
4-76 Introduction to Web Development with Microsoft® Visual Studio® 2010
f Task 1: Create an event procedure for the Click event of the Insert
button
• Open the InsertCustomer Web Form in the Design view, and create an event
procedure for the Click event of the Insert button, by double-clicking the
Button control.
Note: Notice that the initial event procedure for the Click event of the
CustomerInsertButton control is added in the code window.
f Task 2: Create an event procedure for the Click event of the Cancel
button
• Open the InsertCustomer Web Form in the Design view, and create an event
procedure for the Click event of the Cancel button, by double-clicking the box
next to the Click event in the Properties window, with the Button control
selected in the Designer.
Note: Notice that the initial event procedure for the Click event of the
CustomerCancelButton is added to the class in the code window.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-77
End Sub
End Sub
End Sub
Results: After completing this exercise, you will have created event procedures for
button controls, Page_Load event, Page_LoadComplete event, and Page_Unload
event.
4-78 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Customer class, within the Class member fields region, add a private
member field for the first name of the customer named customerFirstName,
of type String, and initialize to Nothing.
• In the Customer class, within the Class member fields region, add a private
member field for the last name of the customer named customerLastName, of
type String, and initialize to Nothing.
• In the Customer class, within the Class member fields region, add a private
member field for the address of the customer named customerAddress, of
type String, and initialize to Nothing.
#Region "Properties"
#End Region
4-80 Introduction to Web Development with Microsoft® Visual Studio® 2010
''' <summary>
''' The unique customer ID
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ID() As Guid?
• In the Customer class, within the Properties region, add a public property
named FirstName, of type String, that sets and gets the private member
backing field named customerFirstName, and ensure that the length is no
longer than 50 characters by using the following lines of code.
''' <summary>
''' The customer first name
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property FirstName As String
Get
Return Me.customerFirstName
End Get
• In the Customer class, within the Properties region, add a public property
named LastName, of type String, that sets and gets the private member
backing field named customerLastName, and ensure that the length is no
longer than 30 characters by using the following lines of code.
''' <summary>
''' The customer last name
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property LastName As String
Get
Return Me.customerLastName
End Get
• In the Customer class, within the Properties region, add a public property
named Address, of type String, that sets and gets the private member backing
field named customerAddress, and ensure that the length is no longer than 50
characters by using the following lines of code.
''' <summary>
''' The customer address, including street name, house number and
floor
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Address As String
Get
Return Me.customerAddress
End Get
''' <summary>
''' The customer zip code or postal code
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ZipCode() As String
Get
Return Me.customerZipCode
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerZipCode = ""
Else
' Only get the first 10 characters
If (value.Length > 10) Then
Me.customerZipCode = value.Substring(0, 10)
Else
Me.customerZipCode = value
End If
End If
End Set
End Property
''' <summary>
''' The name of the city in which the customer lives
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
''' <summary>
''' The name of the state or region in which the customer lives
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property State() As String
Get
Return Me.customerState
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerState = ""
Else
' Only get the first 30 characters
If (value.Length > 30) Then
Me.customerState = value.Substring(0, 30)
Else
Me.customerState = value
End If
End If
End Set
End Property
''' <summary>
''' The ID of the country in which the customer lives
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property CountryID() As Guid?
Get
Return Me.customerCountryID
End Get
Set(ByVal value As Guid?)
Me.customerCountryID = value
End Set
End Property
''' <summary>
''' The customer phone number
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Phone() As String
Get
Return Me.customerPhone
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerPhone = ""
Else
' Only get the first 30 characters
If (value.Length > 30) Then
Me.customerPhone = value.Substring(0, 30)
Else
Me.customerPhone = value
End If
End If
End Set
End Property
''' <summary>
''' The customer e-mail address
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
''' <summary>
''' The customer web address
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property WebAddress() As String
Get
Return Me.customerWebAddress
End Get
Set(ByVal value As String)
If (value Is Nothing) Then
Me.customerWebAddress = ""
Else
' Only get the first 80 characters
If (value.Length > 80) Then
Me.customerWebAddress = value.Substring(0, 80)
Else
Me.customerWebAddress = value
End If
End If
End Set
End Property
''' <summary>
''' The current credit limit of the customer
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property CreditLimit() As Integer
Get
Return Me.customerCreditLimit
End Get
Set(ByVal value As Integer)
' Negative value?
If value < 0 Then
Me.customerCreditLimit = 0
Else
Me.customerCreditLimit = value
End If
End Set
End Property
''' <summary>
''' Does the customer subscriber to news?
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property NewsSubsriber() As Boolean
Get
Return Me.customerNewsSubscriber
End Get
Set(ByVal value As Boolean)
Me.customerNewsSubscriber = value
End Set
End Property
''' <summary>
''' The date the customer was created in the system
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
''' <summary>
''' The name of the user creating the customer
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property CreatedBy() As String
Get
Return Me.customerCreatedBy
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerCreatedBy = ""
Else
' Only get the first 15 characters
If (value.Length > 15) Then
Me.customerCreatedBy = value.Substring(0, 15)
Else
Me.customerCreatedBy = value
End If
End If
End Set
End Property
''' <summary>
''' The date the customer was last modified in the system
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
''' <summary>
''' The name of the user who last modified the customer
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ModifiedBy() As String
Get
Return Me.customerModifiedBy
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerModifiedBy = ""
Else
' Only get the first 15 characters
If (value.Length > 15) Then
Me.customerModifiedBy = value.Substring(0, 15)
Else
Me.customerModifiedBy = value
End If
End If
End Set
End Property
#Region "Constructors"
#End Region
4-90 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Customer class, within the Constructors region, add the default public
parameterless constructor that initializes the customerID and
customerCreatedDate member fields, by using the public properties.
''' <summary>
''' Default parameterless constructor
''' </summary>
''' <remarks></remarks>
Public Sub New()
' Initialize backing fields with default values
Me.ID = Guid.NewGuid()
Me.CreatedDate = DateTime.Now
End Sub
''' <summary>
''' Initializes backing fields with passed and default values
''' </summary>
''' <param name="id"></param>
''' <remarks></remarks>
Public Sub New(ByVal id As Guid?)
' Initialize backing fields with passed and default values
Me.ID = id
Me.CreatedDate = DateTime.Now
End Sub
''' <summary>
''' Initializes with a value for all backing fields
''' </summary>
''' <param name="id"></param>
''' <param name="firstName"></param>
''' <param name="lastName"></param>
''' <param name="address"></param>
''' <param name="zipCode"></param>
''' <param name="city"></param>
''' <param name="state"></param>
''' <param name="countryID"></param>
''' <param name="phone"></param>
''' <param name="emailAddress"></param>
Me.CreatedBy = createdBy
Me.ModifiedDate = modifiedDate
Me.ModifiedBy = modifiedBy
End Sub
Results: After completing this exercise, you will have created a new component by
using the Class Library project, added a reference to the component project from the
Web site, and added a member variable of type Customer.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-93
''' <summary>
''' Instantiates Customer object
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
' Instantiate Customer
instantiateCustomerObject()
End Sub
4-94 Introduction to Web Development with Microsoft® Visual Studio® 2010
''' <summary>
''' Instantiates and populates the Customer member object
''' </summary>
''' <remarks></remarks>
Private Sub instantiateCustomerObject()
' First time loading page?
If Not Me.IsPostBack Then
' Instantiate new Customer object
currentCustomer = New
CustomerManagementEntities.Customer()
Else
' Instantiate new Customer object with user input
currentCustomer = New CustomerManagementEntities.Customer(
Nothing, CustomerFirstNameTextBox.Text,
CustomerLastNameTextBox.Text,
CustomerAddressTextBox.Text,
CustomerZipCodeTextBox.Text, CustomerCityTextBox.Text,
CustomerStateTextBox.Text, Nothing,
CustomerPhoneTextBox.Text,
CustomerEmailAddressTextBox.Text,
CustomerWebAddressTextBox.Text, -1,
CustomerNewsSubscriberCheckBox.Checked, DateTime.Now,
_
"", Nothing, "")
End If
End Sub
Adding Functionality to a Microsoft® ASP.NET Web Form 4-95
''' <summary>
''' Populates UI controls
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.LoadComplete
' Populate the UI controls
populateUI()
End Sub
''' <summary>
''' Populates the UI controls with the values in the
''' current Customer object
''' </summary>
''' <remarks></remarks>
Private Sub populateUI()
CustomerFirstNameTextBox.Text = currentCustomer.FirstName
CustomerLastNameTextBox.Text = currentCustomer.LastName
CustomerAddressTextBox.Text = currentCustomer.Address
CustomerZipCodeTextBox.Text = currentCustomer.ZipCode
CustomerCityTextBox.Text = currentCustomer.City
CustomerStateTextBox.Text = currentCustomer.State
If currentCustomer.CountryID.HasValue Then
CustomerCountryDropDownList.SelectedValue =
currentCustomer.CountryID.Value.ToString()
Else
CustomerCountryDropDownList.SelectedIndex = -1
End If
CustomerPhoneTextBox.Text = currentCustomer.Phone
CustomerEmailAddressTextBox.Text =
currentCustomer.EmailAddress
CustomerWebAddressTextBox.Text = currentCustomer.WebAddress
CustomerCreditLimitTextBox.Text =
currentCustomer.CreditLimit.ToString()
CustomerNewsSubscriberCheckBox.Checked =
currentCustomer.NewsSubscriber
End Sub
4-96 Introduction to Web Development with Microsoft® Visual Studio® 2010
''' <summary>
''' Destroys objects
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Unload
' Destroy Customer object
currentCustomer = Nothing
End Sub
''' <summary>
''' Redirects to home page
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub CustomerCancelButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles CustomerCancelButton.Click
' Redirect to home page
Response.Redirect("~/Default.aspx")
End Sub
Adding Functionality to a Microsoft® ASP.NET Web Form 4-97
''' <summary>
''' Saves the current customer information and adds default values
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub customerInsertButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles customerInsertButton.Click
' Add the current user name
currentCustomer.CreatedBy = Context.User.Identity.Name
' Add the user credit limit
currentCustomer.CreditLimit = 50000
End Sub
Note: The initial code for saving the customer information is created here. However, the
final code for saving to the database will be created in Module 8.
4-98 Introduction to Web Development with Microsoft® Visual Studio® 2010
f Task 6: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have added code to handle the
Page.Load, Page.LoadComplete, and Page.Unload events for the InsertCustomer
Web Form, and added code to handle the Click event for the Insert and Cancel
button controls.
Note: The answers to the exercises are on the Course Companion CD.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-99
Section 2: Visual C#
Exercise 1: Implementing Code in a Web Application
The main tasks for this exercise are as follows:
1. Open an existing ASP.NET Web site.
Results: After completing this exercise, you will have opened the existing
CustomerManagement Web site and the InsertCustomer Web Form code-behind file.
4-100 Introduction to Web Development with Microsoft® Visual Studio® 2010
f Task 1: Create an event procedure for the Click event of the Insert
button
• Open the InsertCustomer Web Form in the Design view, and create an event
procedure for the Click event of the Insert button, by double-clicking the
Button control.
Note: Notice that the initial event procedure for the Click event of the
CustomerInsertButton control is added in the code window.
f Task 2: Create an event procedure for the Click event of the Cancel
button
• Open the InsertCustomer Web Form in the Design view, and create an event
procedure for the Click event of the Cancel button, by double-clicking the box
next to the Click event in the Properties window, with the Button control
selected in the Designer.
Note: Notice that the initial event procedure for the Click event of the
CustomerCancelButton is added to the class in the code window.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-101
Results: After completing this exercise, you will have created event procedures for
button controls Page_LoadComplete event, and Page_Unload event.
4-102 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Customer class, within the Class member fields region, add a private
member field for the first name of the customer named customerFirstName,
of type string, and initialize to null.
• In the Customer class, within the Class member fields region, add a private
member field for the last name of the customer named customerLastName, of
type string, and initialize to null.
• In the Customer class, within the Class member fields region, add a private
member field for the address of the customer named customerAddress, of
type string, and initialize to null.
#region Properties
#endregion
/// <summary>
/// The unique customer ID
/// </summary>
public Guid? ID { get; set; }
• In the Customer class, within the Properties region, add a public property
named FirstName, of type string, that sets and gets the private member
backing field named customerFirstName. Ensure that the length is no longer
than 50 characters, by using the following lines of code.
/// <summary>
/// The customer first name
/// </summary>
public string FirstName
{
get
{
return this.customerFirstName;
}
set
{
// Null value?
if (value == null)
this.customerFirstName = "";
else
// Only get the first 50 characters
if (value.Length > 50)
this.customerFirstName = value.Substring(0, 50);
else
this.customerFirstName = value;
}
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-105
• In the Customer class, within the Properties region, add a public property
named LastName, of type string, that sets and gets the private member
backing field named customerLastName. Ensure that the length is no longer
than 30 characters, by using the following lines of code.
/// <summary>
/// The customer last name
/// </summary>
public string LastName
{
get
{
return this.customerLastName;
}
set
{
// Null value?
if (value == null)
this.customerLastName = "";
else
// Only get the first 30 characters
if (value.Length > 30)
this.customerLastName = value.Substring(0, 30);
else
this.customerLastName = value;
}
}
4-106 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Customer class, within the Properties region, add a public property
named Address, of type string, that sets and gets the private member backing
field named customerAddress. Ensure that the length is no longer than 50
characters, by using the following lines of code.
/// <summary>
/// The customer address, including street name, house number and
floor
/// </summary>
public string Address
{
get
{
return this.customerAddress;
}
set
{
// Null value?
if (value == null)
this.customerAddress = "";
else
// Only get the first 50 characters
if (value.Length > 50)
this.customerAddress = value.Substring(0, 50);
else
this.customerAddress = value;
}
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-107
/// <summary>
/// The customer zip code or postal code
/// </summary>
public string ZipCode
{
get
{
return this.customerZipCode;
}
set
{
// Null value?
if (value == null)
this.customerZipCode = "";
else
// Only get the first 10 characters
if (value.Length > 10)
this.customerZipCode = value.Substring(0, 10);
else
this.customerZipCode = value;
}
}
/// <summary>
/// The name of the city in which the customer lives
/// </summary>
public string City
{
get
{
return this.customerCity;
}
set
{
// Null value?
if (value == null)
this.customerCity = "";
else
/// <summary>
/// The name of the state or region in which the customer lives
/// </summary>
public string State
{
get
{
return this.customerState;
}
set
{
// Null value?
if (value == null)
this.customerState = "";
else
// Only get the first 30 characters
if (value.Length > 30)
this.customerState = value.Substring(0, 30);
else
this.customerState = value;
}
}
/// <summary>
/// The ID of the country in which the customer lives
/// </summary>
public Guid? CountryID
{
get
{
return this.customerCountryID;
}
set
{
this.customerCountryID = value;
}
}
/// <summary>
/// The customer phone number
/// </summary>
public string Phone
{
get
{
return this.customerPhone;
}
set
{
// Null value?
if (value == null)
this.customerPhone = "";
else
// Only get the first 30 characters
if (value.Length > 30)
this.customerPhone = value.Substring(0, 30);
else
this.customerPhone = value;
}
}
/// <summary>
/// The customer e-mail address
/// </summary>
public string EmailAddress
{
get
{
return this.customerEmailAddress;
}
set
{
// Null value?
if (value == null)
this.customerEmailAddress = "";
else
// Only get the first 50 characters
if (value.Length > 50)
this.customerEmailAddress = value.Substring(0,
50);
else
this.customerEmailAddress = value;
}
}
/// <summary>
/// The customer Web address
/// </summary>
public string WebAddress
{
get
{
return this.customerWebAddress;
}
set
{
// Null value?
if (value == null)
this.customerWebAddress = "";
else
// Only get the first 80 characters
if (value.Length > 80)
this.customerWebAddress = value.Substring(0, 80);
else
this.customerWebAddress = value;
}
}
/// <summary>
/// The current credit limit of the customer
/// </summary>
public int CreditLimit
{
get
{
return this.customerCreditLimit;
}
set
{
// Negative value?
if (value < 0)
this.customerCreditLimit = 0;
else
this.customerCreditLimit = value;
}
}
/// <summary>
/// Does the customer subscriber to news?
/// </summary>
public bool NewsSubscriber
{
get
{
return this.customerNewsSubscriber;
}
set
{
this.customerNewsSubscriber = value;
}
}
/// <summary>
/// The date the customer was created in the system
/// </summary>
public DateTime? CreatedDate
{
get
{
return this.customerCreatedDate;
}
private set
{
// Date in the past?
if (value < DateTime.Now)
this.customerCreatedDate = DateTime.Now;
else
this.customerCreatedDate = value;
}
}
/// <summary>
/// The name of the user creating the customer
/// </summary>
public string CreatedBy
{
get
{
return this.customerCreatedBy;
}
set
{
// Null value?
if (value == null)
this.customerCreatedBy = "";
else
// Only get the first 15 characters
if (value.Length > 15)
this.customerCreatedBy = value.Substring(0, 15);
else
this.customerCreatedBy = value;
}
}
/// <summary>
/// The date the customer was last modified in the system
/// </summary>
public DateTime? ModifiedDate
{
get
{
return this.customerModifiedDate;
}
set
{
// Date in the past?
if (value < DateTime.Now)
this.customerModifiedDate = DateTime.Now;
else
this.customerModifiedDate = value;
}
}
/// <summary>
/// The name of the user who last modified the customer
/// </summary>
public string ModifiedBy
{
get
{
return this.customerModifiedBy;
}
set
{
// Null value?
if (value == null)
this.customerModifiedBy = "";
else
// Only get the first 15 characters
if (value.Length > 15)
this.customerModifiedBy = value.Substring(0, 15);
else
this.customerModifiedBy = value;
}
}
#region Constructors
#endregion
• In the Customer class, within the Constructors region, add the default public
parameterless constructor that initializes the customerID and
customerCreatedDate member fields by using the public properties.
/// <summary>
/// Default parameterless constructor
/// </summary>
public Customer()
{
// Initialize backing fields with default values
this.ID = Guid.NewGuid();
this.CreatedDate = DateTime.Now;
}
4-114 Introduction to Web Development with Microsoft® Visual Studio® 2010
/// <summary>
/// Initializes backing fields with passed and default values
/// </summary>
/// <param name="id"></param>
public Customer(Guid? id)
{
// Initialize backing fields with passed and default values
this.ID = id;
this.CreatedDate = DateTime.Now;
}
/// <summary>
/// Initializes with a value for all backing fields
/// </summary>
/// <param name="id"></param>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="address"></param>
/// <param name="zipCode"></param>
/// <param name="city"></param>
/// <param name="state"></param>
/// <param name="countryID"></param>
/// <param name="phone"></param>
/// <param name="emailAddress"></param>
/// <param name="webAddress"></param>
/// <param name="creditLimit"></param>
/// <param name="newsSubscriber"></param>
/// <param name="createdDate"></param>
/// <param name="createdBy"></param>
/// <param name="modifiedDate"></param>
/// <param name="modifiedBy"></param>
public Customer(Guid? id, string firstName, string lastName,
string address,
string zipCode, string city, string state, Guid? countryID,
string phone,
string emailAddress, string webAddress, int creditLimit, bool
newsSubscriber,
DateTime? createdDate, string createdBy, DateTime?
modifiedDate, string modifiedBy)
{
// Initialize member backing fields with passed values
this.ID = id;
this.FirstName = firstName;
this.LastName = lastName;
this.Address = address;
this.ZipCode = zipCode;
this.City = city;
this.State = state;
this.CountryID = countryID;
this.Phone = phone;
this.EmailAddress = emailAddress;
this.WebAddress = webAddress;
this.CreditLimit = creditLimit;
this.NewsSubscriber = newsSubscriber;
if (createdDate != null)
this.CreatedDate = createdDate;
else
this.CreatedDate = DateTime.Now;
this.CreatedBy = createdBy;
this.ModifiedDate = modifiedDate;
this.ModifiedBy = modifiedBy;
}
Results: After completing this exercise, you will have created a new component by
using the Class Library project, added a reference to the component project from the
Web site, and added a member variable of type Customer.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-117
/// <summary>
/// Instantiates Customer object
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
// Instantiate Customer
instantiateCustomerObject();
}
4-118 Introduction to Web Development with Microsoft® Visual Studio® 2010
/// <summary>
/// Instantiates and populates the Customer member object
/// </summary>
private void instantiateCustomerObject()
{
// First time loading page?
if (!this.IsPostBack)
// Instantiate new Customer object
currentCustomer = new CustomerManagementEntities.Customer(
null, CustomerFirstNameTextBox.Text,
CustomerLastNameTextBox.Text,
CustomerAddressTextBox.Text,
CustomerZipCodeTextBox.Text,
CustomerCityTextBox.Text, CustomerStateTextBox.Text,
null, CustomerPhoneTextBox.Text,
CustomerEmailAddressTextBox.Text,
CustomerWebAddressTextBox.Text, -1,
CustomerNewsSubscriberCheckBox.Checked,
DateTime.Now, "", null, "");
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-119
/// <summary>
/// Populates UI controls
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Populate the UI controls
populateUI();
}
/// <summary>
/// Populates the UI controls with the values in the
/// current Customer object
/// </summary>
private void populateUI()
{
CustomerFirstNameTextBox.Text = currentCustomer.FirstName;
CustomerLastNameTextBox.Text = currentCustomer.LastName;
CustomerAddressTextBox.Text = currentCustomer.Address;
CustomerZipCodeTextBox.Text = currentCustomer.ZipCode;
CustomerCityTextBox.Text = currentCustomer.City;
CustomerStateTextBox.Text = currentCustomer.State;
if (currentCustomer.CountryID.HasValue)
CustomerCountryDropDownList.SelectedValue =
currentCustomer.CountryID.Value.ToString();
else
CustomerCountryDropDownList.SelectedIndex = -1;
CustomerPhoneTextBox.Text = currentCustomer.Phone;
CustomerEmailAddressTextBox.Text =
currentCustomer.EmailAddress;
CustomerWebAddressTextBox.Text = currentCustomer.WebAddress;
CustomerCreditLimitTextBox.Text =
currentCustomer.CreditLimit.ToString();
CustomerNewsSubscriberCheckBox.Checked =
currentCustomer.NewsSubscriber;
}
4-120 Introduction to Web Development with Microsoft® Visual Studio® 2010
/// <summary>
/// Destroys objects
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Unload(object sender, EventArgs e)
{
// Destroy Customer object
currentCustomer = null;
}
/// <summary>
/// Redirects to home page
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CustomerCancelButton_Click(object sender, EventArgs
e)
{
// Redirect to home page
Response.Redirect("~/Default.aspx");
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-121
/// <summary>
/// Saves the current customer information and adds default values
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CustomerInsertButton_Click(object sender, EventArgs
e)
{
// Add the current user name
currentCustomer.CreatedBy = Context.User.Identity.Name;
// Add the user credit limit
currentCustomer.CreditLimit = 50000;
}
Note: The initial code for saving the customer information is created here. However, the
final code for saving to the database is created in Module 8.
4-122 Introduction to Web Development with Microsoft® Visual Studio® 2010
f Task 6: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have added code to handle the
Page.Load, Page.LoadComplete, and Page.Unload events for the InsertCustomer
Web Form, and added code to handle the Click event for the Insert and Cancel
button controls.
Note: The answers to the exercises are on the Course Companion CD.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-123
Lab Review
Module Review
Best Practices
• Follow a naming and casing convention when naming your variables. In this
course, a naming convention consisting of what the variable contains, and is
suffixed by the data type when appropriate, is used. If a variable contains one
of the simple data types—such as Integer or String—it is most often not
necessary to suffix with the data type. Examples are FirstName, LastName,
Name, Age, and Length.
• If you are naming a variable of a specific object type, always use the object type
name as the suffix, such as CustomerManagementDataSet, where the data
type is DataSet, and the name is CustomerManagement. The casing differs
between Pascal Casing and Camel Casing, where the former capitalizes the first
character of each word—including acronyms over two letters in length, such as
“FirstName”. The latter is close to Pascal Casing, but always uses an initial
lower-case letter, such as “firstName”. Pascal Casing is generally used for
public variables, whereas Camel Casing is used for local and private variables,
as well as method parameters. See the next best practice regarding public
variables.
• Member variables—also known as backing fields—as a general rule should
never be made public, because that can corrupt the state of an object. Instead,
make a member variable private, and expose the value through a property with
which you can check when a user of the object sets the value of the property.
There are exceptions to this rule, such as some instances of when an object
needs to be serialized, but that is beyond the scope of this module.
4-126 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Follow a naming and casing convention when naming your methods. In this
course, the naming convention used describes the data it makes available—
such as FirstName—but never with the first word of the name being a verb—
such as used for method names (GetFirstName). Casing uses the same rules as
for variables—public methods use Pascal Casing, whereas non-public methods
use Camel Casing.
• Follow a naming and casing convention when naming your properties. In this
course, a naming convention consisting of what the method does, but always
with the first word of the name being a verb, such a GetUserID or SaveID.
Casing uses the same rules as for variables and methods—public properties use
Pascal Casing, whereas non-public properties use Camel Casing.
Module 5: Implementing Master Pages and User Controls 5-1
Module 5
Implementing Master Pages and User Controls
Contents:
Lesson 1: Creating Master Pages 5-3
Lesson 2: Adding User Controls to an ASP.NET Web Form 5-26
Lab: Implementing Master Pages and User Controls 5-48
5-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
When you design your Web application, you need to add one or more Microsoft®
ASP.NET Web Forms to your project. Quite often, you have to apply a consistent
design to the user interface (UI). You can use master pages to apply a consistent
design to your Web site without having to duplicate the design on multiple Web
Forms.
While master pages help you provide a consistent look to your Web application,
user controls help you reuse UI components in a custom manner. You may use the
same combination of controls on different pages—for example, controls to view
and edit order information. User controls provide an easy way to reuse common
UI components and code across a Web application. You can add existing Web
server controls and markup to a user control, and define properties and methods
for the control. You can then embed them in ASP.NET Web pages, where they can
function as a unit.
In this module, you will learn how to create and implement master pages, and how
to implement user controls in a Web application.
Module 5: Implementing Master Pages and User Controls 5-3
Lesson 1
Creating Master Pages
Master pages help you define the overall layout of a Microsoft ASP.NET application
from a single location—the .master file. You then reuse the layout in all the content
pages that are derived from that master page. Master pages provide several
benefits. You can make design changes on a master page that will immediately be
reflected on all of the pages that use that master page. You can edit the master page
elements of a Web application from one location, without having to customize all
the pages that use the common elements. You can easily create a Web application
with a consistent look and feel, and provide a good user experience.
In this lesson, you will learn how to create a master page, and then create a Web
Form that uses the master page.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe master pages.
• Create a master page.
5-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
ASP.NET master pages allow you to create a consistent layout for the pages in your
application. A single master page defines the look and feel, and standard behavior
that you want for all the pages or a group of pages in your application. You can
then create individual content pages that contain the content that you want to
display. Therefore, you can use a master page to create a predefined layout, which
can include static text, HTML elements, and server controls.
The master page is an ASP.NET file with the extension .master, and it is identified
by a special Master directive that replaces the Page directive that is used for
ordinary Web Form pages.
You can place common Web site content on a master page—for example, the
header that you want to display on multiple pages of a Web site.
5-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
By using master pages, you can create the functionality that was previously
provided by using framesets, and you can include files and user controls. Master
pages can contain the same types of controls and code as standard ASP.NET Web
Forms. If you want the different sections of your Web application to have different
layouts, you can include several master pages in your project. For example, you
may have one section of your Web application for authenticated users, and another
section for anonymous users.
[Visual Basic]
<%@ Master Language="VB" AutoEventWireup="false"
CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
[Visual C#]
<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
Note: By default, a Web server such as Internet Information Services (IIS) 7.0 prevents
files with the .master file extension from being viewed in a Web browser. This security
measure ensures that you do not view the master page as a stand-alone ASP.NET page.
A master page is almost like a standard Web Form, because it can contain standard
content, including the top-level HTML elements for a page such as html, head,
body, and form. For example, on a master page, you might use an HTML table for
the layout or a combination of div elements to display the elements on the page; an
img element for the company logo; static text for the copyright notice; and server
controls for site navigation. However, what differentiates a master page from a
standard Web Form is the inclusion of one or more ContentPlaceHolder controls.
ContentPlaceHolder controls define the areas where replaceable content can
appear. In turn, the replaceable content is defined in content pages. You must
place the ContentPlaceHolder controls within the head element, or within the
form element, as follows.
Module 5: Implementing Master Pages and User Controls 5-7
<html>
<head runat="server">
<title>General Application Title</title>
<asp:ContentPlaceHolder id="HeadContentPlaceHolder"
runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
...
<! Standard content >
<div class="top">
<asp:ContentPlaceHolder id="MainContentPlaceHolder"
runat="server" />
...
<! Standard content >
</div>
<div class="bottom">
<asp:ContentPlaceHolder id="FooterContentPlaceHolder"
runat="server">
<asp:Label id="FooterLabel" runat="server"
Text="Footer Text" />
</asp:ContentPlaceHolder id="FooterContentPlaceHolder">
</div>
...
</form>
</body>
If a content page that is linked with the master page does not include a Content
control that references the ContentPlaceHolder control, then the default content
from the ContentPlaceHolder control on the master page is shown on the
rendered page, which is as follows.
<div class="bottom">
<asp:ContentPlaceHolder id="FooterContentPlaceHolder"
runat="server">
<asp:Label id="FooterLabel" runat="server" Text="Footer Text"
/>
</asp:ContentPlaceHolder>
</div>
Question: Which features differentiate a master page from a standard Web Form?
5-8 Introduction to Web Development with Microsoft® Visual Studio® 2010
After setting the layout of the table, you can add content to the master page that
will appear on all pages. You can add a copyright message as a footer, and then add
a menu. If you have a logo graphic available, you can add that also.
Content Pages
Content pages provide content for a master page. A content page is an ASP.NET
Web Form that references a specific master page. When you have one or more
master pages in your project, you can add new content pages, or convert your
existing Web Forms to content pages. By using content pages, you can create
additional content that merges at run time with the generic content from the
master page.
[Visual Basic]
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master"
AutoEventWireup="false" CodeFile="ContentPage.aspx.vb"
Inherits="ContentPage" %>
Module 5: Implementing Master Pages and User Controls 5-11
[Visual C#]
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="ContentPage.aspx.cs"
Inherits="ContentPage" %>
By specifying the master page in the Page directive, you can use more than one
master page in your project. You can specify different master pages for different
Web Forms. You can also specify a master page at the application level in the
web.config file, as follows.
You can specify that all ASP.NET pages (.aspx files) in the application should
automatically bind to the specified master page, if the page contains one or more
Content controls. When you specify a reference to a master page at the page level,
if you reference a non-existing ContentPlaceHolder control, you will receive a
compile-time error. If you specify a reference to a master page in the web.config
file, and if you reference a non-existent file, you will receive a runtime error.
The MasterPageFile attribute of the Page directive overrides any master page
setting specified in the web.config file.
Content pages must contain at least one Content control that references a
ContentPlaceHolder control on the referenced master page, as indicated in the
following examples.
[Visual Basic]
<asp:Content ID="MainContent"
ContentPlaceHolderID="MainContentPlaceHolder" Runat="Server">
</asp:Content>
<asp:Content ID="FooterContent"
ContentPlaceHolderID="FooterContentPlaceHolder" Runat="Server">
</asp:Content>
[Visual C#]
<asp:Content ID="MainContent"
ContentPlaceHolderID="MainContentPlaceHolder" Runat="Server">
</asp:Content>
<asp:Content ID="FooterContent"
ContentPlaceHolderID="FooterContentPlaceHolder" Runat="Server">
</asp:Content>
5-12 Introduction to Web Development with Microsoft® Visual Studio® 2010
After creating Content controls, you can add text and controls to them. The
Content controls on the content page link directly to the ContentPlaceHolder
controls on the master page. You cannot add a Content control that does not
reference an existing ContentPlaceHolder control in the referenced master page.
On a content page, anything that is not inside the Content controls—except script
blocks for server code—results in a compile-time error.
You can perform any tasks on a content page that you would do on an ASP.NET
page. For example, you can generate content for a Content control by using server
controls, or run database queries.
Module 5: Implementing Master Pages and User Controls 5-13
[Visual Basic]
<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master"
AutoEventWireup="false" CodeFile="ContentPage.aspx.vb"
Inherits="ContentPage" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="MainContentPlaceHolder" Runat="Server">
</asp:Content>
[Visual C#]
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="ContentPage.aspx.cs"
Inherits="ContentPage" %>
<asp:Content ID="Content1"
ContentPlaceHolderID="MainContentPlaceHolder" Runat="Server">
</asp:Content>
Merging Content
You can reference a master page and one or more of the ContentPlaceHolder
controls on a content page, by using Content controls. If a ContentPlaceHolder
control is referenced on the content page, the content—if any—that is located in the
Content control referencing the ContentPlaceHolder control, is rendered. If a
ContentPlaceHolder control is not referenced on the content page, the default
content—if any—that is specified on the master page is rendered. The title attribute
of the Page directive on a content page is also merged with the master page, if the
head element on the master page has the runat attribute set to server. Otherwise,
the setting on the content page is ignored, because the head element is not
available for processing at the server-side, at the time of merging.
Question: When you design a Web application by using master pages, what are
some of the external resources that you might need to reference and add?
Module 5: Implementing Master Pages and User Controls 5-15
Key Points
Master pages can be nested, with one master page referencing another as its
master.
The following examples show the Master directive for a parent master page.
[Visual Basic]
<%@ Master Language="VB" AutoEventWireup="false"
CodeFile="ParentMasterPage.master.vb" Inherits="ParentMasterPage" %>
[Visual C#]
<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="ParentMasterPage.master.cs" Inherits="ParentMasterPage" %>
The following examples show the Master directive for a child master page.
[Visual Basic]
<%@ Master Language="VB" AutoEventWireup="false"
MasterPageFile="~/ParentMasterPage.master"
CodeFile="ChildMasterPage.master.vb" Inherits="ChildMasterPage" %>
[Visual C#]
<%@ Master Language="C#" AutoEventWireup="true"
MasterPageFile="~/ParentMasterPage.master"
CodeFile="ChildMasterPage.master.cs" Inherits="ChildMasterPage" %>
A child master page has the file name extension .master, similar to any master
page. The child master page contains content controls that link to content
placeholders on the parent master page. In addition, the child master page has its
own content placeholders. These placeholders display the content that is supplied
by the content pages of the child master pages.
When designing a portal or a Web site with many different areas or sections, best
practice is to have an overall master page that only defines the overall layout, and
then have two or more nested or child master pages that define the layout for
specific areas or sections.
[Visual Basic]
<% @ Master Language="VB" AutoEventWireup="false"
CodeFile="ParentMasterPage.master.vb" Inherits="ParentMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<body>
<head runat="server">
<title>Untitled Page</title>
</head>
<form id="Form1" runat="server">
<div>
<h1>Parent Master</h1>
<p style="font:color=red">This is parent master content.</p>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</form>
</body>
</html>
[Visual C#]
<% @ Master Language="C#" AutoEventWireup="true"
CodeFile="ParentMasterPage.master.cs" Inherits="ParentMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="Form1" runat="server">
<div>
<h1>Parent Master</h1>
<p style="font:color=red">This is parent master content.</p>
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</form>
</body>
</html>
5-18 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual Basic]
<%@ Master Language="VB" MasterPageFile="~/ParentMasterPage.master"%>
<asp:Content id="Content1" ContentPlaceholderID="MainContent"
runat="server">
<asp:Panel runat="server" id="PanelMain" backcolor="lightyellow">
<h2>Child master</h2>
<asp:Panel runat="server" id="Panel1" backcolor="lightblue">
<p>This is childmaster content.</p>
<asp:ContentPlaceHolder ID="ChildContent1" runat="server"
/>
</asp:Panel>
<asp:Panel runat="server" id="Panel2" backcolor="pink">
<p>This is childmaster content.</p>
<asp:ContentPlaceHolder ID="ChildContent2" runat="server"
/>
</asp:Panel>
<br />
</asp:Panel>
</asp:Content>
[Visual C#]
<%@ Master Language="C#" MasterPageFile="~/ParentMasterPage.master"%>
<asp:Content id="Content1" ContentPlaceholderID="MainContent"
runat="server">
<asp:Panel runat="server" id="PanelMain" backcolor="lightyellow">
<h2>Child master</h2>
<asp:Panel runat="server" id="Panel1" backcolor="lightblue">
<p>This is child master content.</p>
<asp:ContentPlaceHolder ID="ChildContent1" runat="server"
/>
</asp:Panel>
<asp:Panel runat="server" id="Panel2" backcolor="pink">
<p>This is child master content.</p>
<asp:ContentPlaceHolder ID="ChildContent2" runat="server"
/>
</asp:Panel>
<br />
</asp:Panel>
</asp:Content>
Module 5: Implementing Master Pages and User Controls 5-19
The following two examples are of a content page that references the child master
page.
[Visual Basic]
<%@ Page Language="VB" MasterPageFile="~/Child.master"%>
<asp:Content id="Content1" ContentPlaceholderID="ChildContent1"
runat="server">
<asp:Label runat="server" id="Label1" text="Child label1" font-
bold="true" />
<br>
</asp:Content>
<asp:Content id="Content2" ContentPlaceholderID="ChildContent2"
runat="server">
<asp:Label runat="server" id="Label2" text="Child label2" font-
bold="true"/>
</asp:Content>
[Visual C#]
<%@ Page Language="C#" MasterPageFile="~/Child.master"%>
<asp:Content id="Content1" ContentPlaceholderID="ChildContent1"
runat="server">
<asp:Label runat="server" id="Label1" text="Child label1" font-
bold="true" />
<br>
</asp:Content>
<asp:Content id="Content2" ContentPlaceholderID="ChildContent2"
runat="server">
<asp:Label runat="server" id="Label2" text="Child label2" font-
bold="true"/>
</asp:Content>
Key Points
When you work with master pages and content pages, both master pages and
content pages can use the same set of events, such as the Init or Load events. You
must know the event order to use master pages effectively. When a user requests a
Web page (.aspx), ASP.NET checks the Page directive and fetches the master page,
if one is referenced. The process is as follows:
1. The user requests a page by typing the URL of the content page. However, the
user request is not directed to the master page, as the Web server disallows
access to .master files, by default.
2. ASP.NET reads the Page directive of the content page and the pages element
of the web.config file. If the Page directive or the pages element contains a
MasterPageFile attribute, ASP.NET retrieves the master page. When the two
pages are requested for the first time, the content page and master page are
compiled.
3. ASP.NET merges the master page content into the control tree of the content
page.
Module 5: Implementing Master Pages and User Controls 5-21
From the user's perspective, the master and content pages are combined into a
single, discrete page. The URL of the page is that of the content page. From a
programming perspective, the two pages act as separate containers for their
respective controls. The content page acts as a container for the master page, but
you can reference the public members of the master page from the code on the
content page. For example, you can save a specific object to Session state and make
it available to all content pages by using a public property. This way you avoid the
need to duplicate the code for saving the object on the content pages.
Note: Session state will be covered in Module 13, “Managing State in Web Applications.”
You may need to access some controls programmatically from the content page—
for example, a Menu control, a SiteMapPath control, or a Login control. This
could be a checked menu item that you want to select or clear, depending on the
user input on the content page, or an expression.
Similar to a user control, the master page functions as a child element of the
content page, and also as a container within the content page. There is one
difference though, in that the master page is the container for all server controls
rendered to the browser.
Note: User controls are covered in the next lesson, “Adding User Controls to an ASP.NET
Web Form.”
Question: How is the master page merged with the content page at run time?
5-22 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
Even if you did not use master pages when you originally developed your Web
application, you can still add one or more master pages to your Web application at
a later stage. To add and use a master page in an existing Web application project,
you need add at least one content page, or convert an existing Web Form in the
Web application project to a content page.
Because Web Forms are similar to the combination of a master page and a content
page, it is easy to convert a Web Form into a content page. After adding a master
page, you can add new pages as content pages.
Module 5: Implementing Master Pages and User Controls 5-23
You can use the following tasks to convert a Web Form to a content page:
• Create a master page, or add an existing master page.
• Remove all of the top-level HTML elements from the Web Form, including
html, head, body, and form. If you have a title element in the head element,
determine if that title should be moved to the master page; if so, ensure that
the head element on the master page contains the runat attribute set to server.
• Add the MasterPageFile attribute to the Page directive, and reference the
required master page. Your Web Form is now considered a content page.
• Add the required number of Content controls to the content page by
referencing the ContentPlaceHolder controls on the referenced master page.
• Move the existing controls to the Content controls.
• Consider moving any existing styles—whether inline or stored in a cascading
style sheet (CSS) file—to the master page, or to the CSS file used by the master
page.
• Lay out the server controls in the Content controls. While you cannot place
the server controls outside the Content controls, you will still have full control
over how they are laid out within the Content controls.
5-24 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
There are several advantages of using master pages. By using master pages,
you can:
• Improve the maintenance of Web sites, because you can apply updates in one
location that affect all of the content pages on that Web site.
• Define a portion of a page separately, and then reuse it on multiple pages.
• Obtain fine-grained control over the layout of a Web page, because you can
control how the content is rendered.
• Define a locked-down layout with editable placeholders. The content pages are
constrained to add or modify content in the allowed placeholders.
• Implement an object model that helps you access elements of the master page
from content pages that reference the master page.
• Share the master pages across Web application projects.
Module 5: Implementing Master Pages and User Controls 5-25
Lesson 2
Adding User Controls to an ASP.NET Web Form
A user control is an ASP.NET page that other Web Forms can import as a server
control. Similar to Web server controls—which are components that run on the
server—user controls provide UI and other related functionality. After you create a
user control, other Web pages in the same Web application can use that control.
In this lesson, you will learn about user controls, and why they are a useful
addition to your Web applications. You will also learn how to reference a user
control from an ASP.NET Web Form, and how to access the properties in a user
control.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe user controls.
• Describe the advantages and disadvantages of using user controls.
Module 5: Implementing Master Pages and User Controls 5-27
Key Points
User controls can simplify the reuse of code and common UI components. To
develop effective ASP.NET Web applications with reusability, you must know how
to utilize user controls.
User Controls
User controls are ASP.NET pages with an .ascx file extension. You can create a user
control by extending the functionality of an existing server control—for example, a
calendar control that stores the date in a text box. User controls can also consist of
several elements that work and interact together to get a task done. For example,
you can group several controls together to gather information about a user's
previous work experience.
Module 5: Implementing Master Pages and User Controls 5-29
User controls offer you the option to partition and reuse common UI functionality
across ASP.NET Web applications. Similar to a Web Form, you can author these
controls by using Visual Studio 2010, and add logic to them by using code-behind
classes. Similar to a Web Form page, user controls are compiled when first
requested, and then stored in server memory to reduce the response time for
subsequent requests. Unlike Web Form pages, user controls cannot be requested
independently, and user controls must be included in a Web Form page to work.
Note: By default, a Web server such as IIS 7.0 prevents files with the .ascx file extension
from being viewed in a Web browser. This security measure ensures that you do not view
the user control as a stand-alone ASP.NET page.
[Visual Basic]
[Visual C#]
Note: The Control directive supports many of the same attributes as the Page directive.
However, the Control directive does not support the Trace attribute. Therefore, if you
want to enable tracing for the user control, you must add the Trace attribute to the
Page directive for the .aspx page that calls the user control. For more information about
tracing, see Module 7, “Troubleshooting Microsoft ASP.NET Web Applications.”
Web server control Web server controls include form-type controls such
as button and text box, and specific controls, such as
calendar. You can also create custom, compiled Web
server controls, which are a special type of component
that provides a user interface.
User control Unlike Web server controls, a user control must have a
user interface at both design time and run time, and
you can write code to implement the functionality of
the user control.
Module 5: Implementing Master Pages and User Controls 5-31
Key Points
There are several advantages to having user controls in your ASP.NET Web
applications. User controls are self-contained, can be used multiple times, and can
be written in a programming language that is different from the language that is
used for the main hosting page.
User controls are typically used for creating small units of layout and code that are
used repeatedly within a Web application. This includes logon, validation,
navigation, toolbars, and similar functionality.
• User controls can be used multiple times. User controls can be used more than
once on a hosting page, without causing property and method conflicts.
• User controls can be written in a language that is different from the language
that is used for the main hosting page. For example, a user control that is
written in Microsoft Visual C#® can be used on a Web Form that is written in
Microsoft Visual Basic®.
• User controls can be shared in a Web application. You can share a single user
control among all the pages in a Web application.
Key Points
If you do not include user controls during the initial development of your Web
application project, you can still add one or more user controls at a later stage. In
fact, sometimes, it is better to create user controls after development has started,
because you can then identify the bits and pieces in your Web Forms that are
duplicated. Because Web Forms are similar to user controls, you can easily convert
a Web Form to a user control.
Note: For more information about the attributes that are supported by the Page and
Control directives, see "Directive Syntax" in the Visual Studio 2010 documentation.
Note: If the Web Form contains a code-behind file, you must also change the file
extension of this page to .ascx.cs or .ascx.vb. In addition, change the type from which the
class inherits, from System.Web.UI.Page to System.Web.UI.UserControl.
• Add properties to the user control to allow controlled access to the private
data—if any—that is contained in the user control. These properties work the
same way as they do for a Web Form.
In this demonstration, you will see how to convert a Web Form into a user control.
Demonstration Steps
1. Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
2. Open the CustomerManagement solution from either the
D:\Demofiles\M5\VB or D:\Demofiles\M5\CS folder.
a. On the Start menu of 10267A-GEN-DEV, point to All Programs,
click Microsoft Visual Studio 2010, and then click Microsoft Visual
Studio 2010.
b. On the File menu of Visual Studio 2010, click Open Project.
c. In the Open Project dialog box, in the File name box, type either
D:\Demofiles\M5\VB\CustomerManagement.sln or
D:\Demofiles\M5\CS\CustomerManagement.sln, and then click Open.
5-36 Introduction to Web Development with Microsoft® Visual Studio® 2010
3. Open the InsertCustomer.aspx Web Form, and change its Page directive to a
Control directive.
[Visual Basic]
<%@ Control Language="VB" AutoEventWireup="false"
CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer" %>
[Visual C#]
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer" %>
[Visual Basic]
<%@ Control Language="VB" AutoEventWireup="false"
CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer" %>
[Visual C#]
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer" %>
[Visual Basic]
<%@ Control Language="VB" AutoEventWireup="false"
CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer"
ClassName="InsertCustomer" %>
[Visual C#]
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer"
ClassName="InsertCustomer" %>
Module 5: Implementing Master Pages and User Controls 5-37
ClassName="InsertCustomer"
Note: You should take care not to delete the div element and the content within the
form element. Both the opening and closing tags for each element—if they exist—must
be removed.
Note: After removing all the top-level elements, you will get the following code.
[Visual Basic]
<%@ Control Language="VB" AutoEventWireup="false"
CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer"
ClassName="InsertCustomer" %>
<div class="customertable">
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerNameLabel" runat="server"
Text="Name:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerNameTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerAddressLabel"
runat="server" Text="Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerPhoneLabel" runat="server"
Text="Phone:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerPhoneTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerZipCodeLabel"
runat="server" Text="Zip Code:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerZipCodeTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerCityTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerStateTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerEmailAddressLabel"
[Visual C#]
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer"
ClassName="InsertCustomer" %>
<div class="customertable">
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerNameLabel" runat="server"
Text="Name:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerNameTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerAddressLabel"
runat="server" Text="Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerPhoneLabel"
runat="server" Text="Phone:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerPhoneTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerZipCodeLabel"
runat="server" Text="Zip Code:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerZipCodeTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerCityTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerStateTextBox"
runat="server" MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerEmailAddressLabel"
runat="server" Text="Email Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerEmailAddressTextBox"
runat="server" MaxLength="40"></asp:TextBox>
</div>
</div>
<div class="customertablefooter">
</div>
<asp:Button ID="CustomerInsertButton" runat="server"
Text="Insert"
onclick="CustomerInsertButton_Click" />
<asp:Button ID="customerCancelButton" runat="server"
Text="Cancel"
onclick="CustomerCancelButton_Click" />
</div>
[Visual Basic]
Partial Class InsertCustomer
Inherits System.Web.UI.UserControl
[Visual C#]
public partial class InsertCustomer : System.Web.UI.UserControl
[Visual Basic]
Partial Class InsertCustomer
Inherits System.Web.UI.UserControl
[Visual C#]
public partial class InsertCustomer :
System.Web.UI.UserControl
9. Move the content from the Page_LoadComplete event method, and append it
to the Page_Load event method.
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
' Instantiate Customer
instantiateCustomerObject()
' Populate the UI controls
populateUI()
End Sub
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
// Instantiate Customer
instantiateCustomerObject();
// Populate the UI controls
populateUI();
}
Module 5: Implementing Master Pages and User Controls 5-43
[Visual Basic]
' Populate the UI controls
populateUI()
[Visual C#]
// Populate the UI controls
populateUI();
[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
' Instantiate Customer
instantiateCustomerObject()
' Populate the UI controls
populateUI()
End Sub
[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
// Instantiate Customer
instantiateCustomerObject();
// Populate the UI controls
populateUI();
}
Key Points
You can place a user control in any ASP.NET Web Form. The page that references
the user control is called a host, and the control is included in that host.
The TagPrefix attribute determines a unique namespace for the user control, and
differentiates between multiple user controls that have the same name. The
TagName attribute is the unique name for the user control. The Src attribute is the
virtual path to the user control file.
5-46 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: You can drag a user control from Solution Explorer onto a Web Form. When you
drag a user control onto a Web Form in Design View, Visual Studio 2010 automatically
adds the Register directive and the tag for the user control to the page markup.
When a user requests the Web Form on which the user control has been placed,
the runtime compiles the user control file and makes it available to the page.
[Visual Basic]
WebUserControl1.Name = "Gregory Weber"
[Visual C#]
WebUserControl1.Name = "Gregory Weber";
If the public property is read-write, you can also write the values in your Web
Form, just as you write any other property.
[Visual Basic]
<%@ Page Language="VB" %>
<%@ Register TagPrefix="uc" TagName="Spinner"
Src="~\Controls\Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1" runat="server" MinValue="1"
MaxValue="10" />
</form>
</body>
[Visual C#]
<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" TagName="Spinner"
Src="~\Controls\Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1" runat="server" MinValue="1"
MaxValue="10" />
</form>
</body>
Question: What is the difference between the TagPrefix, TagName, and Src
attributes?
5-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: You can perform tasks in this lab either by using the Visual Basic or Visual C#
programming language. If you are using Visual Basic as your programming language,
refer to the steps provided in Section 1 of the lab document. If you are using Visual C#
as your programming language, refer to the steps provided in Section 2 of the lab
document.
Introduction
In this lab, you will implement master pages and user controls in an ASP.NET Web
project. In addition, you will add navigation to the master page and convert a Web
Form to a user control.
Module 5: Implementing Master Pages and User Controls 5-49
Objectives
After completing this lab, you will be able to:
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
5-50 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses a Web site to manage its customer
information. The organization has decided to modify their Web site to provide
consistent user experience to all customers.
To do this, you need to add a master page and convert an existing Web Form into
a user control for reuse. In addition, you will need to add navigation to the master
page. A senior developer has already created some of the code to add navigation to
the Web site, and the developer has created a sitemap XML document. You can use
the code and the document for adding navigation to the master page. In addition,
you need to convert a Web Form into a content page, move the content from the
content page to the master page, and create a new content page with a user control.
Module 5: Implementing Master Pages and User Controls 5-51
X Task 2: Initialize the style controls and elements on the master page
• In the Site.master window, add an id property to the head element by using
the following code.
• Reference the Site.css file in the Site.master Web Form, relative to the root
folder, by placing the following markup next to the closing tag of the title
element.
• In the Site.master window, add a Class property to the body element by using
the following markup.
<body class="template">
• In the Site.master window, add a Class property to the div element by using
the following markup.
<div class="content">
• In the Site.master window, set the value of the title element to Contoso
Customer Management by using the following code.
<div class="content">
<asp:ContentPlaceHolder id="MainContentPlaceHolder"
runat="server">
</asp:ContentPlaceHolder>
</div>
Results: After completing this exercise, you will have created a master page named
Site.master, and defined a ContentPlaceHolder control on the master page.
Module 5: Implementing Master Pages and User Controls 5-53
• Remove the top-level HTML elements from the Default Web Form.
Note: You should take care not to delete the div element and its content within the
form element.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css"
/>
</head>
<body>
<form id="form1" runat"server">
</form>
</body>
</html>
5-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:Content ID="MainContent"
ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
</asp:Content>
• In the Default.aspx window, move the following code and it after the opening
tag of the form element on the Site.master master page.
<div class="appTitle">
<asp:Literal ID="AppTitleLiteral" runat="server"
Text="Customer Management"></asp:Literal>
</div>
• Format the Site.master master page, by pressing CTRL+K, and then pressing
CTRL+D.
• Save the changes to the Site.master master page.
• Format the Default.aspx Web Form, by pressing CTRL+K, and then pressing
CTRL+D.
• Save and close the Default.aspx Web Form.
<div class="siteMapPath">
<asp:SiteMapPath ID="MainSiteMapPath" runat="server" />
</div>
Module 5: Implementing Master Pages and User Controls 5-55
• Add a menu to the master page by adding a Menu control named MainMenu,
wrapped in a div element with a class attribute value of menu. Add the new
div element below the existing div element with a class attribute value of
siteMapPath.
<div class="menu">
<asp:Menu ID="MainMenu" runat="server">
</asp:Menu>
</div>
Orientation="Horizontal"
• Ensure that the built-in image that indicates if a static menu item has a child
menu is not displayed, by setting the StaticEnableDefaultPopOutImage
attribute.
StaticEnableDefaultPopOutImage="false"
• Get the items for the Menu control from the MainSiteMapDataSource data
source control by applying the DataSourceID attribute.
DataSourceID="MainSiteMapDataSource"
• Add the following child elements to the Menu control, by placing them
between the opening and closing Menu tags.
• Remove all the top-level HTML elements, such as the DOCTYPE, html, head,
body, title, link, and form elements.
• Format the document.
Note: After removing all top-level HTML elements, you can view the following markup in
the InsertCustomer.aspx window.
5-58 Introduction to Web Development with Microsoft® Visual Studio® 2010
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCityTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerStateTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCountryLabel" runat="server"
Text="Country:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:DropDownList ID="CustomerCountryDropDownList"
runat="server">
</asp:DropDownList>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerPhoneLabel" runat="server"
Text="Phone:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerPhoneTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerEmailAddressLabel"
runat="server" Text="Email Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerEmailAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerWebAddressLabel" runat="server"
Text="Web Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerWebAddressTextBox"
runat="server" MaxLength="80"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCreditLimitLabel"
runat="server" Text="Credit Limit:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCreditLimitTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerNewsSubscriberLabel"
runat="server" Text="News Subscriber:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:CheckBox ID="CustomerNewsSubscriberCheckBox"
runat="server" />
</div>
</div>
<div class="customerTableFooter">
<asp:Button ID="CustomerInsertButton" runat="server"
Text="Insert" />
<asp:Button ID="CustomerCancelButton" runat="server"
Text="Cancel" />
</div>
</div>
• Open the Customer.ascx.vb user control code-behind file, change the class
name to Customer, and change its base class from System.Web.UI.Page to
System.Web.UI.UserControl.
• Move the content from the Page_LoadComplete event method, and append it
to the Page_Load event method.
''' <summary>
''' Populates UI controls
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks<>/remarks>
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.LoadComplete
End Sub
• Save the modified files, and close the Customer.ascx.vb user control.
Note: Notice that the new user control displays on the InsertCustomer Web Form.
X Task 5: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have converted the default Web
Form into a content page, added navigation to the master page, and then converted
the Web Form into a user control. In addition, you should have created a content
page and inserted a user control.
Module 5: Implementing Master Pages and User Controls 5-63
Section 2: Visual C#
Exercise 1: Adding and Applying a Master Page
The main tasks for this exercise are as follows:
X Task 2: Initialize the style controls and elements on the master page
• In the Site.master window, add an id property to the head element by using
the following code.
• Reference the Site.css file in the Site.master Web Form, relative to the root
folder, by placing the following markup next to the closing tag of the title
element.
• In the Site.master window, add a Class property to the body element by using
the following markup.
<body class="template">
• In the Site.master window, add a Class property to the div element by using
the following markup.
<div class="content">
• In the Site.master window, set the value of the title element to Contoso
Customer Management by using the following code.
<div class="content">
<asp:ContentPlaceHolder id="MainContentPlaceHolder"
runat="server">
</asp:ContentPlaceHolder>
</div>
Results: After completing this exercise, you will have created a master page named
Site.master, and defined a ContentPlaceHolder control on the master page.
Module 5: Implementing Master Pages and User Controls 5-65
• Remove the top-level HTML elements from the Default Web Form.
Note: You should take care not to delete the div element and the content within the
form element.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css"
/>
</head>
<body>
<form id="form1" runat"server">
</form>
</body>
</html>
5-66 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:Content ID="MainContent"
ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
</asp:Content>
• In the Default.aspx window, move the following code and place the code after
the opening tag of the form element on the Site.master master page.
<div class="appTitle">
<asp:Literal ID="AppTitleLiteral" runat="server"
Text="Customer Management"></asp:Literal>
</div>
• Format the Site.master master page, by pressing CTRL+K, and then pressing
CTRL+D.
• Save the changes to the Site.master master page.
• Format the Default.aspx Web Form, by pressing CTRL+K, and then pressing
CTRL+D.
• Save and close the Default.aspx Web Form.
<div class="siteMapPath">
<asp:SiteMapPath ID="MainSiteMapPath" runat="server" />
</div>
• Add a menu to the master page by adding a Menu control named MainMenu,
wrapped in a div element with a class attribute value of menu. Add the new
div element below the existing div element with a class attribute value of
siteMapPath.
<div class="menu">
<asp:Menu ID="MainMenu" runat="server">
</asp:Menu>
</div>
Module 5: Implementing Master Pages and User Controls 5-67
Orientation="Horizontal"
• Ensure that the built-in image that indicates if a static menu item has a child
menu is not displayed, by setting the StaticEnableDefaultPopOutImage
attribute.
StaticEnableDefaultPopOutImage="false"
• Get the items for the Menu control from the MainSiteMapDataSource data
source control by applying the DataSourceID attribute.
DataSourceID="MainSiteMapDataSource"
• Add the following child elements to the Menu control, by placing them
between the opening and closing Menu tags.
• Position: relative
• Z-order: 1
• Top: 62px
• Add a siteMapPath style, by using the Manage Styles window. The
siteMapPath style must have the following definition:
• Selector: div.siteMapPath
• Define in: Styles/Site.css
• Category: Position
• Position: fixed
• Top: 42px
• Category: Box
• Padding section: Remove the selection from the Same for all check box; in
the bottom box, type 5px
• Save all modified files, and run the Site.master master page.
• Remove all the top-level HTML elements, such as the DOCTYPE, html, head,
body, title, link, and form elements.
• Format the document.
Note: After removing all top-level HTML elements, you can view the following markup in
the InsertCustomer.aspx window.
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerAddressLabel" runat="server"
Text="Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerZipCodeLabel" runat="server"
Text="Zip Code:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerZipCodeTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCityTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerStateTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCountryLabel" runat="server"
Text="Country:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:DropDownList ID="CustomerCountryDropDownList"
runat="server">
</asp:DropDownList>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerPhoneLabel" runat="server"
Text="Phone:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerPhoneTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerEmailAddressLabel"
runat="server" Text="Email Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerEmailAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerWebAddressLabel" runat="server"
Text="Web Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerWebAddressTextBox"
runat="server" MaxLength="80"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCreditLimitLabel"
runat="server" Text="Credit Limit:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCreditLimitTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerNewsSubscriberLabel"
runat="server" Text="News Subscriber:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:CheckBox ID="CustomerNewsSubscriberCheckBox"
runat="server" />
</div>
</div>
<div class="customerTableFooter">
<asp:Button ID="CustomerInsertButton" runat="server"
Text="Insert" OnClick="CustomerInsertButton_Click" />
<asp:Button ID="CustomerCancelButton" runat="server"
Text="Cancel" OnClick="CustomerCancelButton_Click" />
</div>
</div>
• Move the content from the Page_LoadComplete event method, and append it
to the Page_Load event method.
/// <summary>
/// Populates UI controls
/// </summary>
/// <param name="sender">>/param>
/// <param name="e"></param>
protected void Page__LoadComplete(object sender, EventArgs e)
{
}
• Save the modified files and close the Customer.ascx.cs user control.
Note: Notice that the new user control displays on the InsertCustomer Web Form.
X Task 5: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have converted the default Web
Form to a content page, added navigation to the master page, and then converted
the Web Form into a user control. In addition, you will have created a content page
and inserted a user control.
5-74 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Review
Best Practices
Mention some best practices in the context of your own business situations.
• Use master pages whenever you have a layout that will be used for two or
more pages.
• Apply master pages in the web.config file, if it is to be used with all or nearly all
the pages on the Web site, or in specific areas of the Web site. This makes it
easier to replace the master pages at a later stage.
Validating User Input 6-1
Module 6
Validating User Input
Contents:
Lesson 1: Overview of User Input Validation 6-4
Lesson 2: ASP.NET Validation Controls 6-10
Lesson 3: Validating Web Forms 6-37
Lab: Validating User Input 6-43
6-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
When you create an input control such as a TextBox control, you have
expectations or requirements about the type of input that the user will enter into
that control. Incorrect input can in the worst case, break your Web application. To
verify that the user input meets your requirements, you must check the input
against the value, range, or format of the input that you expect to receive from the
user. To create this check, you need to link at least one input validation control to
the input control, and then set the criteria of the validation control to test for your
requirements.
Various input validation controls are available in Microsoft® ASP.NET. You can
apply these controls to an ASP.NET Web Form to perform both client-side and
server-side input validation. When you use client-side validation instead of server-
side validation, you reduce the traffic of data between the client and server, save
server resources, and improve the response time of your Web application.
Validating User Input 6-3
There is more to a secure application than validating user input, and with regards
to input validation, there are many other types of input that must be validated.
Your Web Form must validate input from an external service such as a Web
service, or input from externally supplied files.
There are also concerns about how input validation is performed in the different
layers of an application. This module discusses user input, which generally means
the User Interface (UI) layer, but the business logic layer (BLL) and the data access
layer (DAL) also require input validation. These layers are used by other parts or
layers of an application, and this means that input validation might have already
been performed, but as a developer you cannot rely on that; you must make sure
that input is validated wherever input is accepted.
6-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 1
Overview of User Input Validation
You can perform input validation at the client side or the server side to verify that
the user has filled in the valid data in the input controls on a Web Form, before the
request is processed on the server. Using client-side input validation, you can filter
incorrect input before input is submitted to the server. Using server-side validation,
you can perform validation checks on the server and on the client.
If you do not validate user input, it may lead to application crashes, application
damage, malicious database manipulation, or even database corruption. Input
validation is a powerful mechanism to check for errors, and if necessary, to display
messages to the user.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe input validation.
• Describe client-side and server-side input validation.
Validating User Input 6-5
Key Points
Input validation can help improve a user’s experience with a Web site by reducing
the waiting time for error messages, and reducing the likelihood of incorrect
returns and Web sites crashing due to problems with user input. When combined
with comprehensive and useful error messages, input validation can help you
improve the usability of a Web site, and improve the customer’s perception of the
overall quality of the Web site.
6-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Input validation verifies that the user has correctly filled in an input control before
the request is processed on the server. The input validation on a Web page acts as
a data filter before the page or server logic is processed. In ASP.NET, input
validation always runs on the server side, but it can also run on the client side if the
client browser supports validation. If the browser supports client-side validation
and validation is enabled, the input validation mechanisms that you create perform
error checking on the client before posting the data to the server. Users receive
immediate feedback on whether the data that they entered is valid according to the
rules that were created. For security reasons, any input validation that is run on the
client side is also repeated on the server side. Input validation verifies control
values, prevents page processing when invalid data is found, and helps avoid the
addition of malicious code.
With ASP.NET, client-side input validation is always repeated on the server side,
where users cannot modify or disable validation controls.
• Malicious code. If users are allowed to add unlimited text to a Web page
through user input controls that do not have input validation, they may enter
malicious code. When the user sends the next request to the server, this code
can be disruptive on the Web server and any connected applications.
Key Points
Input validation can take place on both the client side and the server side.
Although server-side validation is always required by ASP.NET, client-side
validation is an option with some browsers. The validation controls in ASP.NET
have both client-side and server-side support. Client-side validation uses JavaScript
and Dynamic HTML (DHTML) scripts. Server-side validation can be written in any
Microsoft .NET Framework–based language. Both client-side and server-side
validation use the same programming model, although variations among languages
may create minor differences to the validation functions.
Client-Side Validation
Client-side validation enhances the usability of the Web Form by checking user
input when the user enters data. By checking for errors when data is entered,
client-side validation allows errors to be detected on the client-side before the Web
Form is submitted. This prevents the round trip that is necessary for server-side
validation.
Validating User Input 6-9
Writing multiple versions of validation code to support both the server and several
types of browsers can be time consuming. ASP.NET validation controls eliminate
this problem, because the validation logic is encapsulated in the controls. The
controls create browser-specific code so that users with client-side script support
will have client-side input validation. Browsers that do not support scripts will not
receive client-side validation scripts.
In browser versions that support input validation—such as Windows® Internet
Explorer® 8—client-side validation occurs when users click the Submit button.
The page will not be posted back to the server until all the client-side validation
completes. In modern browsers, when the user moves from one input control to
the next, the client-side validation happens for the completed input control. This
validation feature provides users with immediate feedback on their input.
Server-Side Validation
All input validation controls run on the server side. Client-side validations are
repeated on the server side when the page posts back to the server. This repetition
helps avoid spoofing attempts by users who try to bypass the client-side script and
send invalid input.
You can write Microsoft .NET-based server-side validation controls. In addition to
validating input format, you can use server-side validation controls to compare
user input with stored data. This ability to compare user input with stored data
allows the validation of many values, such as valid credit card numbers, stored
passwords, and geographical restrictions related to local laws and taxes.
Question: When will you post a page to the server, even with errors?
6-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson 2
ASP.NET Validation Controls
Validating user input used to be a tedious and time-consuming process. For each
input control, you needed to determine the requirements, and then write the
validation code for the server in your preferred programming language. Then, if
you wanted to perform client-side validation, you would write the equivalent client-
side validation for each expected browser in a script language, such as JavaScript.
ASP.NET and Microsoft Visual Studio® 2010 help you easily validate user input by
providing input validation controls that provide both server-side and client-side
code.
Lesson Objectives
After completing this lesson, you will be able to:
• Describe the various ASP.NET validation controls.
• Describe the RegularExpressionValidator control.
• Describe the CustomValidator control.
Validating User Input 6-11
Key Points
When creating ASP.NET Web Forms that require user input, one of the most
important aspects is the ability to check whether user input is valid. ASP.NET
provides a set of validation controls that help you to easily and effectively check
for input errors. In addition, it is possible to display error messages to the user, if
required.
Validating User Input 6-13
Validation Controls
The following table lists the validation controls that are included in the ASP.NET
page framework.
Key Points
The basic validation controls are the RequiredFieldValidator, CompareValidator,
and RangeValidator controls. These validation controls validate against fixed
values or a second input control, and expose the public ControlToValidate
property, which identifies the input control that should be validated.
<asp:RequiredFieldValidator id="NameRequiredFieldValidator"
runat="server" ControlToValidate="NameTextBox" InitialValue="Enter
your name" ErrorMessage="You must enter your name" Text="*" />
In the following code example, a CompareValidator control verifies that the values
of the two TextBox controls, PasswordTextBox and
PasswordConfirmationTextBox, match.
The RangeValidator control will evaluate an empty input control as valid, and
therefore, you must combine it with the RequiredFieldValidator control, if you
need to ensure a value. The RangeValidator control has the following properties:
• MinimumValue. This property specifies the minimum value of the valid range
for numeric variables, or the minimum character length of the string for string
variables.
• MaximumValue. This property specifies the maximum value of the valid range
for numeric variables, or the maximum character length of the string for string
variables.
• Type. This property specifies the data type of the values to compare against
one of the .NET Framework data types, System.String, System.Int32,
System.Double, System.DateTime, and System.Decimal. You can do this by
specifying the corresponding value from the ValidationDataType enum:
String, Integer, Double, Date, or Currency. Note that for dates, only the date
portion can be specified, and not the time portion. The values to compare are
converted to this data type before any comparison is performed.
In the following code example, a RangeValidator control verifies that the TextBox
named AgeTextBox has a value in the range 18–50.
Question: Which server control will you use to perform data-type validation?
6-18 Introduction to Web Development with Microsoft® Visual Studio® 2010
RegularExpressionValidator Control
Key Points
You can use the RegularExpressionValidator control to verify that a user’s input
matches a predefined pattern—such as a telephone number, a postal code, a URL,
or an e-mail address. This validation control compares the pattern of characters,
digits, and symbols that are entered by the user, with one or more patterns in the
control.
In the Properties window, when you click the ellipsis (…) button for the
ValidationExpression property, Visual Studio 2010 provides a set of preset
regular expression patterns in the Regular Expression Editor dialog box. These
patterns include e-mail addresses and URLs, telephone numbers, postal codes and
zip codes, and social security numbers. To create a new pattern, first select a
pattern that resembles the functions of your desired pattern, and then select the
Custom template. The pattern that you first selected will then be available for
editing as your own custom pattern. This last-used feature gives you a foundation
from which you can create your own pattern by editing what you know will work.
Validating User Input 6-19
Character Definition
a Matches the lowercase letter a. This is the case for all alphabet
characters. Any letter that is not preceded by a backslash (\), or part
of a range, matches that literal value.
1 Matches the number or digit 1. This is the case for all numeric
characters. Any number or digit that is not preceded by a backslash
(\), or part of a range, matches that literal value.
? Matches 0 or 1 literal.
* 0 to n literals.
\ Is a command character.
<asp:RegularExpressionValidator id="EmailRegexValidator"
runat="server" ControlToValidate="EmailTextBox" ErrorMessage="Use the
format username@organization.xxx" ValidationExpression="\w+@\w+\.\w+"
Text="*" />
...
<script type="text/javascript">
//<![CDATA[
function WebForm_OnSubmit() {
if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() ==
false) return false;
return true;
}
//]]>
</script>
...
</div>
<div>
<input name="EmailTextBox" type="text" id="EmailTextBox" />
<span id="EmailRegexValidator"
style="visibility:hidden;">*</span>
</div>
<script type="text/javascript">
//<![CDATA[
var Page_Validators = new
Array(document.getElementById("EmailRegexValidator"));
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
var EmailRegexValidator = document.all ?
document.all["EmailRegexValidator"] :
document.getElementById("EmailRegexValidator");
EmailRegexValidator.controltovalidate = "EmailTextBox";
EmailRegexValidator.errormessage = "Use the format
username@organization.xxx";
EmailRegexValidator.evaluationfunction =
"RegularExpressionValidatorEvaluateIsValid";
EmailRegexValidator.validationexpression = "\\w+@\\w+\\.\\w+";
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
function ValidatorOnSubmit() {
if (Page_ValidationActive) {
return ValidatorCommonOnSubmit();
}
else {
return true;
}
}
//]]>
</script>
6-22 Introduction to Web Development with Microsoft® Visual Studio® 2010
The following table describes the specific pattern for which the
RegularExpressionValidator control checks, in the preceding example.
Character Definition
@ An at sign (@).
\. A period.
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
The following table describes the e-mail address pattern in the preceding code
example.
Character Definition
\w+ Matches a string of at least one character.
(continued)
Character Definition
([-.]\w+)* Matches a hyphen or period (.), and a string of at least one character.
([-.]\w+)* Matches a hyphen or period (.), and a string of at least one character.
CustomValidator Control
Key Points
You can use the CustomValidator control to apply your customized validation
logic, and check user input against a variable, formula, or input from a second
source. The CustomValidator control is often used for tasks such as password
verification, in which case the user input is compared with a password that is
stored in a database.
The CustomValidator control has the following two members that are specific to
the control:
• ClientValidationFunction. This property is the name of the script that you
want the CustomValidator control to run on the client side. Because you write
your own client script, it is important to check for logical consistency with the
server-side code.
• OnServerValidate. This is the name of the method that you want the
CustomValidator to run on the server side, when the ServerValidate event is
triggered. Because you write your own server code, it is important to check for
logical consistency with the client-side script.
The following code example demonstrates the server-side and client-side handlers
for a CustomValidator control, and verifies that the input number for the control
is even.
Client-Side Handler
The following JavaScript code is designed to run on Internet Explorer 6 or later,
and verifies that a number is even.
<script type="text/javascript">
function ClientValidationHandler(source, args)
{
args.IsValid = (args.Value % 2 == 0)
}
</script>
6-26 Introduction to Web Development with Microsoft® Visual Studio® 2010
Server-Side Handler
The following code examples are designed to run on the server and verify that a
number is even. Place this code in the Web Form in a script element or in the Page
derived class for the Web Form.
[Visual Basic]
Protected Sub ServerValidationHandler(ByVal source as Object,
ByVal args as ServerValidateEventArgs)
[Visual C#]
protected void ServerValidationHandler(object source,
ServerValidateEventArgs args)
{
args.IsValid = (args.Value % 2 == 0)
}
Note that the value from the input control can be accessed on both the client-side
and the server-side by using the Value property of the args parameter on both the
client-side and the server-side.
Setting the ControlToValidate property is not required for the CustomValidator
control. However, if you do not specify a value for the ControlToValidate
property, an empty string is passed to the client-side and server-side validation
functions.
Key Points
Sometimes a single validation function or control is not sufficient to verify that the
user has correctly entered data into an input control.
Most often you combine the RequiredFieldValidator control with one of the other
validation controls, but other scenarios do exist.
For example, a telephone number TextBox control may require an input, must
conform to one of several telephone number patterns, and must be checked
against a stored telephone number database. In this scenario, you should
link the TextBox control to a RequiredFieldValidator control, link a
RegularExpressionValidator control with several patterns, and link a
CustomValidator control with server-side access to a database.
6-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:RequiredFieldValidator id="PhoneRequiredFieldValidator"
runat="server" ErrorMessage="The telephone number is required."
ControlToValidate="PhoneTextBox" Text="*" />
<asp:RegularExpressionValidator
id="PhoneRegularExpressionValidator" runat="server"
ErrorMessage="The telephone number is not formatted as a correct
US phone number." ControlToValidate="PhoneTextBox"
ValidationExpression="((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
Text="*" />
<asp:CustomValidator id="PhoneCustomValidator"
OnServerValidate="PhoneServerValidationHandler" runat="server"
ErrorMessage="This telephone number is not recognized"
ControlToValidate="PhoneTextBox" Text="*" />
Validating User Input 6-29
Key Points
In this demonstration, you will see how to add validation controls to an ASP.NET
Web Form.
Demonstration Steps
1. Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
2. Open Visual Studio 2010.
• On the Start menu of 10267A-GEN-DEV, click All Programs, click
Microsoft Visual Studio 2010, and then click Microsoft Visual
Studio 2010.
3. Open an existing Web site from either D:\Demofiles\M6\VB\Validation or
D:\Demofiles\M6\CS\Validation.
• On the File menu of the Start Page - Microsoft Visual Studio window, click
Open Web Site.
6-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Open Web Site dialog box, in the Folder box, type either
D:\Demofiles\M6\VB\Validation or D:\Demofiles\M6\CS\Validation,
and then click Open.
4. Open the Order Web Form in Design view.
• In Solution Explorer, right-click Order.aspx, and then click View
Designer.
5. Add a RequiredFieldValidator control named
DueDateRequiredFieldValidator, for the DueDateTextBox control, with an
asterisk (*) as the text, and The Due Date must be filled in. as the error
message. The display must be dynamic.
<asp:RequiredFieldValidator ID="DueDateRequiredFieldValidator"
ControlToValidate="DueDateTextBox" runat="server"
ErrorMessage="The Due Date must be filled in."
Text="*"></asp:RequiredFieldValidator>
• In the Order.aspx window, place the cursor next to the Due Date TextBox
control.
• In the Toolbox, expand Validation, and then double-click
RequiredFieldValidator.
• In Properties window, in the (ID) box, type
DueDateRequiredFieldValidator, in the ControlToValidate list, click
DueDateTextBox, and in the Display list, click Dynamic. In the Text box,
type *, in the ErrorMessage box, type The Due Date must be filled in.,
and then press ENTER.
6. Add a RangeValidator control named DueDateRangeValidator for the
DueDateTextBox control, with an asterisk (*) as the text, and The Due Date
must be valid. as the error message. The validator should accept only dates.
Today’s date should be set as the minimum value, and today’s date plus 30
days should be set as the maximum value, both programmatically.
<asp:RangeValidator ID="DueDateRangeValidator"
ControlToValidate="DueDateTextBox" runat="server"
ErrorMessage="The Due Date must be valid."
Text="*"></asp:RangeValidator >
[Visual Basic]
DueDateRangeValidator.MinimumValue =
DateTime.Now.ToShortDateString()
DueDateRangeValidator.MaximumValue = (DateTime.Now +
New TimeSpan(30, 0, 0, 0)).ToShortDateString()
[Visual C#]
DueDateRangeValidator.MinimumValue =
DateTime.Now.ToShortDateString();
DueDateRangeValidator.MaximumValue = (DateTime.Now +
new TimeSpan(30, 0, 0, 0)).ToShortDateString();
<asp:RegularExpressionValidator
ID="CustomerEmailAddressRegularExpressionValidator"
ControlToValidate="CustomerEmailAddressTextBox" runat="server"
ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*@\w+([-
.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
• In the Order.aspx window, place the cursor next to the Email Address
TextBox control.
• In the Toolbox, expand Validation, and then double-click
RegularExpressionValidator.
6-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:ValidationSummary ID="OrderValidationSummary"
runat="server"></asp:ValidationSummary>
Note: Notice that today’s date has been added to the Order Date box.
Note: Notice that there is an asterisk next to the Due Date box, and an error message in
the validation summary at the bottom.
Note: Notice that there is an asterisk next to the Due Date box, at the same location as
the one shown on the previous try to save the order, and there is a different error
message in the validation summary at the bottom.
Note: Notice that there is an asterisk next to the Email Address box, and an error
message in the validation summary at the bottom.
Key Points
Input validation controls can display an error message when an input violation has
occurred. It is important to position input validation controls so that it is clear to
the user which control has the incorrect input. In Visual Studio 2010, you must
position the validation control on the page where the error message text should
appear.
The following code is the standard markup for an input validation control.
In Visual Studio 2010, by default, the value for the Text property is placed between
the begin and end tags of the validation control. The following code illustrates this
scenario.
<asp:ValidatorType...>TextValue</asp:ValidatorType>
You can explicitly declare the Text property. The following code
illustrates this approach.
<asp:ValidatorType...Text="TextValue"></asp:ValidatorType> or
<asp:ValidatorType...Text="TextValue" />
Option Description
Static Defines a fixed layout for the error message that causes each
validation control to occupy space, even when no error message text
is visible. This option allows you to define a fixed layout for the page,
and it is the default option in Visual Studio 2010.
Dynamic Enables validation controls to render on the page as part of the text
flow. You can use this option to prevent the display of blank spaces
on the page when input validation controls are not triggered. This
option sometimes causes controls to move on the Web Form when
error messages display.
None Blocks the display of the error message at the location of the
validation control.
The ValidationSummary control should be placed where it makes sense for the
user to look, if the page is not posted back to the server. This quite often means
placing the ValidationSummary control near the submit button(s).
Validating User Input 6-37
Lesson 3
Validating Web Forms
You should always validate user input at the source, as a best practice. However, to
avoid script exploits and to ensure that validation is performed, you should
manually apply server-side validation. You can add server-side validation code to
your ASP.NET Web Forms by using Visual Studio 2010.
Lesson Objectives
After completing this lesson, you will be able to:
• Add the ValidationSummary control.
• Programmatically validate Web Forms.
6-38 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
The ValidationSummary control displays error messages when the Page.IsValid
property returns false. Each of the validation controls on the page is polled, and
the ValidationSummary control aggregates the ErrorMessage messages. The
ValidationSummary control is not a control that performs validations on the
content input in your Web Forms; instead, this control is the reporting control
that is used by the other validation controls on a page.
You can use this validation control to consolidate error reporting for all the
validation errors that occur on a page, instead of requiring each and every
individual validation control to do this.
Validating User Input 6-39
<asp:ValidationSummary id="MyValidationSummary"
runat="server"
HeaderText="These errors were found:"
ShowSummary="True"
DisplayMode="List" />
Locating Errors
The Text property of a validation control displays at the location of the validation
control, and the ErrorMessage property displays in the ValidationSummary
control display.
A Text property with a red asterisk (*) typically displays to the right of the input
control to warn the user that the input control has not been filled in correctly. An
ErrorMessage property with a description of the input error displays in the
ValidationSummary control, which is usually placed near the event that triggers
the control.
Question: How will you summarize error messages from a group of validation
controls on a Web Form?
6-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
The ASP.NET validation controls perform validation automatically when a Web
Form is posted back to the server. This happens after page initialization, but before
the control event-handling code is run.
Sometimes you may want to apply your own validation programmatically:
• If you are adding controls dynamically at run time.
• If you are setting validation values at run time, such as the MinimumValue or
MaximumValue of the RangeValidator control.
• If you need to determine the validity of a page or an individual control in the
Page_Load event handler, such as preventing the access of certain server-side
resources—like a database—when a page is invalid.
Validating User Input 6-41
The IsValid property determines the validity of the page or a validation control.
The problem with this property is that when it is set, it is accessible without an
exception being thrown. So, if you want to determine validity before the validation
control event handler methods are run, you can programmatically start the
validation by calling the Validate method of the page or control. The following
code examples demonstrate how you can call the Validate method.
[Visual Basic]
Me.Validate()
[Visual C#]
this.Validate();
Another example for apply your own programmatic validation is when you are
working with the RangeValidator control, and you are setting the MinimumValue
property at run time based on values read from a configuration file.
After the validation runs, you can check the IsValid property of the Page. If the
IsValid property is false, then you will need to find out which of the individual
controls are failing the validation by checking the IsValid property of each
validation control. When a control performs its validation check, the IsValid
property is set accordingly. When an error is detected and the page is returned to
the user, the error messages display.
The following code examples illustrate how you can validate a page on postback,
and find the validation control that caused the validation error.
[Visual Basic]
' User postback?
If Me.IsPostBack Then
' Validate page
Me.Validate()
[Visual C#]
// User postback?
if (this.IsPostBack)
{
// Validate page
this.Validate();
// Is page valid?
if (!this.IsValid)
{
// Loop through all validation controls to see which
// generated the error(s)
foreach (IValidator controlValidator in this.Validators)
{
if (!controlValidator.IsValid)
{
...
}
}
}
}
Note: You can perform tasks in this lab either by using either the Microsoft Visual Basic®
or Microsoft Visual C#® programming language. If you are using Visual Basic as your
programming language, refer to the steps provided in the Section 1 of the lab document.
If you are using Visual C# as your programming language, refer to the steps provided in
Section 2 of the lab document.
Lab Introduction
In this lab, you will add and configure validation controls in a user control to help
you ensure valid user inputs in a Web project. You will use client-side scripting,
which will help you avoid frequent cross-checking of user inputs with the server. In
addition, you will perform server-side validation to protect the Web project against
spoofing and malicious code.
6-44 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Objectives
After completing this lab, you will be able to:
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
Validating User Input 6-45
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses a Web site to manage its customer
information. For effective communication, the organization should maintain
updated customer information in their database. To meet this requirement, you
need to add and configure validation controls to the Customer Management
project without causing administrative overheads or performance issues from
frequent cross-checking with the server.
6-46 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:RequiredFieldValidator
ID="CustomerFirstNameRequiredFieldValidator"
ControlToValidate="CustomerFirstNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerLastNameRequiredFieldValidator"
ControlToValidate="CustomerLastNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
Validating User Input 6-47
<asp:RequiredFieldValidator
ID="CustomerAddressRequiredFieldValidator"
ControlToValidate="CustomerAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerZipCodeRequiredFieldValidator"
ControlToValidate="CustomerZipCodeTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCityRequiredFieldValidator"
ControlToValidate="CustomerCityTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
6-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:RequiredFieldValidator
ID="CustomerWebAddressRequiredFieldValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCreditLimitRequiredFieldValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RegularExpressionValidator
ID="CustomerEmailAddressRegularExpressionValidator"
ControlToValidate="CustomerEmailAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
<asp:RegularExpressionValidator
ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
Validating User Input 6-49
<asp:RangeValidator ID="CustomerCreditLimitRangeValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
MinimumValue="500" MaximumValue="50000"
ErrorMessage="RangeValidator"></asp:RangeValidator>
<asp:ValidationSummary ID="CustomerValidationSummary"
runat="server"></asp:ValidationSummary>
Result: After completing this exercise, you will have added validation controls to a
user control.
6-50 Introduction to Web Development with Microsoft® Visual Studio® 2010
''' <summary>
''' Redirects to home page
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub CustomerCancelButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles CustomerCancelButton.Click
' Redirect to home page
Response.Redirect("~/Default.aspx")
End Sub
• Save the Customer user control, and view the changes in the browser.
Note: Notice that the Web browser is redirected to the default Web Form, instead of
displaying the error messages.
Validating User Input 6-51
Note: Notice the error indicator that displays next to the Email Address and Web
Address boxes, because of the invalid e-mail and web addresses.
Validating User Input 6-53
Note: Notice the error indicator and error messages next to the First Name, Last Name,
Address, Zip Code, City, Country, and Credit Limit controls.
f Task 3: Set the e-mail address and credit limit validation controls
• View the InsertCustomer.aspx Web Form in a browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
click the Insert button.
Note: Notice that the value for Credit Limit box is set to 0 and the error indicator text
for the Web Address box is not aligned with the other error indictors. Also notice that
the error message for the Credit Limit box is The Credit Limit must be within the
valid range.
Note: Notice that the location of the error indicator for the Credit Limit box has
changed. However, the error message for the Credit Limit box is still The Credit Limit
must be within the valid range.
Note: Notice that the error indicator and error messages do not display for the Email
Address, Web Address, and Credit Limit boxes.
Results: After completing this exercise, you will have removed validation control from
the Cancel button, and added error indicators and error messages to the validation
controls.
Validating User Input 6-55
''' <summary>
''' Saves the current customer information and adds default values
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub CustomerInsertButton_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles CustomerInsertButton.Click
' Did page validation succeed?
If Not Page.IsValid Then
Return
End If
''' <summary>
''' Instantiates Customer object
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
' Validate Page
Page.Validate()
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected." Text="*"
EnableClientScript="false"></asp:RequiredFieldValidator>
• Save the Customer user control, and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer, type the
following settings, and then click the Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
Validating User Input 6-57
Note: Notice the postback of the Web page with the inputs. Also notice that after the
postback, the error indicator for the Country list and associated error message display.
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected."
Text="*"></asp:RequiredFieldValidator>
f Task 2: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have added server-side validation
controls to the Customer user control.
Note: The answers to the exercises are on the Course Companion CD.
6-58 Introduction to Web Development with Microsoft® Visual Studio® 2010
Section 2: Visual C#
Exercise 1: Adding Validation Controls
The main tasks for this exercise are as follows:
<asp:RequiredFieldValidator
ID="CustomerFirstNameRequiredFieldValidator"
ControlToValidate="CustomerFirstNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerLastNameRequiredFieldValidator"
ControlToValidate="CustomerLastNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
Validating User Input 6-59
<asp:RequiredFieldValidator
ID="CustomerAddressRequiredFieldValidator"
ControlToValidate="CustomerAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerZipCodeRequiredFieldValidator"
ControlToValidate="CustomerZipCodeTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCityRequiredFieldValidator"
ControlToValidate="CustomerCityTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
6-60 Introduction to Web Development with Microsoft® Visual Studio® 2010
<asp:RequiredFieldValidator
ID="CustomerWebAddressRequiredFieldValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RequiredFieldValidator
ID="CustomerCreditLimitRequiredFieldValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
<asp:RegularExpressionValidator
ID="CustomerEmailAddressRegularExpressionValidator"
ControlToValidate="CustomerEmailAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
<asp:RegularExpressionValidator
ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
Validating User Input 6-61
<asp:RangeValidator ID="CustomerCreditLimitRangeValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
MinimumValue="500" MaximumValue="50000"
ErrorMessage="RangeValidator"></asp:RangeValidator>
<asp:ValidationSummary ID="CustomerValidationSummary"
runat="server"></asp:ValidationSummary>
Result: After completing this exercise, you will have added validation controls to a
user control.
6-62 Introduction to Web Development with Microsoft® Visual Studio® 2010
/// <summary>
/// Redirects to home page
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CustomerCancelButton_Click(object sender, EventArgs
e)
{
// Redirect to home page
Response.Redirect("~/Default.aspx");
}
• Save the Customer user control and view the changes in the browser.
Note: Notice that the Web browser is redirected to the default Web Form, instead of
displaying the error messages.
Validating User Input 6-63
Note: If you see the AutoComplete message box display, click the No button.
Note: Notice the error indicator that displays next to the Email Address and Web
Address boxes, because of the invalid e-mail and web addresses.
Validating User Input 6-65
Note: Notice the error indicator and error messages next to the First Name, Last Name,
Address, Zip Code, City, Country, and Credit Limit controls.
f Task 3: Set the e-mail address and credit limit validation controls
• View the InsertCustomer.aspx Web Form in a browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
click the Insert button.
Note: Notice that the value for Credit Limit box is set to 0, and the error indicator text
for the Web Address box is not aligned with the other error indictors. Also notice that
the error message for the Credit Limit box is The Credit Limit must be within the
valid range.
Note: Notice that the location of the error indicator for the Credit Limit box has
changed. However, the error message for the Credit Limit box is still The Credit Limit
must be within the valid range.
Note: Notice that the error indicator and error messages do not display for the Email
Address, Web Address, and Credit Limit boxes.
Results: After completing this exercise, you will have removed validation control from
the Cancel button, and added error indicators and error messages to the validation
controls.
Validating User Input 6-67
/// <summary>
/// Saves the current customer information and adds default values
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CustomerInsertButton_Click(object sender, EventArgs
e)
{
// Did page validation succeed?
if (!Page.IsValid)
return;
// Instantiate Customer
instantiateCustomerObject();
// Populate the UI controls
populateUI();
}
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected." Text="*"
EnableClientScript="false"></asp:RequiredFieldValidator>
• Save the Customer user control and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer, type the
following settings, and then click the Insert button.
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
Validating User Input 6-69
Note: Notice the postback of the Web page with the inputs. Also notice that after the
postback, the error indicator for the Country list and its associated error message
displays.
<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected."
Text="*"></asp:RequiredFieldValidator>
f Task 2: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have added server-side validation
controls to the Customer user control.
Note: The answers to the exercises are on the Course Companion CD.
6-70 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Shutdown
After you complete the lab, you must turn off the 10267A-GEN-DEV virtual
machine and revert the changes.
1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click
10267A-GEN-DEV, and then click Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click
10267A-GEN-DEV, and then click Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Validating User Input 6-71
Lab Review
Best Practices
Mention some best practices in the context of your own business situations.
• Always add server-side validation code when using validation controls,
because client-side scripting might be disabled, or a malicious user could
compromise the user input, which could then be sent to the server.
• Always validate user input that is used for performing actions server-side, such
as searching a database or accessing server-side resources.
Troubleshooting Microsoft® ASP.NET Web Applications 7-1
Module 7
Troubleshooting Microsoft® ASP.NET Web
Applications
Contents:
Lesson 1: Debugging in ASP.NET 7-3
Lesson 2: Tracing in ASP.NET 7-23
Lab: Troubleshooting Microsoft ASP.NET Web Applications 7-36
7-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
When you develop a Web application, it is difficult to find every possible error in
code. Errors could include compile-time errors, logic errors, or runtime errors. You
can use the Microsoft® Visual Studio® 2010 compilers to identify compile-time
errors. To find runtime errors and logic errors, you can use the Visual Studio 2010
debugger, or use Visual Studio 2010 along with the Debug and Trace objects.
Debugging is an important part of development to ensure that a Web application
meets specified requirements. During the debugging process, you can identify
errors and fix them. You can also trace the application to capture its runtime
information and analyze its performance.
This module describes the steps required to enable tracing and debugging,
including how you can use debugging and tracing in a Web application.
Troubleshooting Microsoft® ASP.NET Web Applications 7-3
Lesson 1
Debugging in ASP.NET
You can use debugging to find errors in an ASP.NET Web application. Debugging
is the process of identifying and resolving the logical and technical errors in a Web
application. For most debugging operations, you can run the Visual Studio 2010
debugger on the computer hosting the Web application. You can debug a Web
application by adding breakpoints, and stepping through the code in debug mode.
While local debugging helps you debug applications on your local computer,
remote debugging enables you to debug a Web application that runs at a remote
location.
This lesson describes how you can perform both local debugging and remote
debugging.
7-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson Objectives
After completing this lesson, you will be able to:
• Describe types of errors.
• Describe debugging.
• Describe the Debug class.
• Explain how to gather debug information at run time.
• Describe the methods for printing Debug information.
• Describe debugging in a Web application.
• Describe remote debugging in a Web application.
Troubleshooting Microsoft® ASP.NET Web Applications 7-5
Key Points
When you develop applications, you could encounter several types of errors.
Before you can resolve these errors, you need to identify the type of error to fix it
appropriately.
There are three kinds of errors that you need to handle when you develop
applications: syntax errors, runtime errors, and semantic errors.
Syntax Errors
The syntax of an application must be correct for a compiler to be able to compile
the code, and for the application to run. Syntax refers to the application structure,
and the rules associated with the structure. For example, this could be the curly
braces that surround a block of code in Microsoft Visual C#®
((!this.IsPostBack) { Block of Code }), or the matching Begin and
End statements in Microsoft Visual Basic® (Sub SubName() ... End Sub.). If
you leave out one of the matching curly braces in Visual C#, or the End Sub
statement in Visual Basic, a syntax error occurs.
7-6 Introduction to Web Development with Microsoft® Visual Studio® 2010
Syntax errors are part of what is referred to as compile-time errors. Visual Studio
2010 warns you of potential errors at design time. Syntax notifications or squiggles
under code indicates that the code will not compile or that might cause an error.
You can identify syntax errors in order to resolve them when you compile the
application.
Runtime Errors
Runtime errors occur while the application is running. Runtime errors are also
known as exceptions. For example, an application may rely on another file at
runtime. However, if the file is not available when the application tries to access
it, an exception is thrown, and your application must decide whether or not to
handle the exception. Exception handling can be implemented by wrapping code
in a Try...Catch/try...catch construct, like the following example.
[Visual Basic]
Try
' Place any code here, that are critical to your application,
' that potentially throws an exception
Catch
' Add any cleanup/resolve code here to handle the exception
' thrown, or code to log the exception details
Finally
' Add any code that must be executed whether an exception
' is thrown or not
End Try
[Visual C#]
try
{
// Place any code here, that are critical to your application,
// that potentially throws an exception
}
catch
{
// Add any cleanup/resolve code here to handle the exception
// thrown, or code to log the exception details
}
finally
{
// Add any code that must be executed whether an exception
// is thrown or not
}
Troubleshooting Microsoft® ASP.NET Web Applications 7-7
Semantic Errors
Semantic errors are the hardest to locate and fix, because your application will
appear to run successfully and you will not see any error messages. However,
your application may not perform as intended. For example, a user performs a
calculation, and the correct result displays on the screen. If the calculation and
related operations are not saved to the data storage, a second user will view the
same data initially viewed by the first user. This means that the semantics of the
application are wrong. Identifying this type of error can be very tricky and
confusing, because it requires you to follow the input, output, and the flow of the
application’s logic to locate the bug.
7-8 Introduction to Web Development with Microsoft® Visual Studio® 2010
What Is Debugging?
Key Points
Programming errors are generally referred to as “bugs,” and the process of tracking
them is called debugging.
When you encounter a bug, you first need to decide whether you should fix it,
then identify the source of the error, and finally, fix the bug by using the tools
provided by Visual Studio 2010.
Note: At development time, most bugs are fixed, but not always. Bug fixing does not
apply to released software only, it is also for projects under development.
Question: How will you ensure that your program or code is without any errors?
7-10 Introduction to Web Development with Microsoft® Visual Studio® 2010
Debug Class
Key Points
The Debug class provides a set of methods and properties that can help debug
your code by printing debug information and checking your code with assertions.
Using the Debug class, you can ensure that your code is robust, without affecting
the performance and the code size of your released product. This is because when
compiling in Release mode, the calls to methods and properties of the Debug class
are not compiled in the assembly at compile time. The Debug class is globally
available to your application when you import the System.Diagnostics namespace.
So, you do not have to create an instance of it. You cannot create an instance of the
Debug class, because it has no constructors, and you cannot inherit the class
because it is sealed.
Troubleshooting Microsoft® ASP.NET Web Applications 7-11
Method Description
Note: A listener produces formatted output when debugging and tracing. The Listeners
collection contain listeners monitors the debug and trace output.
7-12 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
While ensuring that your application follows the required path of execution or
performs the necessary actions, you can view diagnostic information about page
requests by enabling the tracing feature for your page or application. Using the
Debug and TraceContext classes, you can collect and display diagnostic
information at runtime:
• The Debug class. You can use the Debug class to output debug information.
Statements that use the Debug class run only when you compile the
application using the debug mode, and when the Web application is run in the
debugger. If you create a release build, the statements will not be included in
the compiled assembly.
With the Debug class, messages are sent as output to the current collection of
trace listeners, which, by default, displays the output in the Debug pane of the
Output window in Visual Studio 2010. A listener produces formatted output
from the debug output.
Troubleshooting Microsoft® ASP.NET Web Applications 7-13
When you use the Debug class to print debug information and check your
logic, you can make your code more stable without affecting the performance
of the final product or the code size.
• The TraceContext class. The TraceContext class enables you to display
information on a Web page, or to the trace log in memory. It is used to capture
and present execution details about a Web request. In a Web Form, the
TraceContext class is accessible by using the Trace property of the Page class.
You need to remember that the Trace property is different from the Trace
class in the System.Diagnostics namespace.
Note: To use the Debug class, you must import the System.Diagnostics namespace in
your code file, or prefix the class method call with the namespace.
Question: What are the two default configurations in Visual Studio 2010?
7-14 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
To print any debug information, you can use a number of methods, including the
Write and WriteLine methods.
• Write. Writes a text string to the trace listeners. There are four overloads of
this method—two that write a single line of text, and two others that write a
single line of text and the category name. The category name can be used to
group the output messages.
• WriteLine. Writes a text string to the trace listeners, and adds a new line
character at the end of the text, so that any new text following your call will
be written on the next line. There are four overloads of this method—two that
write a single line of text, and two others that write a single line of text and the
category name. You can use the category name to group the output messages.
Troubleshooting Microsoft® ASP.NET Web Applications 7-15
The following code examples show how you can use the Write and WriteLine
methods.
[Visual Basic]
Debug.Write("Writing a string of text...")
Debug.WriteLine("Writing a line of text...")
Debug.Write("Writing a string of text...", "Category 1")
Debug.WriteLine("Writing a line of text...", "Category 2")
[Visual C#]
Debug.Write("Writing a string of text...");
Debug.WriteLine("Writing a line of text...");
Debug.Write("Writing a string of text...", "Category 1");
Debug.WriteLine("Writing a line of text...", "Category 2");
To conditionally print any debug information, you can use two other methods: the
WriteIf method, and the WriteLineIf method.
• WriteIf. Conditionally writes a text string to the trace listeners. There are four
overloads of this method—two that write a single line of text, and two that
write a single line of text and the category name that can be used to group the
output messages.
• WriteLineIf. Conditionally writes a text string to the trace listeners, and adds a
new line character at the end of the text, so that any new text following your
call will be written on the next line. There are four overloads of this method:
two that write a single line of text, and two that write a single line of text and
the category name. You can use the category name to group the output
messages. The following code examples show how to use the WriteIf and
WriteLineIf method.
[Visual Basic]
Debug.WriteIf(Page.IsPostBack, "Writing a string of text...")
Debug.WriteLineIf(Page.IsPostBack, "Writing a line of text...")
[Visual C#]
Debug.WriteIf(Page.IsPostBack, "Writing a string of text...");
Debug.WriteLineIf(Page.IsPostBack, "Writing a line of text...");
7-16 Introduction to Web Development with Microsoft® Visual Studio® 2010
To format any debug information when printing, you can use the Print method,
which uses the String.Format method to convert the value of an object to its text
representation, and then embed that representation in a string.
The Print method writes a formatted line of text to the trace listeners. There are
two overloads of this method, as shown in the following code examples.
[Visual Basic]
Debug.Print("Printing a line of text...")
Debug.Print("Printing a line a text, Postback = {0}", Page.IsPostBack)
[Visual C#]
Debug.Print("Printing a line of text...");
Debug.Print("Printing a line a text, Postback = {0}",
Page.IsPostBack);
If you need to display either a message or the call stack if a specific condition is
false, you can use the Debug.Assert method to check for the condition. The
method has four overloads, as shown in the following code examples.
[Visual Basic]
Debug.Assert(Page.IsPostBack)
Debug.Assert(Page.IsPostBack, "Brief Message")
Debug.Assert(Page.IsPostBack, "Brief Message", "Detail description
message")
Debug.Assert(Page.IsPostBack, "Brief Message", "Detail description
message", objectArrayToFormat)
[Visual C#]
Debug.Assert(Page.IsPostBack)
Debug.Assert(Page.IsPostBack, "Brief Message")
Debug.Assert(Page.IsPostBack, "Brief Message", "Detail description
message");
Debug.Assert(Page.IsPostBack, "Brief Message", "Detail description
message", objectArrayToFormat);
Troubleshooting Microsoft® ASP.NET Web Applications 7-17
A dialog box displays whether you run the application with or without debugging,
and whether you compile the application in debug or release mode. The dialog
box generates with the method overload, which takes three parameters: condition,
message, and description. The first overload shown above takes only a condition
parameter, and shows only the call stack. The next overload shows only the
message and the call stack. The call stack shows you the names of the functions on
the call stack, the parameter types, and the parameter values, at a given point in
time.
7-18 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
If one of your Web pages contains an error, you can use debugging to identify the
source of the problem. When you want to debug a Web application, you first need
to enable debugging, and then decide if you need to generate an output of debug
information while your Web application is running. In addition, you need to
decide if you want to add breakpoints in your code, where you want execution to
pause, and finally, you need to run the Web application in the debug mode. If you
have added any breakpoints, you can step through the code when a breakpoint is
hit.
[Visual Basic]
<configuration>
<system.web>
<compilation debug="true" strict="false" explicit="true">
...
</system.web>
<configuration>
[Visual C#]
<configuration>
<system.web>
<compilation debug="true">
...
</system.web>
<configuration>
Question: How will you examine a variable or a value of the variable during a
debugging session?
Troubleshooting Microsoft® ASP.NET Web Applications 7-21
Remote Debugging
Key Points
Remote debugging is the process of debugging Web applications that are running
on a separate server. Remote debugging enables you to debug Web applications
on numerous disparate servers, from a single workstation. You may want to use
remote debugging if you cannot run your Web application locally, or if you want to
test the application while it is deployed on a Web server.
Before you start remote debugging, you must configure the environments on both
the debugger host and the remote computer. You must also consider security
features. For example, the remote server must grant access to the user who
performs the debugging.
Lesson 2
Tracing in ASP.NET
Lesson Objectives
After completing this lesson, you will be able to:
• Describe tracing.
• Describe the TraceContext class.
• Perform tracing in a Web application.
Troubleshooting Microsoft® ASP.NET Web Applications 7-25
What Is Tracing?
Key Points
Tracing is the process of receiving informative messages about the execution of a
Web application at runtime. If one of your Web pages contains an error and you
want to analyze the error, or if you want to follow the path of execution and view
how much time was spent in the various methods, you can use tracing. To trace a
Web application, you first need to enable tracing, and then you need to decide if
you need to get an output of the trace information while your Web application is
running. You also need to decide if you want to use page-level tracing, or
application-level tracing.
ASP.NET Trace
ASP.NET introduces a function called tracing, which allows you to view diagnostic
information about a single request for an ASP.NET page simply by enabling it for
your page or application. Tracing also allows you to write debug statements
directly in your code without having to remove them from your application when
you deploy it to production servers. You can write variables or structures in a page,
assert whether a condition is met, or simply trace through the execution path of
your page or application.
7-26 Introduction to Web Development with Microsoft® Visual Studio® 2010
In order for these messages and other tracing information to be gathered and
displayed, you must enable tracing for the page or application. When you enable
tracing, two events occur:
• ASP.NET appends a series of diagnostic information tables immediately
following the page's output. The information is also sent to a trace viewer
application, if you have enabled tracing for the application.
• ASP.NET displays your custom diagnostic messages in the Trace Information
table of the appended performance data.
TraceContext Class
Key Points
You can use the TraceContext class to write trace messages on a page, or to the
trace log in memory. You implement the trace log by using the TraceRecords
messages collection, which is a collection of trace records that are associated with
the current request. Because the TraceContext class is readily available when
working in an ASP.NET Web Form through the Trace property of the Page class,
you do not need to create an instance of it. In fact, the TraceContext class is of
type System.Web.HttpContext, which encapsulates all HTTP-specific information
about a Hypertext Transfer Protocol (HTTP) request. Therefore, you should never
create an instance of this class, because the constructor supports the .NET
Framework infrastructure; it is not intended to be used directly from your code.
Also, the TraceContext class cannot be inherited, because it is sealed.
7-28 Introduction to Web Development with Microsoft® Visual Studio® 2010
To write information to the trace log, you can use any of the following methods of
the TraceContext class:
• Write. Writes a trace message to the trace log. There are three overloads of the
Write method, all of which write a trace message to the trace log. The second
overload specifies the category name that indicates the category that will
receive the trace message. The third overload takes a third parameter, of type
Exception, which indicates that you can supply a caught or user-defined
exception.
• Warn. The Warn method is similar to the Write method. However, unlike the
Write method, all warnings appear in the log as red text.
The following code examples show how you can write trace messages.
[Visual Basic]
Trace.Write("Trace Message")
Trace.Write("Category 1", "Trace Message")
Trace.Write("Category 2", "Trace Message", New Exception("En Exception
was thrown, because..."))
[Visual C#]
Trace.Write("Trace Message");
Trace.Write("Category 1", "Trace Message");
Trace.Write("Category 2", "Trace Message", new Exception("En Exception
was thrown, because..."));
If you enable tracing, the output will be appended to the page in which the code
has been executed.
On the trace information page, the category parameter enables you to classify and
group trace messages. For example, you can set the sort order of trace messages to
display messages of the same category together. The TraceMode attribute can be
used to specify the order in which you want your trace messages to appear.
Set TraceMode to SortByTime, to sort trace messages in the order in which they
are processed.
Troubleshooting Microsoft® ASP.NET Web Applications 7-29
The following code shows how you can set TraceMode to SortByCategory, to sort
trace messages by the categories that you specified in the Warn and Write method
calls.
You can use the IsEnabled property of the TraceContext class to dynamically
change the state of tracing in a page.
TraceContext.IsEnabled Statement
TraceContext class has a Boolean property named IsEnabled, which enables you
to call the Write and Warn methods only when tracing is enabled. The following
code examples illustrate how to use the Trace.IsEnabled statement.
[Visual Basic]
If Trace.IsEnabled Then
Trace.Write("Tracing is enabled!")
End If
[Visual C#]
if (Trace.IsEnabled)
{
Trace.Write("Tracing is enabled!");
}
You can also use the IsEnabled property to dynamically change the state of tracing
for a page. The following code examples illustrate this.
[Visual Basic]
Trace.IsEnabled = False
[Visual C#]
Trace.IsEnabled = false;
7-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
The following screen shot displays the trace information for a page in a Web
application:
You can use the TraceContext class to append messages to specific trace
categories, and to obtain a set of trace records at the end of request execution for
custom processing.
Troubleshooting Microsoft® ASP.NET Web Applications 7-31
Key Points
You can enable tracing at the page-level or at the application-level. To enable page-
level tracing, you must set the Trace attribute of the Page directive to true for the
Web Form.
[Visual Basic]
<%@ Page Language="VB" Trace="true" %>
[Visual C#]
<%@ Page Language="C#" Trace="true" %>
When you use page-level tracing, all trace messages append to the end of the Web
page, which enables you to quickly view the trace messages when you view the
Web page.
7-32 Introduction to Web Development with Microsoft® Visual Studio® 2010
To enable application-level tracing, you need to configure the web.config file for
the Web application, and add the trace element. The following code shows how
you can enable application-level tracing.
<configuration>
...
<system.web>
<trace enabled="true" />
...
</system.web>
</configuration>
If you need to view the trace information when your application is running, you
can use the methods of the TraceContext class.
When you enable application-level tracing, you enable tracing for all the pages in
the Web application. Application-level tracing also gives you flexibility when you
write trace statements. For example, with page-level tracing, all trace messages are
appended to the page. However, with application-level tracing, you can write trace
messages to the page, or to memory. Trace statements that you save to memory are
accessible by the application-level trace viewer trace.axd. To view the application-
level trace viewer, type the URL for your application, and add trace.axd to the
URL—for example, http://www.contoso.com/trace.axd.
When a page in your Web application is requested, the page gathers trace
information, and then runs any trace statements that it contains. You can view the
trace output in the trace viewer. The trace viewer lists the requests in the order in
which they were processed, and you can choose a specific request from any of the
application pages that have been requested.
Trace Results
Page-level trace results are appended to the end of the .aspx page for which they
are enabled. The trace results contains lot of information, along with the custom
messages that you created by using the Trace.Write and Trace.Warn statements.
Troubleshooting Microsoft® ASP.NET Web Applications 7-33
Trace Categories
Trace results contain several categories of information. The following table lists
each category, and provides the description about the type of information it
contains.
Category Description
Control Tree Lists of all of the items that are on the page, along with the
size of each item.
Presents an HTML representation of the ASP.NET Control
Tree. Shows each control’s unique ID, runtime type, the
number of bytes it took to be rendered, and the bytes it
requires in ViewState and ControlState. The three columns
showing the weight of each control indicates the number of
bytes occupied in ViewState or ControlState by that
particular control. You must be aware of the number of
bytes used by each of your controls, especially if you write
your custom controls. You want your controls to return as
few bytes as possible to keep the overall page weight down.
Cookies Collection Displays a list of cookies that are in use for the request and
response.
7-34 Introduction to Web Development with Microsoft® Visual Studio® 2010
(continued)
Category Description
Form Collection Displays a list of controls, and their values on the form that is
posted.
Server Variables List of all the server variables and their values.
The following screen shot displays the requests in the trace viewer:
Note: You can perform tasks in this lab by using either the Visual Basic or Visual C#
programming language. If you are using Visual Basic as your programming language,
refer to the steps provided in the Section 1 of the lab page. If you are using Visual C# as
your programming language, refer to the steps provided in Section 2 of the lab page.
Introduction
In this lab, you will debug an ASP.NET Web application for runtime errors by
adding breakpoints and watches. In addition, you will implement tracing in the
Web application to view information such as Session state, Application state, and
server variables.
Troubleshooting Microsoft® ASP.NET Web Applications 7-37
Objectives
After completing this lab, you will be able to:
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the 10267A-GEN-DEV virtual machine, and then log on by using the
following credentials:
• User name: Student
• Password: Pa$$w0rd
7-38 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses a Web site to manage its customer
information. To maintain correct user information, you need to debug the
customer management Web application for logical issues in its functionality.
You need to debug the application by adding appropriate output statements,
breakpoints, and watches. You also need to enable tracing by using the web.config
file to identify possible errors in the code after the application’s deployment. The
version of the Web application that was finished in the previous module has
been deployed to a staging server where debugging is not possible. However,
there seems to be a performance issue when loading or rendering the
InsertCustomer.aspx Web Form. You are not allowed to append trace information
to each page, so you must therefore enable application-level tracing, and then test
that you can view the timings for the InsertCustomer.aspx Web Form.
Troubleshooting Microsoft® ASP.NET Web Applications 7-39
Imports System.Diagnostics
7-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
• In the Page_Load event handler, send the message, “Page Postback detected in
Page_Load” to the trace listeners, when the page is loaded in response to a
postback.
• In the Page_Load event handler, send the message, “No Page Postback
detected in Page_Load” to the trace listeners, when the page is not loaded in
response to a postback.
• At the end of the Page_Unload event handler, send the message, “Page has
been unloaded” to the trace listeners.
• At the end of the Click event of the CustomerInsertButton control, send the
message, “Customer has been inserted in CustomerInsertButton_Click” to the
trace listeners.
• At the end of the private populateUI method, send the message, “UI controls
have been populated” to the trace listeners.
• Click the Smart Tag button, and then click Edit Items.
• In the ListItem Collection Editor dialog box, click Add.
• In the ListItem properties pane, in the Text box, type USA, and then click
OK.
• Save and close the user control file.
• Run the Web application in the debug mode.
• Verify the output for the Page_Load, Page_Unload, and
instantiateCustomerObject methods, by creating a new customer and
viewing the Output pane of the Debugger variable windows.
Note: In the Debug pane of the Output window, notice that the output of the Debug
statements displays. You may have to scroll up to see the statements.
• Verify the output for the Click event handler of the CustomerInsertButton
control, by creating a new customer, using the following information, and then
clicking the Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
• Close Windows Internet Explorer®.
Note: In the Debug pane of the Output window, notice that the Customer has been
inserted in CustomerInsertButton_Click message is displayed.
7-42 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: Notice that the value for the Credit Limit box is set to 0 by default.
Note: Notice that the value for the Credit Limit box is set to 50, which is incorrect.
instantiateCustomerObject();
• Create a new customer, by using the following information, and then click the
Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
Note: In the Watch1 window, notice that the value for the
CustomerCreditLimitTextBox is changed to 50.
Note: Notice that the value of 50 for the CreditLimit property is not assigned here.
• Re-run the Web application in debug mode to examine the Customer class.
• Create a new customer, and ignore the first breakpoint, by continuing program
execution.
7-44 Introduction to Web Development with Microsoft® Visual Studio® 2010
• Create a new customer, by using the following information, and then click the
Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
• Step into the instantiateCustomerObject method.
• Step over the first line of code, and then the check for postback.
• Step into the method that instantiates the customer object.
Note: Stepping into the instantiation of the customer object action may take some time.
• Step over each single line of code in the Customer.vb code window, until the
following line of code in the constructor that initializes the CreditLimit
property is reached.
Me.CreditLimit = creditLimit
• Step through the assignment of the passed value to the CreditLimit property.
• Locate the step that adds the extra 50 to the private customerCreditLimit
member Credit Limit box.
Me.customerCreditLimit = value + 50
• View the functions and procedure calls that are currently on the stack, by
viewing the Call Stack window.
• Stop debugging the Web project.
• Remove the extra value from the customerCreditLimit property.
Me.customerCreditLimit = value
Note: Notice that the value for the Credit Limit box is still 0.
Results: After completing this exercise, you will have enabled debugging for the
CustomerManagement Web project, added debug output statements to the user
control, and fixed a bug in the CustomerManagement Web application functionality.
7-46 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: Scroll down to see all of the information output, including the control tree, session
and application state, form and querystring collection, and server variables of the
InsertCustomer.aspx Web page. Verify that you can see the Trace Information section,
which gives you information about how much time is spent when loading, rendering, and
unloading the Web Form.
f Task 3: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Results: After completing this exercise, you will have enabled and implemented
application-level tracing for the CustomerManagement Web application.
7-48 Introduction to Web Development with Microsoft® Visual Studio® 2010
Section 2: Visual C#
Exercise 1: Debugging a Web Application
The main tasks for this exercise are as follows:
using System.Diagnostics;
Troubleshooting Microsoft® ASP.NET Web Applications 7-49
• In the Page_Load event handler, send the message, “Page Postback detected in
Page_Load” to the trace listeners, when the page is loaded in response to a
postback.
• In the Page_Load event handler, send the message, “No Page Postback
detected in Page_Load” to the trace listeners, when the page is not loaded in
response to a postback.
• At the end of the Page_Unload event handler, send the message, “Page has
been unloaded” to the trace listeners.
• At the end of the Click event of the CustomerInsertButton control, send the
message, “Customer has been inserted in CustomerInsertButton_Click” to the
trace listeners.
• At the end of the private populateUI method, send the message, “UI controls
have been populated” to the trace listeners.
Note: In the Debug pane of the Output window, notice that the output of the Debug
statements display. You may have to scroll up to see the statements.
• Verify the output for the Click event handler of the CustomerInsertButton
control, by creating a new customer using the following information, and then
Click the Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
• Close Windows Internet Explorer®.
Note: In the Debug pane of the Output window, notice that the Customer has been
inserted in CustomerInsertButton_Click message is displayed.
Troubleshooting Microsoft® ASP.NET Web Applications 7-51
Note: Notice that the value for the Credit Limit box is set to 0 by default.
Note: Notice that the value for the Credit Limit box is set to 50, which is incorrect.
instantiateCustomerObject();
• Create a new customer, by using the following information, and then click the
Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
Note: In the Watch1 window, notice that the value for the
CustomerCreditLimitTextBox is changed to 50.
Note: Notice that the value of 50 for the CreditLimit property is not assigned here.
• Re-run the Web application in debug mode to examine the Customer class.
Troubleshooting Microsoft® ASP.NET Web Applications 7-53
• Create a new customer, and ignore the first breakpoint, by continuing program
execution.Create a new customer, by using the following information, and
then click the Insert button:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
• Step into the instantiateCustomerObject method.
• Step over the first line of code and then the check for postback.
• Step into the method that instantiates the customer object.
Note: Stepping into the instantiation of the customer object action may take some time.
• Step over each single line of code in the Customer.cs code window, until the
following line of code in the constructor that initializes the CreditLimit
property is reached.
this.CreditLimit = creditLimit;
• Step through the assignment of the passed value to the CreditLimit property.
• Locate the step that adds the extra 50 to the private customerCreditLimit
member Credit Limit box.
• View the functions and procedure calls that are currently on the stack, by
viewing the Call Stack window.
• Stop debugging the Web project.
• Remove the extra value from the customerCreditLimit property.
this.customerCreditLimit = value;
7-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
Note: Notice that the value for the Credit Limit box is still 0.
Results: After completing this exercise, you will have enabled debugging for the
CustomerManagement Web project, added debug output statements to the user
control, and fixed a bug in the CustomerManagement Web application functionality.
Troubleshooting Microsoft® ASP.NET Web Applications 7-55
Note: Scroll down to see all of the information output, including the control tree, session
and application state, form and querystring collection, and server variables of the
InsertCustomer.aspx Web page. Verify that you can see the Trace Information section,
which gives you information about how much time is spent when loading, rendering, and
unloading the Web Form.
Results: After completing this exercise, you will have enabled and implemented
application-level tracing for the CustomerManagement Web application.
f Task 3: Turn off the virtual machine and revert the changes
After you complete the lab, you must turn off the 10267A-GEN-DEV virtual
machine and revert the changes.
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Troubleshooting Microsoft® ASP.NET Web Applications 7-57
Lab Review
Best Practices
Mention some best practices in the context of your own business situations.
• Messages written to the trace listeners that should not be included in a release
version of your application should always be written by using the Debug
object.
• Always disable tracing in a Web application before deployment to a
production server.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-1
Module 8
Managing Data in a Microsoft® ASP.NET 4.0
Web Application
Contents:
Lesson 1: Overview of ADO.NET 8-3
Lesson 2: Connecting to a Database 8-16
Lesson 3: Managing Data 8-29
Lab: Managing Data in an ASP.NET 4.0 Web Application 8-48
8-2 Introduction to Web Development with Microsoft® Visual Studio® 2010
Module Overview
Microsoft® ADO.NET is the technology that you can use to connect Microsoft .NET
Framework–based applications to data sources such as Microsoft SQL Server®
databases and XML files. ADO.NET is designed to work in disconnected
environments such as the Internet, and it provides a flexible and simple way for
you to integrate data access and data manipulation into your Web applications.
Considering the reach of the Internet as the means of data communication, a data
technology such as ADO.NET makes data accessible and updatable in a
disconnected architecture.
This module explains what ADO.NET is, and how you can incorporate ADO.NET
into a Microsoft ASP.NET Web application by using the tools that are built into
Microsoft Visual Studio® 2010.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-3
Lesson 1
Overview of ADO.NET
Lesson Objectives
After completing this lesson, you will be able to:
• Describe ADO.NET.
• Describe the ADO.NET object model.
• Describe the ADO.NET Entity Framework.
8-4 Introduction to Web Development with Microsoft® Visual Studio® 2010
What Is ADO.NET?
Key Points
ADO.NET is a part of the .NET Framework base class library, and is a set of
components that you can use to access and manipulate data. Even though
ADO.NET can be used to access data in non-relational data sources, its primary use
is to access and manage data that is stored in relational database systems, such as
SQL Server 2008.
ADO.NET
ADO.NET is specifically designed for data-related connections in a disconnected
environment. Therefore, ADO.NET is a good choice for Internet-based Web
applications. ADO.NET uses XML as the format for data transmission between the
database and your Web application.
ADO.NET consists of two layers—a disconnected layer, and a connected layer.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-5
Disconnected Layer
The disconnected layer consists of a number of classes for storing data and
relations. The DataSet class is the main class that represents an in-memory cache
of data. The DataSet contains a collection of one or more DataTable objects that
consist of rows and columns of data, and the primary key, foreign key, constraint,
and relation information about the data in the DataTable objects. You can think of
the DataSet class as an in-memory representation of a database.
Connected Layer
The connected layer manages the traffic of data to and from the data source, and is
specific to a data source, such as SQL Server or an XML file. The connected layer is
also known as the data provider. ADO.NET ships with a number of ready-to-use
data providers, including:
• SQL Server .NET Framework Data Provider, for accessing SQL Server 7.0 and
newer databases.
• OLE DB .NET Framework Data Provider, for accessing any OLE DB data
source for which you have an OLE DB provider.
• ODBC .NET Framework Data Provider, for accessing any ODBC data source
for which you have an ODBC driver.
A number of third-party vendors, including IBM and Oracle, have created .NET
Framework Data Provider implementations. Most data sources from major vendors
facilitate data access by using ADO.NET.
Key Points
The ADO.NET object model provides an infrastructure that you can use to access
data from different data sources. There are two layers of the ADO.NET object
model: the disconnected layer, which is usually made up of the DataSet class and
related classes, and the connected layer, also known as the data provider.
Disconnected Layer
The disconnected layer includes the DataTable, DataRow, DataColumn,
Constraint, DataRelation, and DataView classes. The disconnected layer is
independent of a data source, and can be used to manage in-memory data. As a
result, it can be used with multiple data sources or XML data, or to manage data
that is local to the application. Optionally, you can connect the disconnected layer
to a data source by using the connected layer.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-7
The disconnected layer consists of common types for storing data and relations,
which are found within the System.Data namespace. The following table lists these
common types.
Type Description
Connected Layer
The ADO.NET connected layer provides the link between the data source and the
disconnected layer, which is either a DataSet and/or a DataTable object. The
common base types are found within the System.Data.Common namespace.
The connected layer includes classes such as the DataAdapter, Connection,
Command, and DataReader classes. The .NET Framework Data Providers are
designed for data manipulation, and for fast, forward-only, read-only access to data.
• The Connection object provides connectivity to a data source.
• The Command object enables access to database commands, which can be
used to return data, modify data, run stored procedures, and send or retrieve
parameter information.
• The DataReader class provides a high-performance stream of data from the
data source.
• The DataAdapter class provides the bridge between the DataSet object and
the data source. The DataAdapter class uses Command objects to run SQL
commands at the data source, to both load the DataSet object with data, and
reconcile the changes that were made to the data in the DataSet object, back to
the data source.
The following table lists the common base types provided by the connected layer.
The types listed in the previous table are all abstract base types that must be
inherited. Therefore, you need to use the following types for specific data source
implementation:
• With the SQL Server .NET Framework Data Provider, use the SqlDataAdapter,
SqlDataReader, SqlCommand, and SqlConnection classes, which are all
found in the System.Data.SqlClient namespace.
• With the OLE DB .NET Framework Data Provider, use the
OleDbDataAdapter, OleDbDataReader, OleDbCommand, and
OleDbConnection classes, which are all found in the System.Data.OleDb
namespace.
• With the ODBC .NET Framework Data Provider, use the OdbcDataAdapter,
OdbcDataReader, OdbcCommand, and OdbcConnection classes, which are
all found in the System.Data.Odbc namespace.
• With the Oracle .NET Data Provider, use the OracleDataAdapter,
OracleDataReader, OracleCommand, and OracleConnection classes, which
are all found in the System.Data.OracleClient namespace. You can use the
Oracle .NET Data Provider if you want to connect to an Oracle database
version 8.1.7 or newer.
Note: You cannot mix and match the types from the connected layer. All the types used
for managing data with a single data source must come from the same .NET Data
Provider.
Key Points
The Entity Framework is a set of technologies in ADO.NET that support
development of data-oriented software applications, and it is part of the Microsoft
data platform.
Architects and developers of data-oriented applications have struggled with
the need to achieve two very different objectives: they must model the entities,
relationships, and logic of the business problems they are solving, and they
must also work with the data engines that are used to store and retrieve the data.
The data may span multiple storage systems, each with its own protocols; even
applications that work with a single storage system must balance the requirements
of the storage system against the requirements of writing efficient and maintainable
application code.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-11
The Entity Framework enables you to work with data in the form of domain-
specific objects and properties—such as customers and customer addresses—
without having to be concerned with the underlying database tables and columns
where this data is stored. This is enabled by elevating the level of abstraction at
which you can work when working with data, and by reducing the code that is
required to create and maintain data-oriented applications. Because the Entity
Framework is a component of the .NET Framework, Entity Framework
applications can run on any computer on which the .NET Framework 4 is
installed.
Conceptual Models
A longstanding and common design pattern for data modeling is the division of
the data model into three parts: a conceptual model, a logical model, and a
physical model. The conceptual model defines the entities and relationships in the
system that is being modeled. The logical model for a relational database normalizes
the entities and relationships into tables with foreign key constraints. The physical
model addresses the capabilities of a particular data engine by specifying storage
details, such as partitioning and indexing.
The physical model is refined by database administrators to improve
performance, but programmers writing application code primarily confine
themselves to working with the logical model by writing SQL queries and
calling stored procedures. You can use conceptual models as a tool for capturing
and communicating the requirements of an application, and frequently these
conceptual models are used as inert diagrams that are viewed and discussed in
the early stages of a project, and then abandoned. Many development teams skip
creating a conceptual model and begin by specifying tables, columns, and keys in a
relational database.
The Entity Framework gives life to conceptual models by enabling you to query
entities and relationships in the conceptual model while relying on the Entity
Framework to translate those operations to data source-specific commands. This
frees applications from hard-coded dependencies on a particular data source. The
conceptual model, the storage model, and the mapping between the two are
expressed in an external specification, known as the Entity Data Model (EDM).The
storage model and mappings can change as needed, without requiring changes to
the conceptual model, data classes, or application code. Because storage models
are provider-specific, you can work with a consistent conceptual model across
various data sources.
8-12 Introduction to Web Development with Microsoft® Visual Studio® 2010
An EDM is defined by the following three model and mapping files that have
corresponding file name extensions:
• Conceptual schema definition language file (.csdl). Defines the conceptual
model.
• Store schema definition language file (.ssdl). Defines the storage model, which
is also called the logical model.
• Mapping specification language file (.msl). Defines the mapping between the
storage and conceptual models.
The Entity Framework uses these XML-based models and mapping files to
transform, create, read, update, and delete operations against entities and
relationships in the conceptual model to equivalent operations in the data source.
In addition, the EDM supports mapping entities in the conceptual model to stored
procedures in the data source.
The EDM tools generate extensible data classes that are based on the conceptual
model. These classes are partial classes that can be extended with additional
members that the developer adds. The classes that are generated for a particular
conceptual model derive from base classes that provide Object Services for
materializing entities as objects, and for tracking and saving changes. You can use
these classes to work with the entities and relationships as objects that are related
by navigation properties.
EntityDataSource Control
The EntityDataSource control supports data binding scenarios based on EDM.
The EDM specification represents data as sets of entities and relationships. The
Entity Framework uses EDM in object-relational mapping, and in other scenarios
such as ADO.NET Data Services. Users accustomed to the design-time model of
ASP.NET data-binding controls will find the programming surface of the
EntityDataSource control similar to that of other data source controls.
The EntityDataSource control manages the read, create, update, and delete
operations with a data source on behalf of data-bound controls on the page. The
EntityDataSource works with editable grids, forms with user-controlled sorting
and filtering, 2-way bound drop-down list controls, and master-detail pages. The
EntityDataSource control is able to obtain query parameter values from page
controls, query parameters appended to the page URI, cookies, and other ASP.NET
parameter objects.
EDM Tools
The EDM tools are designed to help you build Entity Framework applications.
With the EDM tools, you can create a conceptual model from an existing database,
and then graphically visualize and edit your conceptual model. Or, you can
graphically create a conceptual model first, and then generate a database that
supports your model. In either case, you can automatically update your model
when the underlying database changes and automatically generate object-layer
code for your application. Database generation and object-layer code generation
are customizable.
8-14 Introduction to Web Development with Microsoft® Visual Studio® 2010
Together with the Entity Framework runtime, the .NET Framework 4 includes the
EDM Generator. This command-line utility can connect to a data source by using a
data source–specific .NET Framework data provider, and generate the conceptual
model (.csdl), storage model (.ssdl), and mapping (.msl) files that are used by
the Entity Framework. The EDM Generator can validate an existing model, and
generate a Microsoft Visual Basic® or Microsoft Visual C#® code file that contains
the object classes generated from a conceptual model (.csdl) file. It can also
generate a Visual Basic or Visual C# code file that contains the pre-generated views
for an existing model.
Component Description
(continued)
Component Description
EntityClient A.NET Framework data provider that allows you to interact with
an EDM. EntityClient follows the .NET Framework data provider
pattern of exposing EntityConnection and EntityCommand
objects that return an EntityDataReader. EntityClient works
with the Entity SQL language, providing flexible mapping to
storage-specific data providers.
Lesson 2
Connecting to a Database
You can use ADO.NET to connect data in a data source (such as a database) to
objects and controls in your Web Forms. You can establish a connection to a
data source by using the Visual Studio 2010 integrated development environment
(IDE). You can also use the DataAdapter object and DataReader object to
establish data communication between the client and server. Some of the common
tasks you might perform programmatically by using ADO.NET are selecting,
inserting, updating, and deleting data.
This lesson explains how to programmatically work with data by using ADO.NET,
and how to create a connection to access the data that is stored in a SQL Server
database.
Lesson Objectives
After completing this lesson, you will be able to:
• Create a connection to a data source.
• Enable data transport between clients and servers.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-17
Creating a Connection
Key Points
You can use Visual Studio 2010 IDE to easily establish a connection to a data
source, and then verify the connection at design time. You can also create a
connection programmatically.
After you create a connection, Server Explorer displays the connection in Data
Connections. In Server Explorer, expand the connection, and then expand the
Tables folder to view the tables in the database connection.
The connection created by using Server Explorer is useful in scenarios where you
want to design new tables, or modify existing tables or stored procedures. You can
also use the connection created to drag table objects directly to a Web Form, in
which case a GridView control is added to the form with a data source control.
[Visual Basic]
Imports System.Data.SqlClient
[Visual C#]
using System.Data.SqlClient;
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-19
After importing the namespace, you can create your connection object as follows.
[Visual Basic]
Dim orderConnection As New SqlConnection()
[Visual C#]
SqlConnection orderConnection = new SqlConnection();
After you have created the connection object, you need to set the connection string.
The connection string directs the connection object to the server and database to
connect with, as the following code examples show.
[Visual Basic]
orderConnection.ConnectionString =
"Data Source=DatabaseServer;Initial
Catalog=OrderDatabase;Integrated Security=True"
[Visual C#]
orderConnection.ConnectionString =
"Data Source=DatabaseServer;Initial
Catalog=OrderDatabase;Integrated Security=True";
Notice how a data source or server, an initial catalog or database, and the
credentials used for accessing the database, have all been specified.
You can get these details by contacting your database administrator. If you are
connecting to a SQL Server, integrated security is often used as specified. However,
that is not always the case; therefore, you may have to specify the credentials by
using the User ID and Password attributes.
Tip: If you have created a connection to a database by using Server Explorer, you can
copy the connection string form there, and use it directly in code. Open Server Explorer,
and then click the data connection. Next, press the F4 key to open the Properties
window—if it is not already open—and select and copy the text from the Connection
String property. Finally, paste the copied text into your code.
8-20 Introduction to Web Development with Microsoft® Visual Studio® 2010
After the connection object is initialized and instantiated, it must be opened before
it can be used by the DataAdapter and/or DataReader classes, which is done as
follows.
[Visual Basic]
orderConnection.Open()
[Visual C#]
orderConnection.Open();
When you are done with your connection, you must close or dispose of it, as
follows.
[Visual Basic]
' Close connection
orderConnection.Close()
' Dispose of connection
orderConnection.Dispose()
[Visual C#]
// Close connection
orderConnection.Close();
// Dispose of connection
orderConnection.Dispose();
You need to close the connection or dispose of it, because both operations will
eventually dispose of both the unmanaged and managed resources. However, there
is no penalty in calling both methods, and it can make your code easier to read
from a maintenance point of view. Often, this is a matter of personal preference, or
is based on the coding conventions in your workplace.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-21
[Visual Basic]
Using orderConnection As New SqlConnection()
orderConnection.ConnectionString = _
"Data Source=DatabaseServer;Initial
Catalog=OrderDatabase;Integrated Security=True"
orderConnection.Open()
...
orderConnection.Close()
End Using
[Visual C#]
using (SqlConnection orderConnection = new SqlConnection())
{
orderConnection.ConnectionString =
"Data Source=DatabaseServer;Initial
Catalog=OrderDatabase;Integrated Security=True";
orderConnection.Open();
...
orderConnection.Close();
}
When you use the Using/using statement, it is not necessary to call the Close
method explicitly, as is done by the Dispose method, which is implicitly called
when you wrap the object instantiation in a Using/using statement. However, it
may help make your code easier to read.
Question: How can you change the data source type for a connection?
8-22 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
After you have created a connection to the database, you need an object to facilitate
the transport and synchronization of data between the client and the server. This is
where the DataAdapter object is helpful. However, if you only want to retrieve
data from the database and not manipulate it in any way, then the DataReader
object is your best choice.
DataAdapter
The DataAdapter object uses the Connection object to connect to a database, and
uses command objects to issue the commands for managing the data.
The DataAdapter object has four command object–related properties:
• SelectCommand. Issues an SQL SELECT statement for retrieving data from
the data source.
• UpdateCommand. Issues an SQL UPDATE statement for updating the data in
the data source whenever changes are made on the client.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-23
Of these four properties, only the SelectCommand must be set, but if you try to
update, insert, or delete data, an exception is thrown if the corresponding property
has not been set. Each of these properties can have SQL statements, or can be calls
to stored procedures in the database. You can use stored procedures to reduce the
amount of code that is required to perform SELECT, INSERT, UPDATE, and
DELETE operations. You also get an extra layer of security, because the actual SQL
code for performing the action is located on the server. Execute permission can be
limited to the stored procedures.
Note: The examples shown in the rest of this topic have been created with the lab
exercise application to show how you can create the DataAdapter object manually, so
that it fits into an overall concrete solution.
[Visual Basic]
' Declare and instantiate data adapter
Dim ordersDataAdapter As New SqlDataAdapter()
[Visual C#]
// Declare and instantiate data adapter
SqlDataAdapter ordersDataAdapter = new SqlDataAdapter();
8-24 Introduction to Web Development with Microsoft® Visual Studio® 2010
When you instantiate the data adapter, you can set the command properties as
follows.
[Visual Basic]
' Declare and instantiate command objects
Dim selectCommand As New SqlCommand("SELECT * FROM Orders",
orderConnection)
Dim deleteCommand As New SqlCommand("DELETE FROM Orders WHERE ID=@ID",
orderConnection)
Dim insertCommand As New SqlCommand("INSERT INTO Orders (CustomerID,
InvoiceDate, CreatedDate, CreatedBy) VALUES(@CustomerID, @InvoiceDate,
@CreatedDate, @CreatedBy)", orderConnection)
Dim updateCommand As New SqlCommand("UPDATE Orders SET
CustomerID=@CustomerID, InvoiceDate=@InvoiceDate,
"ModifiedDate=@ModifiedDate, ModifiedBy=@ModifiedBy WHERE ID=@ID",
orderConnection)
[Visual C#]
// Declare and instantiate command objects
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Orders",
orderConnection);
SqlCommand deleteCommand = new SqlCommand("DELETE FROM Orders WHERE
ID=@ID", orderConnection);
SqlCommand insertCommand = new SqlCommand("INSERT INTO Orders
(CustomerID, InvoiceDate, CreatedDate, CreatedBy) VALUES(@CustomerID,
@InvoiceDate, @CreatedDate, @CreatedBy)", orderConnection);
SqlCommand updateCommand = new SqlCommand("UPDATE Orders SET
CustomerID=@CustomerID, InvoiceDate=@InvoiceDate,
"ModifiedDate=@ModifiedDate, ModifiedBy=@ModifiedBy WHERE ID=@ID",
orderConnection);
When setting the command properties of the data adapter object, if you create the
Command object in a separate step and then assign it to the command properties,
you make your code more readable. Using this method, you can easily assign
parameters to Command objects where needed.
In the code, the selectCommand object uses the SQL SELECT statement to
retrieve all the rows from the Orders table. The deleteCommand object deletes
all the rows that contain a value of @ID in the ID column. The @ID part is also
known as a named parameter, and it can be assigned a value at a later stage. At this
stage, you have declared and instantiated the Command object.
Note: The ID column in the Orders table is unique, so when a value is assigned to the
@ID parameter, only one row with that value will be found.
The updateCommand object also makes use of the @ID parameter to identify
the correct row to update (WHERE ID=@ID). In addition, it assigns values to the
various columns by using named parameters (SET CustomerID=@CustomerID,
Invoicedate=@Invoicedate, ...). The insertCommand object performs the same
function as the updateCommand, although with a different syntax. You can assign
the parameter values as follows.
[Visual Basic]
' Declare and instantiate parameter objects
Dim deleteIDParameter As New SqlParameter("@ID",
SqlDbType.UniqueIdentifier, 0, "ID")
insertCommand.Parameters.Add(insertInvoiceDateParameter)
...
8-26 Introduction to Web Development with Microsoft® Visual Studio® 2010
[Visual C#]
// Declare and instantiate parameter objects
SqlParameter deleteIDParameter = new SqlParameter("@ID",
SqlDbType.UniqueIdentifier, 0, "ID");
updateCommand.Parameters.Add(updateIDParameter);
...
insertCommand.Parameters.Add(insertInvoiceDateParameter);
...
Note: The SqlDbType enumeration used to specify the data type for the various
parameters is part of the System.Data namespace; therefore, the System.Data
namespace must be imported to your code files.
When setting the parameter properties of the Command objects, if you create the
Parameter objects in a separate step and then add them to the command
parameters, you make your code more readable. Using this method, you can
specify the data type, the size, the parameter name, and the source column name.
Notice that some parameters are duplicated because they are assigned to more
than one Command object. You can assign a parameter object only to a single
Command object.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-27
[Visual Basic]
[Visual C#]
To read any row from the DataReader object, you need to call the Read method,
which returns a Boolean value indicating if the cursor is located at a valid row. If
the cursor is not located in a valid row, it indicates that there are no more rows in
the DataReader object. So, if you want to loop through the rows in a DataReader
object, calling the Read method is your only choice because the DataReader is a
forward-only construct. (Though you can close it and re-open it, it is an expensive
operation in terms of server resources.) Finally, ensure you call the Close method
on the DataReader object to allow the connection object to be reused for other
purposes.
The DataReader is actually used behind the scenes by the DataAdapter to retrieve
data and schema from the data source when populating a DataSet or DataTable.
Note: When you open a DataReader object, it will monopolize the connection
associated with the command object that is used for creating the DataReader object,
until you close the DataReader object. You cannot use the connection object—for
example, for a DataAdapter object—while it is being used by the DataReader object.
To retrieve data from a single database table without creating the various
command objects manually, you can use the CommandBuilder class.
Question: What are the four command-type properties of the DataAdapter object?
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-29
Lesson 3
Managing Data
When you have a connection to a data source and can transport data to and from
the server, you need a method to manage the data on the client. This might be for
the presentation of the data, or for allowing the users to manipulate the data. You
can achieve these tasks by using the types from the connected and disconnected
layers of ADO.NET.
The DataSet object provides a disconnected copy of all or some of the data in
the database. For long-running Web applications, you can use a DataSet object.
However, you often perform basic operations, such as displaying a single set of
data directly to the user, or accessing a password. For such operations, you do not
have to maintain a DataSet object. Instead, you can use a DataReader object.
This lesson explains how to use the DataSet and DataReader objects to support
the local data storage and data manipulation requirements of Web Forms.
8-30 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lesson Objectives
After completing this lesson, you will be able to:
• Retrieve simple data by using the DataReader class.
• Retrieve non-simple data by using the DataSet class and DataTable class.
• Manipulate data by using the DataAdapter object.
• Bind data to server controls by using the Visual Studio 2010 IDE.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-31
Key Points
When you need to retrieve a single value—such as a password or the number
of rows from the database—you can use the ExecuteScalar method of the
SqlCommand class. If you want to retrieve data from the database that will only be
displayed to the users, the DataReader class is a good choice as a container for the
retrieved data.
The following code examples create and open a connection, execute the command,
store the result in the ordersDataReader object, and then close the connection
after processing the results.
[Visual Basic]
' Declare and instantiate connection
Dim orderConnection As New SqlConnection()
' Initialize connection
orderConnection.ConnectionString = "..."
' Declare and instantiate command object
Dim selectCommand As New SqlCommand("SELECT * FROM Orders",
orderConnection)
[Visual C#]
// Declare and instantiate connection
SqlConnection orderConnection = new SqlConnection();
// Initialize connection
orderConnection.ConnectionString = "...";
// Declare and instantiate command objects
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Orders",
orderConnection);
// Open connection
orderConnection.Open();
// Close datareader
ordersDataReader.Close();
// Close connection
orderConnection.Close();
The HasRows property of the DataReader object verifies if any rows have been
returned. If no rows have been returned, you can inform the user or perform any
other appropriate action. If the HasRows property is true, the rows are looped
through by using the Read method, which advances to the next row, starting with
the first row the first time it is called. If the Read method returns false, there are no
more rows, and you can no longer access the data in the DataReader object. If you
do, an exception is thrown.
8-34 Introduction to Web Development with Microsoft® Visual Studio® 2010
If you need to retrieve just a single value instead of using the ExecuteReader
method, you can simply use the ExecuteScalar method. The following method
returns a single scalar value, such as the value returned by this SELECT statement.
If a single customer with the name “Weber” is found, a single entry with the name
“Weber,” is returned. However, if more than one customer with the name “Weber”
is found, then only the first entry found will be returned. The ID that is returned
depends on the manner in which the rows are sorted in the Orders table. If more
than a single field is returned by the SELECT statement—for example, an entire
row—then the ExecuteScalar method returns the first column of this row. The
ExecuteScalar method returns the value of type System.Object. Therefore, you
might need to cast the return value before you can use it. The following code
examples demonstrate the ExecuteScalar method.
[Visual Basic]
' Declare and instantiate command object
Dim selectCommand As New SqlCommand("SELECT ID FROM Orders WHERE
CreatedBy='Weber'", orderConnection)
[Visual C#]
// Declare and instantiate connection
SqlConnection orderConnection = new SqlConnection();
// Initialize connection
orderConnection.ConnectionString = "...";
// Declare and instantiate command objects
SqlCommand selectCommand = new SqlCommand("SELECT ID FROM Orders WHERE
CreatedBy='Weber'", orderConnection);
// Open connection
orderConnection.Open();
// Close connection
orderConnection.Close();
8-36 Introduction to Web Development with Microsoft® Visual Studio® 2010
Key Points
If you need to retrieve non-simple data—such as the content of an entire table or a
subset of rows from a table—the DataSet or DataTable classes are excellent choices
in a disconnected scenario.
You can enforce data integrity in a DataSet class by using constraints. You can use
the DataSet class to store local data—which you add manually—or you can import
XML documents. You can also use the DataSet class for storing a copy or cache of
the data—or a subset thereof—in a data source on a different server.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-37
[Visual Basic]
Dim ordersDataSet As New DataSet("OrdersDataSet")
[Visual C#]
DataSet ordersDataSet = new DataSet("OrdersDataSet");
[Visual Basic]
ordersDataAdapter.Fill(ordersDataSet, "Orders")
[Visual C#]
ordersDataAdapter.Fill(ordersDataSet, "Orders");
The Fill method runs the SQL statement that is contained in the Command object,
which is accessed by using the SelectCommand property of the DataAdapter
object.
You should always name the table that is being created and populated, preferably
with the name of the table in the database, because you can use this name when
accessing the data later.
The DataAdapter.Fill method uses the DataReader object implicitly to return the
column names and types that are used to create the tables in the DataSet, and the
data to populate the rows of the tables in the DataSet. Tables and columns are
only created if they do not already exist; otherwise Fill uses the existing DataSet
schema.
8-38 Introduction to Web Development with Microsoft® Visual Studio® 2010
Accessing a DataTable
After you have placed data in a DataSet object, you can programmatically access
the data. As the following code examples illustrate, each DataSet object consists of
one or more DataTable objects that you can refer to by name or by ordinal
position.
[Visual Basic]
' Access Orders table by name
ordersDataSet.Tables("Orders")
' Access Orders table by ordinal position
ordersDataSet.Tables(0)
[Visual C#]
// Access Orders table by name
ordersDataSet.Tables["Orders"];
// Access Orders table by ordinal position
ordersDataSet.Tables[0];
The following code examples retrieve the column names from the DataTable
object named Orders, which is contained in the ordersDataSet object.
[Visual Basic]
For Each col As DataColumn In ordersDataSet.Tables("Orders").Columns
Response.Write(col.ColumnName)
Next
[Visual C#]
foreach (DataColumn col in ordersDataSet.Tables["Orders"].Columns)
{
Response.Write(col.ColumnName);
};
[Visual Basic]
ordersDataSet.Tables("Orders").Rows.Count
ordersDataSet.Tables("Orders").Columns.Count
[Visual C#]
ordersDataSet.Tables["Orders"].Rows.Count;
ordersDataSet.Tables["Orders"].Columns.Count;
8-40 Introduction to Web Development with Microsoft® Visual Studio® 2010
Generally, you should not use the index to locate a row in the DataTable object,
because you cannot be sure that you are accessing the correct row. While the
column can be accessed because it is implied from the data source, the rows can be
sorted in different ways, or a row can be marked as deleted, making it difficult to
know exactly which row to access. You can loop through the rows, and when you
find the correct row, you can retrieve the values from the various columns. Another
option is to use the Find method of the DataRowCollection object that is exposed
by the Rows property, to locate one or more rows by using the primary key as
follows.
[Visual Basic]
' Apply the full schema from the data source
ordersDataAdapter.FillSchema(ordersDataSet, SchemaType.Source,
"Orders")
' Get the data row
Dim ordersDataRow As DataRow =
ordersDataSet.Tables("Orders").Rows.Find("a05c7f53-9c4e-de11-aa78-
0003ffa70544")
[Visual C#]
// Apply the full schema from the data source
ordersDataAdapter.FillSchema(ordersDataSet, SchemaType.Source,
"Orders");
// Get the data row
DataRow ordersDataRow =
ordersDataSet.Tables["Orders"].Rows.Find("a05c7f53-9c4e-de11-aa78-
0003ffa70544");
Notice how a call to the FillSchema method of the DataAdapter object is made
prior to calling the Find method of the DataRowCollection object. You need to
call the FillSchema method to apply the full schema to the Orders DataTable
object, because only the data type and name is applied when using the Fill method
of the DataAdapter object. If you want to apply a primary key, you must call the
FillSchema method first.
Question: How does the Fill method return the column names?
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-41
Manipulating Data
Key Points
If you need to manipulate the data in your database—either locally or directly on
the server—you can use the DataAdapter object. You can also access the database
commands and manipulate data by using the Command object.
[Visual Basic]
' Create new row locally
Dim newOrderDataRow As DataRow =
ordersDataSet.Tables("Orders").NewRow()
newOrderDataRow("ID") = Guid.NewGuid()
newOrderDataRow("CustomerID") = currentCustomer.ID
newOrderDataRow("InvoiceDate") = DateTime.Now
newOrderDataRow("CreatedDate") = DateTime.Now
newOrderDataRow("CreatedBy") = currentUser.Name
[Visual C#]
// Create new row locally
DataRow newOrderDataRow = ordersDataSet.Tables["Orders"].NewRow();
newOrderDataRow["ID"] = Guid.NewGuid();
newOrderDataRow["CustomerID"] = currentCustomer.ID;
newOrderDataRow["InvoiceDate"] = DateTime.Now;
newOrderDataRow["CreatedDate"] = DateTime.Now;
newOrderDataRow["CreatedBy"] = currentUser.Name;
If you want to modify the existing data locally, you can do so, as demonstrated in
the follow code examples.
[Visual Basic]
' Find row
Dim orderDataRow As DataRow = _
ordersDataSet.Tables("Orders").Rows.Find("a05c7f53-9c4e-de11-aa78-
0003ffa70544")
[Visual C#]
// Find row
DataRow orderDataRow =
ordersDataSet.Tables["Orders"].Rows.Find("a05c7f53-9c4e-de11-aa78-
0003ffa70544");
If you want to delete the existing data locally, you can do so, as demonstrated in
the following code examples.
[Visual Basic]
' Find row
Dim orderDataRow As DataRow = _
ordersDataSet.Tables("Orders").Rows.Find("20389eb1-f24f-de11-aa78-
0003ffa70544")
[Visual C#]
// Find row
DataRow orderDataRow =
ordersDataSet.Tables["Orders"].Rows.Find("20389eb1-f24f-de11-aa78-
0003ffa70544");
Note: The example code in this topic assumes that you have set up the Command
objects for the InsertCommand, UpdateCommand, and DeleteCommand properties
of the DataAdapter object.
After manipulating the data locally, you may need to send it to the server. The
following code examples illustrate this.
[Visual Basic]
' Update data source
ordersDataAdapter.Update(ordersDataSet, "Orders")
[Visual C#]
// Update data source
ordersDataAdapter.Update(ordersDataSet, "Orders");
Key Points
To effectively manage data, Visual Studio 2010 allows you to administratively
create a database connection, to and create a GridView server control on a Web
Form. You can then add a SqlDataSource object to the Web Form, and easily link
the GridView control to the database.
<configuration>
...
<appSettings/>
<connectionStrings>
<add name="OrderConnectionString1" connectionString="Data
Source=DatabaseServer;Initial Catalog=OrderDatabase;Integrated
Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
...
</configuration>
The DataSourceID property of the GridView control is also set to the name of the
SqlDataSource control. The following code shows how the DataSourceID
property is set to the SqlDataSource control.
At this stage, you can view the Web Form in a browser to display the data from the
data source.
The GridView control includes the following main properties, which can also be
set in the Properties window:
• AllowPaging. Enables paging in the control.
• AllowSorting. Enables sorting in the control.
• Columns. Displays the set of columns to be shown in the control.
• DataSourceID. Displays the control ID of a data source.
• PageSize. The number of rows from the data source to display per page.
You can set the properties in both the Properties window and the Design view.
You can use the SqlDataSource control to connect to a database with little or no
code. The SqlDataSource control is also the default when dragging a table from
Server Explorer onto a Web Form. However, you can use other server controls
also, including LinqDataSource.
The LinqDataSource control exposes LINQ to Web developers through the
ASP.NET data-source control architecture. LINQ provides a unified programming
model for querying and updating data from different types of data sources, and
extends data capabilities directly into the .NET Framework programming
languages, such as Visual Basic and Visual C#. LINQ simplifies the interaction
between object-oriented programming and relational data by applying the
principles of object-oriented programming to relational data.
Note: You can perform tasks in this lab either by using the Visual Basic or Visual C#
programming language. If you are using Visual Basic as your programming language,
refer to the steps provided in the Section 1 of the lab document. If you are using Visual
C# as your programming language, refer to the steps provided in Section 2 of the lab
document.
Introduction
In this lab, you will connect the ASP.NET Web application to a SQL Server
database by using the server control, and then bind the user control in the
application to a data source. In addition, you will modify the source database, and
verify the changes that are made to the database.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-49
Objectives
After completing this lab, you will be able to:
• Connect to a SQL Server database by using the SqlDataSource control.
• Bind a user control to the data source.
• Modify the source database, and verify the changes.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you
begin the lab, you must:
• Start the NYC-CL1 virtual machine, and then log on by using the following
credentials:
• User name: Student
• Password: Pa$$w0rd
8-50 Introduction to Web Development with Microsoft® Visual Studio® 2010
Lab Scenario
You are a developer at Contoso, Ltd, which is a large organization with a global
customer base. Your organization uses a Web site to manage its customer
information. You are responsible for managing the user information in your
organization. To perform this task, you need to add functionality for simple data
access tasks to retrieve data in a short time without using a lot of code. To
minimize the chances of creating error-prone code when accessing the data in the
database, you need to add and configure a data source control to the user control.
In addition, you need to add and bind a server control to the user control for
displaying specific data from the database.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-51
Note: Ensure that the returned rows include the values for the ID and Name columns for
various countries.
<asp:ListItem>USA</asp:ListItem>
DataSourceID="CountriesSqlDataSource"
DataValueField="ID"
DataTextField="Name"
Note: Notice the Build succeeded message in the Build pane of the Output window.
8-54 Introduction to Web Development with Microsoft® Visual Studio® 2010
ConfigurationManager.ConnectionStrings("CustomerManagementConnecti
onString").ConnectionString
customerManagementDataAdapter.FillSchema(customerManagementDataSet
, SchemaType.Source, "Customers")
customerManagementDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey
customerManagementDataAdapter.MissingMappingAction =
MissingMappingAction.Passthrough
' Populate Customers DataTable
customerManagementDataAdapter.Fill(customerManagementDataSet,
"Customers")
customerManagementDataSet.Tables("Customers").Rows.Add(newCustomer
DataRow)
f Task 8: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
8-62 Introduction to Web Development with Microsoft® Visual Studio® 2010
Section 2: Visual C#
Exercise 1: Connecting to a Data Source
The main tasks in this exercise are as follows:
1. Open an existing ASP.NET Web project.
2. Add a SQL Server 2008 Express Database.
3. Add a data source control to the user control.
4. Configure a data source control.
Note: Ensure that the returned rows include the values for the ID and Name columns for
various countries.
<asp:ListItem>USA</asp:ListItem>
DataSourceID="CountriesSqlDataSource"
DataValueField="ID"
DataTextField="Name"
ConfigurationManager.ConnectionStrings["CustomerManagementConnecti
onString"].ConnectionString;
// Open connection
customerManagementConnection.Open();
// Declare and instantiate data adapter
SqlDataAdapter customerManagementDataAdapter = new
SqlDataAdapter();
insertCommand.Parameters.Add(insertWebAddressParameter);
insertCommand.Parameters.Add(insertCreditLimitParameter);
insertCommand.Parameters.Add(insertNewsSubscriberParameter);
insertCommand.Parameters.Add(insertCreatedDateParameter);
insertCommand.Parameters.Add(insertCreatedByParameter);
customerManagementDataAdapter.FillSchema(customerManagementDataSet
, SchemaType.Source, "Customers");
customerManagementDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey;
customerManagementDataAdapter.MissingMappingAction =
MissingMappingAction.Passthrough;
// Populate Customers DataTable
customerManagementDataAdapter.Fill(customerManagementDataSet,
"Customers");
customerManagementDataSet.Tables["Customers"].Rows.Add(newCustomer
DataRow);
f Task 8: Turn off the virtual machine and revert the changes
• Turn off the 10267A-GEN-DEV virtual machine.
• Revert the changes made to the 10267A-GEN-DEV virtual machine.
Note: The answers to the exercises are on the Course Companion CD.
Lab Shutdown
After you complete the lab, you must turn off the 10267A-GEN-DEV virtual
machine and revert the changes.
1. In Microsoft Hyper-V™ Manager, in the Virtual Machines pane, right-click
10267A-GEN-DEV, and then click Turn Off.
2. In the Turn Off Machine dialog box, click Turn Off.
3. In Hyper-V Manager, in the Virtual Machines pane, right-click 10267A-GEN-
DEV, and then click Revert.
4. In the Revert Virtual Machine dialog box, click Revert.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-73
Lab Review
Best Practices
Mention some best practices in the context of your own business situations.
• Connection objects should always be explicitly disposed of.
• Use a DataTable object whenever you only need to work locally with the
content of a single database entity, instead of a DataSet object. It saves
resources.
• Whenever possible, place the connection string in the web.config file, making
it accessible to all of the Web application, and making it easy for an
administrator to change the file without recompiling code.