Download as pdf or txt
Download as pdf or txt
You are on page 1of 618

OFFICIAL MICROSOFT LEARNING PRODUCT

10267A
Introduction to Web
Development with Microsoft®
Visual Studio® 2010

Volume 1

Be sure to access the extended learning content on your


Course Companion CD enclosed on the back cover of the book.
ii Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

All other trademarks are property of their respective owners.

Product Number: 10267A

Part Number: X17-01978

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.

■ Microsoft Certified Trainers and Instructors—Your instructor is a technical and


instructional expert who meets ongoing certification requirements. And, if instructors
are delivering training at one of our Certified Partners for Learning Solutions, they are
also evaluated throughout the year by students and by Microsoft.

■ Certification Exam Benefits—After training, consider taking a Microsoft Certification


exam. Microsoft Certifications validate your skills on Microsoft technologies and can help
differentiate you when finding a job or boosting your career. In fact, independent
research by IDC concluded that 75% of managers believe certifications are important to
team performance1. Ask your instructor about Microsoft Certification exam promotions
and discounts that may be available to you.

■ Customer Satisfaction Guarantee—Our Certified Partners for Learning Solutions offer


a satisfaction guarantee and we hold them accountable for it. At the end of class, please
complete an evaluation of today’s experience. We value your feedback!

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.

Carsten Thomsen—Subject Matter Expert


Carsten Thomsen is an independent consultant who has worked since 1990 as a
software developer, analyst, architect, and author. He holds a number of Microsoft
certifications, including MCTS and MCPD, in various tools and applications,
including the Microsoft® .NET Framework, Microsoft Visual Basic®, Microsoft
Visual C#®, and Microsoft Office SharePoint® Server 2007. He works with
architecture, research, analysis, development, and troubleshooting, and spends
countless hours with the Windows® operating system and many other Microsoft
server products, including Hyper-V™ and SQL Server®.

Toi Wright—Technical Reviewer


Toi is an independent consultant who has worked as a software developer for over
25 years. She has a Bachelor of Science degree in Computer Science and
Engineering from the Massachusetts Institute of Technology, and a Master of
Business Administration degree from Carnegie Mellon University. She has been a
Microsoft MVP in ASP and ASP.NET since 2005. Toi is responsible for creating a
national initiative for Microsoft, and its partners in starting We Are Microsoft,
(www.wearemicrosoft.com), a community based partnership between IT
professionals and local non-profits. She has been a leader and organizer of
technical user groups in the Dallas, Texas area for over 10 years. She is currently
the President of the Dallas ASP.Net User Group, www.dallasasp.net. She is the
founder of Geeks in Pink, www.geeksinpink.org.
Introduction to Web Development with Microsoft® Visual Studio® 2010 xv

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

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


and Microsoft .NET–Based Languages
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

Module 3: Creating a Microsoft ASP.NET Web Form


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

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


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
xvi Introduction to Web Development with Microsoft® Visual Studio® 2010

Module 5: Implementing Master Pages and User Controls


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

Module 6: Validating User Input


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

Module 7: Troubleshooting Microsoft ASP.NET Web Applications


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

Module 8: Managing Data in a Microsoft ASP.NET 4.0 Web Application


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
About This Course i

About This Course


This section provides you with a brief description of the course, audience,
suggested prerequisites, and course objectives.

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

The completion of Course 2667, “Introduction to Programming”, satisfies the


preceding prerequisite programming skills requirement.

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.

To provide additional comments or feedback on the course, send e-mail to


support@mscourseware.com. To inquire about the Microsoft Certification
Program, send e-mail to mcphelp@microsoft.com.
About This Course vi

Virtual Machine Environment


This section provides the information for setting up the classroom environment to
support the business scenario of the course.

Virtual Machine Configuration


In this course, you will use Hyper-V™ to perform the labs.
The following table shows the role of each virtual machine used in this course.

Virtual machine Role

10267A-GEN-DEV Stand-alone machine

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.

Course Hardware Level


To ensure a satisfactory student experience, Microsoft Learning requires a
minimum equipment configuration for trainer and student computers in all
Microsoft Certified Partner for Learning Solutions (CPLS) classrooms in which
Official Microsoft Learning Product courseware are taught.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-1

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

Introduction to Microsoft .NET

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

Microsoft .NET Technologies


Microsoft .NET is built on an open architecture, which makes it easily extendable
when you build and run Web applications and services. Microsoft .NET includes
the following technologies and products:
• .NET Framework. The .NET Framework is a comprehensive and consistent
object-oriented programming model from Microsoft that provides an
environment for building platform-independent and device-independent
applications and services. The .NET Framework is the Microsoft platform for
building applications that have visually stunning user experiences, seamless
and secure communication, and the ability to model a range of business
processes. In the .NET Framework environment, code execution is efficient.
With these features, the .NET Framework helps minimize the efforts in
software deployment; it also reduces versioning conflicts, and promotes the
safe execution of code.
The .NET Framework provides a foundation to build and run applications and
services, and provides a common library of functions to build applications and
services. This commonality makes it easy to integrate applications built by
using the .NET Framework.
• Servers. Microsoft .NET provides an infrastructure to integrate, run, operate,
and manage the .NET Framework–based solutions on servers such as
Windows Server® 2008 R2, Microsoft SharePoint® Server 2010, and SQL
Server 2008 R2. This includes Web servers running Internet Information
Services (IIS) for hosting Web applications and services, and servers hosting
services, including Windows services and Windows Communication
Foundation (WCF) services.
• Clients. Microsoft .NET enables you to provide a consistent user experience
across many devices such as mobile devices, Web browsers, and personal
computers.
• Visual Studio 2010 and other developer tools. Using these tools, you can
rapidly develop WCF services, Windows-based applications, Web applications,
and Windows Azure-based applications, and thereby ensure enriched user
experiences.

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

Benefits of the .NET Framework

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

Components of the .NET Framework

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

During development, CLR provides features that simplify development


in multiple programming languages—for example, developing a Web
application in both Visual Basic and Microsoft Visual C#®. This means that
you can create parts of a Web application in one programming language, while
creating other parts in a different programming language.
• The .NET Framework class library. The .NET Framework class library is a
comprehensive, object-oriented collection of reusable features that you can use
for common development needs, including command-line applications,
graphical user interface (GUI) applications, Web Forms, and Web services.
The .NET Framework class library—also known as the Base Class Library
(BCL)—provides features that include user interface (UI), data access, database
connectivity, cryptography, Web application development, numeric
algorithms, and network communications. It exposes common language
runtime features, and simplifies the development of.NET–based applications.
In addition, you can extend classes by creating your own libraries. All
applications and all Microsoft .NET–based languages access the same .NET
Framework class libraries.
• Languages. The .NET Framework provides a variety of development languages
that enables developers to transfer their skills and development techniques to
the .NET development process. Each language provides broadly the same
functionality. Any language that conforms to the Common Language
Specification (CLS) can run with CLR. In the .NET Framework, Microsoft
provides support for languages such as Visual Basic, Visual C#, Microsoft
Visual C++®, and Microsoft Visual F#®. Third-party organizations also can
provide additional languages.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-11

.NET Framework 4 Technologies


The .NET Framework 4 supplies a comprehensive collection of classes that provide
features in many technology areas, including:
• ASP.NET. ASP.NET is a programming framework for building powerful Web
applications and services.
• Windows Forms. Windows Forms is the core development platform for
building smart client applications.
• Windows Presentation Foundation. Windows Presentation Foundation (WPF)
provides classes for smart-client applications that combine user interface,
documents, and media.
• Data Access. Data Access provides functionality to access external data sources,
including extensive XML support. Data Access is mainly implemented in
Microsoft ADO.NET, which also includes the Entity Framework, and Data
Services.

Note: For more information about ADO.NET, see Module 8, "Managing Data in a
Microsoft ASP.NET 4.0 Web Application."

• Windows Communication Foundation. WCF provides a unified programming


model for service-oriented applications.

Note: For more information about WCF, see Module 12, "Consuming Windows
Communication Foundation Services."

• Windows Workflow Foundation. Windows Workflow Foundation (WF)


provides a programming model and tools to build workflow-enabled
applications that model business processes.
1-12 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Runtime host Description

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 Features of Visual Studio 2010

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.

Features of Visual Studio 2010


Visual Studio 2010 provides the following features:
• Support for various programming languages
• Tools for building Web applications, Windows-based applications, WCF
services, WPF applications, and WF-enabled applications
• Tools for working with cascading style sheets (CSS), including the Apply
Styles and Manage Styles windows
• Data access tools, including support for the Entity Framework and language-
integrated query (LINQ)
1-14 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Multi-targeting support to enable developers to select the version of the .NET


Framework that they want their application to target
• Support for ASP.NET, Asynchronous JavaScript and XML (Ajax), JavaScript,
and jQuery
• Support for Microsoft Silverlight®
• Complete error handing, including local debugging, remote debugging, and
tracing
• Help and documentation that is presented in an easily accessible format

Question: Why is Visual Studio 2010 considered to be a complete set of


development tools?
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-15

Lesson 2
Overview of ASP.NET

ASP.NET is a programming framework for building Web applications. ASP.NET


Web Forms—which are part of an ASP.NET Web application—provide an easy way
to build dynamic Web sites. ASP.NET also includes the technology to build Web-
based WCF services, which provide the building blocks for constructing
distributed Web-based applications.
In this lesson, you will learn about the key features of ASP.NET and ASP.NET Web
applications, the components of an ASP.NET Web application, and the ASP.NET
dynamic compilation execution model.

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

• Describe the process of generating and rendering markup and code.


• Describe the ASP.NET dynamic compilation execution model.
• Describe the ASP.NET extensions.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-17

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."

• ASP.NET is a unified Web-development model that includes the services


necessary for you to build enterprise-class Web applications with a minimum
of coding. You can code your applications in any programming language
compatible with CLR, including Visual Basic, Visual C#, and Microsoft Jscript®
8.0. These languages enable you to develop ASP.NET applications that benefit
from the common language runtime, type safety, inheritance, and other
ASP.NET features.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-21

The following table describes the various features of ASP.NET.

Feature Description

Page and controls Page and controls framework encapsulates common UI


framework functionality in easy-to-use, reusable controls. The page
and controls framework also provides features to control
the overall look and feel of your Web site by using
themes and skins. In addition to themes, you can define
master pages, which you can use to create a consistent
layout for the pages in your application.

ASP.NET compiler All ASP.NET code is compiled, which enables strong


typing, performance optimizations, and early binding,
among other benefits. After the code is compiled, the CLR
component further compiles ASP.NET code to native
code, which provides improved performance.

Security infrastructure ASP.NET provides an advanced security infrastructure for


authenticating and authorizing user access, and
performing other security-related tasks. You can
authenticate users by using Windows authentication,
which is supplied by IIS. Alternatively, you can manage
authentication by using your own user database through
ASP.NET forms authentication and ASP.NET membership.

Forms authentication ASP.NET always runs with a particular Windows identity;


provider therefore, you can secure your application by using
Windows-based capabilities, such as NTFS file system
access control lists (ACLs) and database permissions.

State management ASP.NET provides intrinsic state management


functionality functionality that enables you to store information
between page requests, such as customer information, or
the contents of a shopping cart.

ASP.NET configuration ASP.NET applications use a configuration system


that enables you to define configuration settings for your
Web server, for a Web site, or for individual applications.
You can make configuration settings at the time your
ASP.NET applications are deployed, then add or revise the
configuration settings at any time, with minimal impact
on operational Web applications and servers.
1-22 Introduction to Web Development with Microsoft® Visual Studio® 2010

(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.

Troubleshooting ASP.NET takes advantage of the run-time debugging


support infrastructure to provide cross-language and cross-
computer debugging support. You can debug both
managed and unmanaged objects, and all languages
supported by CLR and script languages. In addition, the
ASP.NET page framework provides a trace mode that
enables you to insert instrumentation messages into your
ASP.NET Web pages.

Web-based WCF ASP.NET supports Web-based WCF services. A Web-


services based WCF service is a component containing business
functionality that enables applications to exchange
information across firewalls by using standards such as
HTTP and XML messaging.

Extensible hosting ASP.NET includes an extensible hosting environment that


environment and controls the life cycle of an application from the time a
application life-cycle user first accesses a resource—such as a page in the
management application—to the time when which the application is
shut down.

Extensible designer ASP.NET includes enhanced designer support for Web


environment server controls for use with a visual design tool such as
Visual Studio 2010.

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

For more information about ASP.NET Health Monitoring, see the


ASP.NET Health Monitoring Overview page at http://go.microsoft.com
/fwlink/?LinkID=192014&clcid=0x409.

For more information about the Extensible Designer Environment, see


the ASP.NET Control Designers Overview page at
http://go.microsoft.com/fwlink/?LinkID=192015&clcid=0x409.
1-24 Introduction to Web Development with Microsoft® Visual Studio® 2010

Components of ASP.NET Web Applications

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.

Components of an ASP.NET Web Application


The components of an ASP.NET Web application include:
• Web Forms, or .aspx pages. Web Forms provide the UI for the Web
application.
• User Controls, or .ascx files. User Controls provide the UI for specific
functionality to be reused in different Web Forms. One example is a user
control with textboxes and validation for username and password input.
• Master Pages, or .master files. Master pages provide a streamlined and
consistent UI across Web Forms.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-25

• 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

Generating and Rendering Markup and Code

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.

Code Generation and Rendering


When the compilers are requested to compile the code for your Web site,
compilation moves through various stages.

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

ASP.NET Dynamic Compilation Execution Model

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

3. If the code is not already compiled in a dynamic-link library (DLL), ASP.NET


invokes the compiler.
4. The runtime loads, and runs the Microsoft intermediate language (MSIL) code.

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.

Web Application Precompilation


ASP.NET can precompile a Web site before it is made available to users. This
provides faster response time, error checking, source-code protection, and efficient
deployment.
1-30 Introduction to Web Development with Microsoft® Visual Studio® 2010

ASP.NET Framework Extensions

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.

What Is ASP.NET Ajax?


ASP.NET Ajax is the free Microsoft Ajax framework that you use for developing
interactive and responsive Web applications that work with most popular
browsers. ASP.NET Ajax provides the ability to asynchronously send a section or
part of a Web page to the server, and respond to the server request in a manner
that does not distract the user or interrupt what the user is currently doing. The
ASP.NET Ajax framework can be used with server-side code and controls that
automatically produce the client-side code. This framework can also be used for
creating custom controls and client-side JavaScript code. The ASP.NET Ajax
framework includes the Ajax Control Toolkit, which is a collection of highly
interactive client-side controls, and the jQuery library, which is an extensive
JavaScript library.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-31

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."

What Is ASP.NET Dynamic Data?


ASP.NET Dynamic Data brings major usability and rapid application development
(RAD) changes to the existing ASP.NET data controls. RAD is significantly
increased by using a rich scaffolding framework. When connected to a data source,
you can use ASP.NET Dynamic Data to create a fully functional and data-driven
Web site. Full Create, Read, Update, and Delete (CRUD) operations are supported.
Smart validation is automatically available, and it provides validation based on the
database constraints for the data type, the field length, and the nullable fields.
Therefore, ASP.NET Dynamic Data is a framework that allows you to easily create
data-driven ASP.NET Web applications. It does this by automatically discovering
the data-model metadata at run time and deriving UI behavior from it. A
scaffolding framework provides a functional Web site for viewing and editing data.
You can easily customize the scaffolding framework by changing the elements or
creating new ones to override the default behavior. Existing applications can easily
integrate scaffolding elements with the ASP.NET pages.

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

Lab Application Setup

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

• Edit a customer row in spreadsheet-like view.


• Validate user input, including ensuring required information is entered, and in
the correct format.
• Store country rows.
• Create new country rows.
• Edit existing country rows.
• Display information about a single country.
• Display all country-related data in a spreadsheet-like view.
• Edit a country-related data in spreadsheet-like view.
• Go directly to customer-related or country-related information by passing the
ID in the URL.
• Expose all country rows to external customers and vendors by using a WCF
service or an independent Web Form.

User Interface Requirements


• Present input validation error messages in place, that is, next to input fields
that did not pass the input validation.
• Make the navigation consistent throughout the application by displaying the
same menu on all pages.
• Display the path to the current location or page being displayed.

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.

Working with the Customer Management Application


The Customer Management application is designed to enable the sales staff of
Contoso Pharmaceuticals to maintain customer and country data. A single
customer is located in a specific country, but any number of customers can live in
the same country, so there is a many-to-one relationship between customers and
countries.
1-36 Introduction to Web Development with Microsoft® Visual Studio® 2010

The application consists of the following components:


• Home Page. This is a simple greeting page that the user sees whenever they
open the application.
• Menu. The Menu, which is accessible on all pages, is based on a sitemap XML
file, and it provides the functionalities that are listed in the following table.

Functionality Description

Customers New—Creates a new customer row.


All—Shows all customer rows.

Countries New—Creates a new country row.


All—Shows all country rows.

Import Imports countries from an XML file.

About Displays a modal About dialog box.

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

ID The unique identifier of the customer. This field is read-only, and


is automatically assigned. The value of this field can be used when
navigating directly to a specific customer.

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.

Phone This is the phone number of the customer, saved in the


appropriate format for the country in which the customer resides,
and is limited to 30 characters.

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.

News Subscriber This Boolean field indicates if the customer subscribes to


newsletters. This field requires the E-mail Address field to be filled
in.

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.

A customer lives in a country, and the country information is saved in the


Countries table, which is referenced from the Customers table.
1-38 Introduction to Web Development with Microsoft® Visual Studio® 2010

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

ID This is a read-only field with the unique identifier of a country.


The value of this field can be used when navigating directly to a
specific country.

Name This is the English name of the country, and is limited to 50


characters. This field is mandatory.

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

ID uniqueidentifier N/A Yes newsequentialid() This is the unique ID


of the customer row,
which is automatically
assigned by the
database, if not
supplied on insert. This
is the primary key.

FirstName nvarchar 50 Yes This is the first name


of the customer. This
is a non-unique, non-
clustered index that is
sorted in ascending
order.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-41

(continued)

Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description

LastName nvarchar 30 Yes This is the last name


of the customer. This
is a non-unique, non-
clustered index that is
sorted in ascending
order.

Address nvarchar 50 Yes This is the customer


address, which includes
street name and door
number.

Phone varchar 30 No This is the customer


phone number, which
is saved in the
appropriate format for
the country in which
the customer resides.

ZipCode nvarchar 10 Yes This is the customer zip


code.

City nvarchar 30 Yes This is the name of


the city in which the
customer lives. This is
a non-unique, non-
clustered index sorted
in ascending order.

State nvarchar 30 No This is the name of the


state or region in which
the customer lives.
1-42 Introduction to Web Development with Microsoft® Visual Studio® 2010

(continued)

Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description

CountryID uniqueidentifier N/A Yes This is the unique ID


of the country in which
the customer lives.
This is a foreign key,
referencing the ID of
the corresponding
country in the
Countries table.

EmailAddress nvarchar 50 No This is the e-mail


address of the
customer. This is also
a non-unique, non-
clustered index that is
sorted in ascending
order.

Url nvarchar 80 No This is the address of


the customer’s Web
site.

CreditLimit int N/A Yes 50,000 This is the credit limit


assigned to the
customer.

NewsSubscriber bit No This indicates whether


or not the customer
subscribes to Contoso
newsletters.

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

The Countries table includes the following fields.

Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description

ID uniqueidentifier N/A Yes newsequentialid() This is a read-only


field with the unique
Identifier of a country.
This is the primary key.

Name nvarchar 50 Yes This is the English


name of the country.
This is also a unique,
non-clustered index
that is sorted in
ascending order.

PhoneNo varchar 30 No This is the format for


Format displaying and
entering a phone
number.

DialingCountry varchar 5 Yes This is the


Code international dialing
code when dialing
from outside 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.
1-44 Introduction to Web Development with Microsoft® Visual Studio® 2010

(continued)

Default value /
Transact-SQL
Field name Data type Size Required (T-SQL) function Description

International varchar 5 Yes This is the code or


DialingCode number that must be
used to dial a number
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.

InternetTLD char 2 Yes This is the country-


specific TLD for
Internet domains, such
as .dk for Denmark,
.de for Germany, .ie
for Ireland, .no for
Norway, or .au for
Australia.

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.

Import Countries Page


The Import Countries Web Form contains a Label, a file selection control for
locating the XML file with the Country data to import, and buttons to load or
import the data and export it to the SQL Server 2008 database.
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-45

Walkthrough: The Lab Solution

In this demonstration, the instructor will demonstrate the features and


functionalities of the Customer Management application. You can open the Lab
solution on the virtual machine and view the steps demonstrated. Open the
solution code by accessing the CustomerManagement solution file from the
D:\Labfiles\Solution\M16\VB or D:\Labfiles\Solution\M16\CS folders.
The Default.aspx Web Form is the home page for the Customer Management Web
application. The Default.aspx Web Form—like the other Web forms in the
application—is based on the Site.master master page. Users can browse to other
Web Forms by using the Menu or SiteMapPath controls.
1-46 Introduction to Web Development with Microsoft® Visual Studio® 2010

Demonstration: Exploring the .NET Framework

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

2. Open the finished lab solution.


• In the Start page – Microsoft Visual Studio (Administrator) window, on
the File menu, click Open Project.
• In the Open Project dialog box, in the File name box, type
D:\Labfiles\Starter\M16\VB\CustomerManagement.sln or
D:\Labfiles\Starter\M16\CS\CustomerManagement.sln, and then click
Open.
3. Examine some of the .NET Framework namespaces and classes, including
System.Web and System.Web.UI, and examine the System.Web.UI.Page
class.
4. Explore the Ajax Extensions and the Ajax Library features.
• Run the solution, and view the About box by clicking About on the Help
menu.

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."

5. Explore how Dynamic Data works.


• Run the solution.
• On the Customers menu, click All.
• On the Countries menu, click All.
6. If time permits, view code for some of the Module 6 and later lab exercises.

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

Demonstration: Exploring the Views and Controls of 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.

• 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-49

2. Create a new ASP.NET Web site with the following settings:


Name: WebSite1
Location: File system
Language: Visual Basic or Visual C#
• 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, under Installed
Templates, click Visual Basic or Visual C#.
• In the middle pane, ensure that .NET Framework 4 is selected in the
target framework list.
• In the New Web Site dialog box, in the middle pane, click ASP.NET
Empty Web Site.
• In the Web location list, ensure that File System is selected, and then
click OK.
3. Add the Default.aspx Web Form to the CustomerManagement 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, click Web Form, in
the Name box, type Default.aspx, and then click Add.
4. Open the Web Form in both the Design view and the Source view.
• In the Default.aspx window, click Design.
• In the Default.aspx window, click Source.
• In the Default.aspx window, click Design.
5. Add a Button control to the Web Form.
• In the Default.aspx window, select the div element.
• In the CustomerManagement – Microsoft Visual Studio (Administrator)
window, point to Toolbox.
• In Toolbox, expand Standard, and then double-click the Button control.
1-50 Introduction to Web Development with Microsoft® Visual Studio® 2010

6. Add code to the Button Click event.


• In the InsertCustomer.aspx window, click the Button control.
• In the Properties window, click the Events icon, and then double-click the
box next to the Click event.

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: Exploring the Components of an


ASP.NET 4.0 Web Application Project

In this demonstration, you will examine the various components of a Web


application project, including the solution file, the project file, the ASP.NET folders,
Web Forms, the code-behind files, the class files, the assembly info file, the
references, the web.config files, and the designer code files.

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

Review Questions and Answers


1. What is the major advantage of using ASP.NET?
2. What is the purpose of the code-behind files in ASP.NET?
3. What are Web Forms?
1-54 Introduction to Web Development with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions and Answers


1. Which components are included in the .NET Framework 4?
2. What is the purpose of CLR?
3. You need to create a programmable Web component that you can share
among multiple Web applications. Which type of component should you
create?
4. You need to develop an application that contains projects that target multiple
versions of the .NET Framework. Which tool enables you to accomplish this?
Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-55

Real-World Issues and Scenarios


1. You are unsure of the functionality of a particular class. How can you
determine the functionality of the class?
Use the .NET Framework documentation, Web sites, or online communities.
2. You are unsure whether to use dynamic compilation or precompilation. What
are the factors that you need to consider?
Use dynamic compilation in the following situations:
• When you want to modify your source code without having to explicitly
compile your code before deploying your Web application
• When you want to extend the ASP.NET build system by creating custom
build providers for new file types that are called during compilation
Use precompilation in the following situations:
• When response time is a concern
• To identify compilation errors before users access the site
• To deploy the Web site to a production server without the source code

Tools
Tool Purpose Where to find it

Visual Studio 2010 Developing Web Start menu


applications
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-1

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

Microsoft® Visual Studio® 2010 is a comprehensive development environment that


you can use to create powerful and reliable enterprise Web solutions. There are
different programming languages that you can use when you develop Microsoft
.NET Framework applications. You need to be aware of the fundamental aspects
when writing code and creating components using two of the .NET Framework–
based languages, Microsoft Visual C#® and Microsoft Visual Basic®. Visual Studio
2010 offers end-to-end Web development capabilities, and scalable and reusable
server-side components. These capabilities and components enable you to improve
your productivity, and effectively create applications and Microsoft ASP.NET Web
sites.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-3

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

For a programming language to be compatible with the .NET Framework, the


corresponding compiler—at build time—must compile the code into MSIL (or IL
as it is generally called). At run time, MSIL is compiled by the just in time (JIT)
compiler. In effect, the .NET CLR understands only one language—MSIL.
Therefore, if your platform or framework is the .NET Framework, you have several
options when choosing a programming language. Many programming languages
for the .NET Framework have the .NET Framework Base Class Library (BCL),
which has most of the functionality. It is generally not the functionality that sets
the programming languages apart, but the syntax, the code structure, and the
corresponding editor where you write your code.
Visual Studio 2010 includes Visual Basic and Visual C# to help create Web
applications. Web development has become very powerful, and yet simpler than
ever before with the inclusion of ASP.NET Asynchronous JavaScript and XML
(Ajax), the Ajax Library, Dynamic Data, language-integrated query (LINQ), many
controls, support for cascading style sheets (CSS), and scripting such as JavaScript
and jQuery.
In this lesson, you will explore the features of Visual Basic and Visual C#, and
examine the considerations for choosing between the two programming languages.
You will have situations that require multiple programming languages within the
same application; therefore, you need to know how to work with code in multiple-
language scenarios.

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

Features of Visual Basic

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

Visual Basic 10.0 Text Editor


The Visual Basic Text Editor features the color-coding of keywords, variables,
constants, and statements, like most other new .NET Framework–based languages.
The default color displays keywords colored in blue, and strings colored in a dark
red.
The Visual Basic Text Editor also features a background compilation model, in
which the code is compiled in the background as you type, to catch compile-time
and syntax errors. Any errors caught by the background compilation are
underlined with a squiggly line, and with different colors, depending on the type of
error. If you hover the pointer over one of these squiggly lines, Microsoft
IntelliSense® displays a description of the error, and the description is added to the
Error window.
The Visual Basic Text Editor automatically adds the method signatures for an
interface when you add the interface to a type declaration, and then press ENTER.
The following example shows how the code—between lines 2 and 33—has been
inserted by the editor by pressing ENTER, after typing the Implements
IDisposable statement.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-7

1 Public Class Class1


2 Implements IDisposable
3
4 #Region "IDisposable Support"
5 Private disposedValue As Boolean ' To detect redundant calls
6
7 ' IDisposable
8 Protected Overridable Sub Dispose(ByVal disposing As Boolean)
9 If Not Me.disposedValue Then
10 If disposing Then
11 ' TODO: dispose managed state (managed objects).
12 End If
13
14 ' TODO: free unmanaged resources (unmanaged objects)
and override Finalize() below.
15 ' TODO: set large fields to null.
16 End If
17 Me.disposedValue = True
18 End Sub
19
20 ' TODO: override Finalize() only if Dispose(ByVal disposing As
Boolean) above has code to free unmanaged resources.
21 'Protected Overrides Sub Finalize()
22 ' Do not change this code. Put cleanup code in Dispose(ByVal
disposing As Boolean) above.
23 ' Dispose(False)
24 ' MyBase.Finalize()
25 'End Sub
26
27 ' This code added by Visual Basic to correctly implement the
disposable pattern.
28 Public Sub Dispose() Implements IDisposable.Dispose
29 ' Do not change this code. Put cleanup code in
Dispose(ByVal disposing As Boolean) above.
30 Dispose(True)
31 GC.SuppressFinalize(Me)
32 End Sub
33 #End Region
34
35 End Class

Question: How are namespaces used in Visual Basic?


2-8 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

Visual C# 4.0 Text Editor


The Visual C# Text Editor offers color-coding of keywords, variables, constants,
and statements, like most other new .NET Framework–based languages. The
default color displays keywords colored in blue, and strings colored in red. Visual
C# also provides a background compilation model—similar to Visual Basic Text
Editor—in which the code compiles in the background as you type, and catches
compile-time and syntax errors. Any errors caught by the background compilation
are underlined with a squiggly line, with different colors indicating the type of
error. If you hover the pointer over one of these squiggly lines, IntelliSense displays
a description of the error. The errors are added to the Error window when the
project is rebuilt.
When you add an interface to a type declaration, you can use the editor to add the
method signatures for an interface by right-clicking the name of the interface. You
can click the Implement Interface, and then click Implement interface again. In
the following code, the code between lines 3 through 10 has been inserted by the
Visual C# Text Editor after adding IDisposable to the class declaration.

1 public class Class1 : IDisposable


2 {
3 #region IDisposable Members
4
5 public void Dispose()
6 {
7 throw new NotImplementedException();
8 }
9
10 #endregion
11 }

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

• Encapsulating a field, which involves creating a property for an existing field


member.
• Removing and reordering parameters.

Visual C# 4.0 Code Structure and Syntax


The syntax in Visual C# 4.0 is based on common English language keywords.
Blocks of code following a statement are enclosed by using braces {}, as shown in
the following code.

if () {}
switch () {}
for () {}
foreach () {}
void {}
class {}
namespace {}

The code in Visual C# is case-sensitive, making it possible to have variables differ


only by the casing of the name. However, this is discouraged because it can make
your code more difficult to read, understand, and debug.
Visual C# is fully object-oriented, which means that you cannot create global or
application-level variables and constants. However, static classes and members
make it possible to create the illusion of global variables and constants, as shown
in the following code.

public static class Class1


{
public const int AppLevelConstant = 15;
public static string AppName = "Application Name";
}

The AppLevelConstant constant and the AppName variable will be available to


the entire project to which the class belongs, as follows.

int appLevel = Class1.AppLevelConstant;


string name = Class1.AppName;
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-11

In Visual C#, each project has a default namespace, which is automatically


applied to all the types that you create. If the default namespace is
CompanyName.ApplicationName and you have a namespace for a specific type—
for example, Services.Customers—then the actual namespace for the type is
Services.Customers, because the default namespace is ignored. In addition, types
in project subfolders are automatically created with a namespace that is made up of
the default project namespace, followed by the folder name. Therefore, if a type is
stored in a subfolder named Test, and the default namespace is
CompanyName.ApplicationName, the actual namespace for that type is
CompanyName.ApplicationName.Test. You can override this by specifying the
full namespace for the type in code.
Statements in Visual C# are terminated by a semicolon. Comments can be single
line or multiline, as follows.

// Single line
/* Multi
line */

By default, most code in Visual C# is inherently safe, but unsafe language


constructs—such as pointers—are allowed. By default, numeric operations are not
checked, thus allowing numeric overflow and numeric underflow.
2-12 Introduction to Web Development with Microsoft® Visual Studio® 2010

Scenarios for Mixed-Language Environments

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.

Question: In what real-world scenarios do you use mixed languages?


Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-13

Considerations for Choosing Between Visual Basic and


Visual C# for an Application

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

Considerations for Choosing a Programming Language


When choosing a programming language, you need to evaluate the following
considerations:
• Number of lines of code to write
• Reuse of existing .NET Framework code
• Porting of legacy code, including classic ASP
• Use of unsafe constructs, such as pointers and numeric underflow and
overflow
• Text Editor formatting
• Use of default namespaces
• Case sensitivity
• Optional parameters
• Statement termination

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

Advantages of Using 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.

Multiple Programming Languages


Visual Studio 2010 natively supports the following programming languages:
• Visual Basic
• Visual C#
• Visual C++
• Visual F#

Multiple Project Types


Visual Studio 2010 supports the development of multiple project types, including
ASP.NET Web applications and XML Web services. This support for multiple
project types enables you to simultaneously work on several projects; you do not
have to change development environments or learn new tool interfaces or
languages.

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.

ASP.NET Development Server


The ASP.NET Development Server is built to run ASP.NET Web pages on the local
computer. It provides an efficient way to test pages locally before you publish or
deploy pages to a test, staging, or production server.
2-18 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Note: For more information about debugging, see Module 7, "Troubleshooting


Microsoft ASP.NET Web Applications."

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

Available Project Templates

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.

Solutions and Projects


When you create a project in Visual Studio 2010, you also create a larger container,
called a solution. This solution can contain multiple projects in the same manner
that a project container can contain multiple pages.
Solutions enable you to focus on the project or set of projects that are needed to
develop and deploy your application; you do not have to focus on the details of
managing the objects and files that define them.
2-20 Introduction to Web Development with Microsoft® Visual Studio® 2010

A solution enables you to:


• Work on multiple projects in the same instance of the IDE.
• Work on items, settings, and options that apply to a group of projects.
• Manage miscellaneous files that are outside the context of a solution or a
project.

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.

Project template Description

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)

Project template Description

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

Features of the Integrated Development Environment

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.

The Editor Window


The Editor window is the primary interface window in Visual Studio 2010. It
displays code for editing, and provides a graphical interface for control placement
in the form of a what you see is what you get (WYSIWYG) interface. You can use
drag-and-drop editing to create the visual design of your application. You can then
manage the logical design of your application by modifying the default Web
control code.
The window options for the editor are the Design mode, the Split mode, and the
Source mode:
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-23

• 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

Solution Explorer Pane


Clicking on the Solution Explorer tab displays the Solution Explorer pane, which
lists a hierarchy of project files. From this pane, you can:
• Use a drag-and-drop operation to rearrange items.
• Select an item in the Solution Explorer pane to view its properties in the
Properties window.

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.

Task List Window


You can use the Task List window to track the status of tasks as you develop your
application. The Categories list displays user tasks and comments:
• User Tasks. You can add tasks and set the description, priority, and
completion of the tasks. To add a task in the Categories list, click User Tasks,
and then click Create User Task.
• Comments. You can add TODO comments to your code for tasks that you
must complete. To access this section of code, in the Categories list, click
Comments, and then double-click the TODO comment.
2-26 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Manage Styles Window


The Manage Styles window lists all CSS style rules that are defined in the page's
external CSS. It also lists style rules that are defined on the page, but not as inline
styles. You can use the Manage Styles window to move styles from an external style
sheet to the style element on the page, and to move from the style element on the
page to an external style sheet. You can also use the window to move the location
of a style within the set of CSS style rules, and create a new CSS style by opening
the Styles dialog box and attaching an existing style sheet to the current page.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-27

Apply Styles Window


The Apply Styles window lists all the CSS style rules that are defined for a page.
This includes style rules that are defined in external style sheets, both as inline
styles, and as styles defined on the page. Class-based and ID-based style rules
appear under the name of the external .css file that contains the style. If the style
rule is defined on the page, it appears under Current Page. Element-based style
rules are organized the same way, but they appear under a separate heading titled,
Contextual Selectors.

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

• Validation. Contains a number of different validation controls that are used to


validate user input in Web server controls.
• Navigation. Contains navigational controls for a Web site.
• Login. Contains login controls for a Web site.
• WebParts. Contains Web Parts for a Web site.
• Ajax Extensions. Contains a set of server controls used for implementing Ajax
functionality.
• Dynamic Data. Contains controls for use with a Dynamic Data Web
application.
• HTML. Contains a set of Hypertext Markup Language (HTML) controls that
you can add to your Web page. These controls can run on either the server
side or the client side.
• Reporting. Contains a set of server controls used for creating SQL Server
reports.

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

Visual Studio 2010 Start Page

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.

Recent Projects Pane


The Recent Projects pane in the Start Page displays a list of recently updated
projects, which you can open or remove from the list by right-clicking the project.
You can also open the folder in which the project is located, from the context
menu.

Get Started Tab


The Get Started tab of the Content area displays a list of Help topics, Web sites,
technical articles, and other resources that can help you increase your productivity
and learn about features of the product.

Guidance and Resources Tab


The Guidance and Resources tab of the Content area on the Start page provides
general information on coding and development, and follows the same format as
the Get Started tab. It includes categories for Development Process, MSDN
Resources, and Additional Tools.

Latest News Tab


The Latest News tab displays a list of articles from the Really Simple Syndication
(RSS) feed that is specified at the top of the pane. By default, the ASP.NET News
RSS feed is used, but you can specify a custom RSS feed.

Customizing the Start Page


You can customize the news channel that the Start Page uses, and remove entries
from the Recent Projects pane. In addition, you can stop the Start Page from
appearing every time you start Visual Studio.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-31

Changing the Item Displayed at Development Environment Startup


1. On the Tools menu, click Options.
2. In the bottom left corner of the Options dialog box, ensure the Show all
settings option is selected.
3. Expand Environment, and then click Startup.
4. From the At startup drop-down list, choose one of the options, and then click
OK.

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

• Choose between a Web site project and a Web application project.


• Identify Web application files.
• Explain how to create, build, and view an ASP.NET Web application.
• Deploy a Web application.
2-34 Introduction to Web Development with Microsoft® Visual Studio® 2010

Web Application Development Process

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.

Note: For more information about debugging, see Module 7, "Troubleshooting


Microsoft ASP.NET Web Applications."

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

Web Application Project Files and Folders

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.

Web Application Project Template Files


When you create a Web application by using the ASP.NET Web application project
template, Visual Studio 2010 creates a Solution folder that contains the .sln
solution file. The file is a map of all of the various files that link one or more
projects together, and it stores global information. The Solution folder also
contains the subfolders and files that are listed in the following table.
2-38 Introduction to Web Development with Microsoft® Visual Studio® 2010

Type Name Description

Folders App_Data A folder that contains application data


files, including MDF files, XML files, and
other data store files.

Bin A folder that contains the project


assembly file.

Obj A folder that contains subfolders for


your build configurations.

My Project A Visual Basic–specific folder that


includes a number of autogenerated
code and XML files to support the
project infrastructure (settings and
resources), including
Application.Designer.vb,
Application.myapp,
Resources.Designer.vb, Resources.resx,
Settings.Designer.vb, and
Settings.settings.
In addition, the folder contains the
AssemblyInfo.vb file, which contains
general information—including
assembly version and assembly
attributes—about the assembly.

Properties A Visual C#–specific folder that


includes the AssemblyInfo.cs file. This
file contains general information about
the assembly, including the assembly
version and assembly attributes.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-39

(continued)

Type Name Description

Files Default.aspx The default ASP.NET Web Form.

Default.aspx.cs or Default.aspx.vb The code-behind file for the Web Form.

Default.aspx.designer.cs or The design-time partial class for the


Default.aspx.designer.vb Web Form.

Web.config The Web configuration file that


contains the configuration settings for
the Web application.

WebApplicationName.csproj or The XML document that contains


WebApplicationName.vbproj references to all project items—such as
forms and classes—in addition to
project references and compilation
options.

WebApplicationName.csproj.user The project settings for the user.


or
WebApplicationName.vbproj.user

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

Containers: Solutions and Projects


Solutions and projects contain items that represent the references, data
connections, folders, and files that you need to create your application. A solution
can contain multiple projects, and a project typically contains multiple items.
These containers enable you to utilize IDE in the following ways:
• Manage settings for your entire solution, or for individual projects.
• Use Solution Explorer to manage the file management details, while you focus
on project development.
• Add items to the solution, or to multiple projects in the solution, without
referencing any item in each individual project.
• Work on miscellaneous files that are independent from solutions or projects.

Items: Files, References, and Data Connections


Items can be files or other parts of your project, such as references, data
connections, or folders. In Solution Explorer, items can be organized in the
following ways:
• As project items, which are items that compose your project. Project items
include forms, source files, and classes within a project in Solution Explorer.
The project item organization and display depends on the project template
that you select, and any modifications that you make.
• As solution items for files that are applicable to your solution as a whole.
Solution items display in the Solution Items folder of Solution Explorer.
• As miscellaneous files that are not associated with either a project or a
solution. These files display in a Miscellaneous Files folder.

Question: What containers does Visual Studio provide?


Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-41

Web Site Project Files and Folders

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.

Web Site Project Template Files


When you create a Web site by using the ASP.NET Web site project template,
Visual Studio 2010 creates a Solution folder for the project. However, unlike the
Web application project Solution folder, the .sln solution file is not contained in
this folder. Instead, this file is by default stored in the Visual Studio 2010\Projects
subfolder of the user’s Documents folder. This file stores some of the information
contained in the project file, if you create a Web application project. This is
necessary to identify the content of the Web site project.
2-42 Introduction to Web Development with Microsoft® Visual Studio® 2010

The Web site project Solution folder contains the subfolders and files listed in the
following table.

Folder/file name Description

Account This folder contains a number of files, all relating to


user authentication.

App_Data This folder is for storing data files, such as


SQL Server 2008 Express edition database files.

Scripts This folder contains jQuery script files, but it can


also be used for any type of script files.

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.

Global.asax This is the Global Application File, which contains a


number of methods relating to the Web
Application or the current user session.

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.

Web.config This is configuration 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

Choosing Between a Web Site and a Web Application


Project

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

ASP.NET Web Applications


The main difference between the two types of Web application project templates
in Visual Studio 2010 is the inclusion of a project file in the ASP.NET Web
application project template. The ASP.NET Web site project template creates a
project that is folder-based—that is, all content in the main Web site project folder
is automatically part of the project. This effectively means that you can drag and
drop files into this folder, whereas with a Web application project, you must add
the new files to the project from within Visual Studio 2010.
When compiling and building a Web application project, all class files included in
the project are compiled into a single assembly that is placed in the Bin folder. The
assembly is the binary unit of deployment, which means that none of the code
must be deployed, except for code written in the markup files. In addition, the
Web form (.aspx) files, the user control (.ascx) files, and other static content files,
must be deployed.
When building a Web site project, you compile the code to test it. To deploy a Web
site project, you should deploy the actual source files and rely on ASP.NET
dynamic compilation to compile the pages and classes in the application.
To run or debug any page in a Web application project, you must build the entire
project, whereas with a Web site project, you can configure the build options to
build the site, build an individual page, or not build at all.
Because of the use of dynamic compilation, there is a distinct advantage to using
the Web site project if files that need compiling will be added after the initial
deployment. However, if you are concerned about deploying the source code, you
should use the Web application project, since only the assembly must be deployed
with the markup files, the Web form files, user control files, and other static
content files.
Other reasons for using the Web site project template are that you want to generate
one assembly for each page, or you want to open and edit any directory as a Web
project, without creating a project file.
Alternatively, the reason for choosing the Web application project template is that
you need to control the names of the output assemblies, which also means that you
can have stand-alone classes, reference pages and user control classes. In addition,
the Web application project template is the best choice if you need to build a Web
application that contains multiple Web projects, or if you need to add pre-build or
post-build steps and have more control over the compilation.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-45

Web Application Files

Key Points
In Visual Studio 2010, you can create different file types to support the
development of your Web application.

Web Application Files


Visual Studio 2010 supports the following application file types and extensions:
• ASP.NET Web Forms (.aspx). You can use ASP.NET Web Forms to build
dynamic Web sites that users can access directly. ASP.NET Web Forms are
supported by a code-behind file that is designated by either the extension
WebForm.aspx.vb, or the extension WebForm.aspx.cs.
• WCF services (.svc). You can use WCF services to create services that will be
accessed only by other programs. WCF services are based on contracts or
interfaces and code-behind files (.vb or .cs).
2-46 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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."

• Global application classes (Global.asax). The Global.asax file—also known as


the ASP.NET application file—is an optional file that contains code for
responding to application-level events that are raised by ASP.NET or by
HttpModules. At run time, Global.asax is parsed and compiled as a
dynamically generated .NET Framework class that is derived from the
HttpApplication base class.
• Master page files (.master). 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 of the pages (or a group
of pages) in your application.

Note: For more information about master pages, see Module 5, "Implementing Master
Pages and User Controls."

• Resource files (.resx). A resource is any non-executable data that is logically


deployed with an application. A resource can be displayed in an application as
an error message, or as part of the UI. Resources can contain data in a number
of forms, including strings, images, and persisted objects. Storing your data in
a resource file enables you to change the data without recompiling your entire
application.
• Styles.css. A CSS is a simple mechanism for adding styles—such as fonts,
colors, and spacing—to Web documents. Styles.css is the default style sheet file
for the Web application.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-47

• 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

Demonstration: How to Create a Simple Web Application


Project

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

3. Add TextBox and Button controls to the Default Web Form.


a. In the Default.aspx window, click Design.
b. In Design view, click the text You can also, click p, press the RIGHT
ARROW key, and then click ENTER.
c. In the Toolbox, expand Standard, and then double-click the Button
control.
d. In the Toolbox, under Standard, double-click the TextBox control.
4. Add code for the Click event handler of the Button control.
• In the Default.aspx window, double-click the Button control, and then
add the following code to the Click event handler.

[Visual Basic]
TextBox1.Text = "You clicked the button"

[Visual C#]
TextBox1.Text = "You clicked the button";

5. Write code to catch PostBack in the Page_Load event handler.


• Type the following code in the Page_Load event handler.

[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");
}
}

6. Build and debug the solution.


a. Place the breakpoint by clicking the mouse at the beginning of the code
where you check for the PostBack.
b. In the WebApplication1 – Microsoft Visual Studio (Administrator)
window, on the Debug menu, click Start Debugging.

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

Deploying a Web Application

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

Lab: Creating Web Applications by Using


Microsoft Visual Studio 2010 and Microsoft
.NET–Based Languages

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:

1. Create a simple ASP.NET Web site project.


2. Add a server control to a Web Form and configure its properties.
3. Build and deploy an ASP.NET Web site.

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

Section 1: Visual Basic


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.

4. Add an existing CSS file to the Web site.

X Task 1: Create an empty ASP.NET Web site


• Log on to the 10267A-GEN-DEV virtual machine as Student, with the
password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Create the empty CustomerManagement Web site with the following settings,
by using the New Web Site dialog box:
• Template: Empty ASP.NET Web Site
• Name: CustomerManagement
• Location: File system
• Path: D:\Labfiles\Starter\M2\VB\CustomerManagement
• Language: Visual Basic

X Task 2: Use a static port with the ASP.NET Development server


• In Solution Explorer, click D:\Labfiles\Starter\M2\VB
\CustomerManagement.
• In the Properties window, in the Use dynamic ports list, click False.
• In the Properties window, in the Port number box, type 1111, and then press
ENTER.

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

X Task 3: Save the Solution file


• In Solution Explorer, click Solution 'CustomerManagement' (1 project), and
then save the solution file as D:\Labfiles\Starter\M2\VB
\CustomerManagement.sln, by using the Save As command on the File
menu.

X Task 4: Add an existing CSS file to the Web site


• Create a folder named Styles, in the CustomerManagement Web site
• Add the D:\Labfiles\Starter\M2\Styles\Site.css file to the Styles folder, by
using the Add Existing Item dialog box.

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

Exercise 2: Adding and Configuring Server Controls in Web


Forms
The main tasks for this exercise are as follows:
1. Add a default Web Form to the Web site.
2. Close Visual Studio 2010.
3. Add the application title to the default Web Form.
4. Set the control properties of the default Web Form.
5. Apply the predefined style to the Web Form.

X Task 1: Add a default Web Form to the Web site


• Add the Default.aspx Web Form to the CustomerManagement Web site by
using the Add New Item dialog box.

Note: The Default Web Form displays in Source view, where you can notice that the
elements such as form, div, and body, are empty.

X Task 2: Close Visual Studio 2010


• Save modified files.
• Close Visual Studio 2010.

X Task 3: Add the application title to the default Web Form


• Open Microsoft Visual Studio 2010 as an administrator by using the Run as
administrator command on the context menu.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M2\VB folder, by using the Open Project dialog box.
• Add a Literal control from the Toolbox to the div element in the Default.aspx
window, and set its Text attribute to Customer Management, and ID property
to AppTitleLiteral, by using the Properties window.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-59

• 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.

X Task 4: Set the control properties of the default Web Form


• Open the default Web Form in Design view.
• Set the Visible property of the Literal control to False by using the Properties
window, and then save the changes.
• View the Web Form in the browser, and then view the source rendered to the
browser, by using the Source command on the View menu of Internet
Explorer.
• Close the open Internet Explorer windows.
• Set the Visible property of the Literal control to True.
• Set the Styles property of the div element by using the following properties in
the Modify Style dialog box, which are accessible from the Style property in
the Property window:
• Font-family: Trebuchet MS
• Font-size: 22
• Color: Gray
• Save the changes, and view the default Web Form in a Web browser.
2-60 Introduction to Web Development with Microsoft® Visual Studio® 2010

X Task 5: Apply the predefined style to the Web Form


• View the changes in the Source view.
• Add a reference to the Site.css file in the Styles folder from within the head
element by dragging the Styles/Site.css file to the Default.aspx window, next
to the title element.
• Set the Class property of the div element to appTitle, and then remove the
specific styles applied for the Styles property, by using the Properties window.
• Save the changes, and view the default Web Form in a Web browser.

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

Exercise 3: Building and Deploying an ASP.NET Web


Application
The main task for this exercise is to build and deploy the CustomerManagement
Web site.

X Task 1: Build and deploy the CustomerManagement Web site


• Open the Copy Web Site tool by selecting the Web site in Solution Explorer,
and then using the Website menu.
• Connect to local IIS in the Copy Web Site tool.
• Create a new virtual directory below the Default Web Site, by selecting Default
Web Site, and then clicking the Create New Virtual Directory button. Use the
following settings:
• Alias name: CustomerManagement
• Folder: C:\inetpub\wwwroot\CustomerManagement
• Select and open the new virtual directory in the Open Web Site dialog box.
• Copy the CustomerManagement Web site to the new virtual directory on the
local IIS, by selecting all files and folders in the left pane of the Copy Web Site
tool, and then clicking the Copy selected files from source to remote web
site button.
• View the deployed Web site in Internet Explorer at the address
http://localhost:1112/CustomerManagement.

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.

4. Add an existing CSS file to the Web site.

X Task 1: Create an empty ASP.NET Web site


• Log on to the 10267A-GEN-DEV virtual machine as Student, with the
password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Create the empty CustomerManagement Web site with the following settings,
by using the New Web Site dialog box:
• Template: Empty ASP.NET Web Site
• Name: CustomerManagement
• Location: File system
• Path: D:\Labfiles\Starter\M2\CS\CustomerManagement
• Language: Visual C#

X Task 2: Use a static port with the ASP.NET Development server


• In Solution Explorer, click D:\Labfiles\Starter\M2\CS
\CustomerManagement.
• In the Properties window, in the Use dynamic ports list, click False.
• In the Properties window, in the Port number box, type 1110, and then press
ENTER.

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

X Task 3: Save the Solution file


• In Solution Explorer, click Solution 'CustomerManagement' (1 project), and
then save the solution file as D:\Labfiles\Starter\M2\CS
\CustomerManagement.sln, by using the Save As command on the File
menu.

X Task 4: Add an existing CSS file to the Web site


• Create a folder named, Styles, in the CustomerManagement Web site. Right-
click the Web site in Solution Explorer, and then click New Folder.
• Add the D:\Labfiles\Starter\M2\Styles\Site.css file to the Styles folder, by
using the Add Existing Item dialog box.

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

Exercise 2: Adding and Configuring Server Controls in Web


Forms
The main tasks for this exercise are as follows:
1. Add a default Web Form to the Web site.
2. Close Visual Studio 2010.
3. Add the application title to the default Web Form.
4. Set the control properties of the default Web Form.
5. Apply the predefined style to the Web Form.

X Task 1: Add a default Web Form to the Web site


• Add the Default.aspx Web Form to the CustomerManagement Web site by
using the Add New Item dialog box.

Note: The Default Web Form displays in Source view, where you can see the elements
such as form, div, and body, are empty.

X Task 2: Close Visual Studio 2010


• Save modified files.
• Close Visual Studio 2010.

X Task 3: Add the application title to the default Web Form


• Open Microsoft Visual Studio 2010 as an administrator, by using the Run as
administrator command on the context menu.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M2\CS folder, by using the Open Project dialog box.
• Add a Literal control from the Toolbox to the div element in the Default.aspx
window, and set its Text attribute to Customer Management, and ID property
to AppTitleLiteral, by using the Properties window.
• 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.
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-65

X Task 4: Set the control properties of the default Web Form


• Open the default Web Form in Design view.
• Set the Visible property of the Literal control to False by using the Properties
window, and then save the changes.
• View the Web Form in the browser, and then view the source rendered to the
browser, by using the Source command on the View menu of Internet
Explorer.
• Close the open Internet Explorer windows.
• Set the Visible property of the Literal control to True. Set the Styles property
of the div element by using the following properties in the Modify Style dialog
box, which are accessible from the Style property in the Property window:
• Font-family: Trebuchet MS
• Font-size: 22
• Color: Gray
• Save the changes, and view the default Web Form in a Web browser.
2-66 Introduction to Web Development with Microsoft® Visual Studio® 2010

X Task 5: Apply the predefined style to the Web Form


• View the changes in the Source view.
• Add a reference to the Site.css file in the Styles folder from within the head
element by dragging the Styles/Site.css file to the Default.aspx window, next
to the title element.
• Set the Class property of the div element to appTitle, and then remove the
specific styles applied for the Styles property, by using the Properties window.
• Save the changes, and view the default Web Form in a Web browser.

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

Exercise 3: Building and Deploying an ASP.NET Web


Application
The main task for this exercise is to build and deploy the CustomerManagement
Web site.

X Task 1: Build and deploy the CustomerManagement Web site


• Build the CustomerManagement Web site, and then verify that the Web site
has no errors.
• Open the Copy Web Site tool, by selecting the Web site in Solution Explorer
and then using the Web site menu.
• Connect to local IIS in the Copy Web Site tool.
• Create a new virtual directory below the Default Web Site, by selecting Default
Web Site, and then clicking the Create New Virtual Directory button. Use the
following settings:
• Alias name: CustomerManagement
• Folder: C:\inetpub\wwwroot\CustomerManagement
• Select and open the new virtual directory in the Open Web Site dialog box.
• Copy the CustomerManagement Web site to the new virtual directory on the
local IIS, by selecting all files and folders in the left pane of the Copy Web Site
tool, and then clicking the Copy selected files from source to remote web
site button.
• View the deployed Web site in Internet Explorer at the address
http://localhost:1112/CustomerManagement.

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

1. How did you create a Web site?


2. Can you think of a reason why an ASP.NET Web Form (.aspx) has an
associated code-behind file?
3. How do you show or hide a server control?
Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET–Based Languages 2-69

Module Review and Takeaways

Review Questions and Answers


1. How would you select a .NET-based programming language to create a new
Web application project?
2. What role does common language runtime play in running an ASP.NET page?
3. What is the role of the JIT compilation?
4. List some of the languages that are currently supported by the .NET
Framework.
5. Why would you create a component for a Web application?
2-70 Introduction to Web Development with Microsoft® Visual Studio® 2010

Real-World Issues and Scenarios


1. You want to create a WCF service. What is the easiest way to implement this?
Use the WCF Service Application project template.
2. You want to create a reusable component that you can share with other
projects. What is the easiest way to implement this?
Use the Class Library project template.

Tools

Tool Function Where to find it

Editor window Displays code for editing and a Visual Studio IDE
graphical interface for control
placement.

Solution Explorer Displays the hierarchy of project Visual Studio IDE


files, and enables you to move and
modify files.

Properties window Enables you to adjust the Visual Studio IDE


properties of documents, classes,
and controls.

Task List Enables you to track the status of Visual Studio IDE
tasks as you develop your
application.

Output Displays status messages for Visual Studio IDE


various features in IDE.

Toolbox Enables you to use a drag-and- Visual Studio IDE


drop operation on the controls in
your application.
Creating a Microsoft® ASP.NET Web Form 3-1

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

What Is a Web Form?

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.

The .aspx Extension


Web Forms have an .aspx extension, and often consist of two separate files:
• The .aspx file that contains the UI for the Web Form.
• The .aspx.vb (Virtual Basic code) or .aspx.cs (Virtual C# code) file that
contains the supporting code. This file is called the code-behind file.
Creating a Microsoft® ASP.NET Web Form 3-5

Page Directives, Declarations, and Elements


Five levels of directives, declarations, and elements define the functions of a Web
Form:
• The Page directive and associated attributes define global functions.
• The !DOCTYPE element and associated attributes specify the document type
definition (DTD) to which the Web Form conforms.
• The HTML element and associated attributes verify that the Web Form
contains HTML elements.
• The BODY element and associated attributes defines and contains all the
content a page.
• The FORM element and associated attributes define how groups of controls
are processed.

Page Directive and Attributes


The page directive @ Page defines the page-specific attributes that are used by the
ASP.NET page parser and compiler. You must include only one page directive tag
for each Web Form. The following examples show the typical attributes for the
page directive, for a new Visual C# and Visual Basic Web Form.

[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

The attributes of a page directive include:


• AutoEventWireUp. The AutoEventWireUp attribute is used to indicate if the
event methods page-level events are automatically wired up. This means that
the Page_Load event, for instance, is automatically wired up to be caught and
handled—if you add the corresponding event handler and add some code to
it—to the code-behind file. For Visual C#, the default value is true, but for
Visual Basic, the default value is false. When AutoEventWireup is true,
ASP.NET does not require that you explicitly bind event handlers to page
events, such as Load or Init. Instead, handlers are automatically bound to
events at run time, based on their name and signature.
For each event, ASP.NET searches for a method that is named according to
the pattern Page_eventname, such as Page_Load or Page_Init. ASP.NET first
checks for an overload that has the typical event-handler signature Object and
EventArgs. If an event handler with this signature is not found, ASP.NET
checks for an overload that has no parameters. When AutoEventWireup is
false, you must explicitly bind event handlers to events. In that case, the
method names do not have to follow a pattern.
• CodeBehind. The CodeBehind attribute specifies the name of the compiled
file that contains the class associated with the page. This attribute is used with
Web application projects (WAPs).
• CodeFile. The CodeFile attribute specifies the path to the referenced code-
behind file for a page that uses the two-file configuration. This attribute is used
together with the inherits attribute to associate the code-behind file carrying
the logic that supports the Web Form. This attribute is used with Web Site
projects (WSP).
• Inherits. The Inherits attribute defines the name of the code-behind class that
the page inherits. The Inherits attribute is case sensitive when the page
language is Visual C#, and it is not case sensitive when the page language is
Visual Basic. This attribute is used with the CodeFile attribute, which contains
the path to the source file for the code-behind class. Notice how the CodeFile
attribute in the preceding examples specifies a file starting with Default, but
the value for the Inherits attribute is set to _Default. This is because Default is
a keyword in Visual Basic, and Visual Studio 2010 automatically prefixes the
class name with an underscore to prevent name conflicts. This is the same for
Visual C#, where there is no capitalized Default keyword. However, remember
that lowercase default is a keyword in Visual C#, which is case sensitive.
Creating a Microsoft® ASP.NET Web Form 3-7

• Language. The Language attribute specifies the programming language in


which the server-side code on the Web Form is written. This includes the code-
behind file, the inline code, and code declaration blocks on the page. Some of
the values for this attribute are Visual C# and Visual Basic, and the values are
used to indicate which compiler to use to parse and compile the page.
• Title. The Title attribute specifies the title of the page, and displays as the
caption of the browser, and on the tab if your browser session is tabbed.
Setting this attribute has the same effect as adding a TITLE element within the
HTML element. However, if both are specified, the title attribute of the Page
directive takes precedence.

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.

!DOCTYPE Element and Attributes


The !DOCTYPE element and associated attributes specify the DTD to which the
Web Form conforms. The following is a typical !DOCTYPE element created by
Visual Studio 2010.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

The !DOCTYPE element is generally used to specify the HTML or Extensible


HTML (XHTML) version that the Web Form complies with. You can find more
information about the !DOCTYPE declaration element in the Visual Studio 2010
Help.

The HTML Element and Attributes


The HTML element and associated attributes identify that the Web Form contains
HTML. In the standards-compliant mode, the HTML element represents the entire
surface on which a document's content can be rendered. The HTML element also
becomes the positioning container for positioned elements that do not have a
positioned parent, for example, a parent element or container that is positioned
differently than the default behavior. The following is a typical HTML element.
This element is not rendered, and typically does not contain any attributes.

<html>
...
</html>
3-8 Introduction to Web Development with Microsoft® Visual Studio® 2010

The BODY Element and Attributes


The BODY element and attributes define how objects appear on the client's
browser. In the nonstandards-compliant mode, the body element represents the
entire surface on which you can render content. The following is a typical body
element.

<body class="body" title="This page...">


</body>

The attributes of a BODY element include:


• class. The class attribute determines the cascading style sheets (CSS) class
that provides the style elements in the body of the Web Form.
• title. The title attribute defines a string that will be used as the tool tip when
the pointer is placed on any HTML elements or server controls that are in the
body of a Web Form.

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.

The FORM Element and Attributes


The <form> tag is different from the <html> tag that defines the entire Web page.
The <form> tag attributes define how groups of controls are processed. Although
you can have many HTML forms on a page, you can have only one server-side form
on an .aspx page.
The following is a typical FORM element.

<form id="form1" runat="server">


...
</form>
Creating a Microsoft® ASP.NET Web Form 3-9

Attributes of a FORM element include:


• id. This id attribute identifies the form server-side code when programmatic
access is required.
• method. The method attribute identifies the method for sending control
values back to the server. The options for this attribute are:
• post. Data is passed in name/value pairs in the body of the HTTP request.
This is the default value.
• get. Data is passed in a query string.
• runat. The runat="server" attribute indicates that the form should be
processed on the server. The runat="server" attribute causes the form to post
control information back to the ASP.NET page on the server on which the
supporting code runs. If the runat attribute is not set to "server" or is omitted,
the form works as a regular HTML form.

Question: What are the two components that make up Web Forms?
3-10 Introduction to Web Development with Microsoft® Visual Studio® 2010

How to Create a Web Form

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.

f Creating a New ASP.NET Web Application Project


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 Empty ASP.NET Web Application.
4. In the Name and Location boxes, type the name and location for the project,
and then click OK.
Visual Studio 2010 creates a new Web application.
Creating a Microsoft® ASP.NET Web Form 3-11

f Creating a New ASP.NET Web Site Project


1. In Visual Studio 2010, on the File menu, click New Web Site.
2. In the New Web Site dialog box, in the left pane, click Visual Basic or Visual
C#.
3. In the middle pane, click Empty ASP.NET Web Site.
4. In the Location box, type the location for the Web site, and then click OK.

Visual Studio 2010 creates a new Web site.

f Adding a Web Form to an Existing Web Application or Web Site


If you are expanding an existing project, you can use Solution Explorer to add
additional Web Forms.
1. In Solution Explorer, right-click an existing Web application project name or
Web site project name, and then click Add New Item. Alternatively, in
Solution Explorer, right-click an existing Web application project name or
Web site project name, and on the Website menu, click Add New Item, or
press the CTRL+SHIFT+A keys.
2. In the Add New Item dialog box, in the middle pane, click the Web Form
template.
3. In the Name box, type the name of the Web Form.
4. To create a code-behind file for a Web site project, select the Place code in
separate file check box, and then click Add.

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

• Add and configure HTML server controls.


• Add and configure Web server controls.
• Determine the appropriate server control for a Web Form.
3-14 Introduction to Web Development with Microsoft® Visual Studio® 2010

What Is a Server Control?

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.

<asp:Button id="SubmitButton" runat="server" Text="Submit" />

The following is an example of an input HTML server control.

<input type="text" value="Submit" runat="server" />


Creating a Microsoft® ASP.NET Web Form 3-15

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.

Common Object Model


In ASP.NET, server controls use a common object model; as a result, they share
several attributes. For example, when you want to set the background color for a
Web server control, you always use the same BackColor attribute, regardless of the
control. The following markup for a Web server control button shows some of the
typical attributes of a server control.

<asp:Button id="Button1" runat="server" BackColor="Red" Width="238px"


Height="25px" Text="Web control" />
3-16 Introduction to Web Development with Microsoft® Visual Studio® 2010

Creating Browser-Specific HTML


When a page is rendered for a browser, the Web server controls determine the type
of browser that is requesting the page, and then deliver the appropriate HTML.
For example, if the requesting browser supports client-side scripting such as
Windows Internet Explorer® 8, the controls create client-side script to implement
their functionality. However, if the requesting browser does not support client-side
script, the controls create server-side code and require more round trips to the
server to obtain the same functionality.
The following is the XHTML script that you would write to create a text box with
the default text “Enter your Username”.

<asp:TextBox id="UsernameTextBox" runat="server" Width="238px"


Height="25px">Enter your Username</asp:TextBox>

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.

<input name="UsernameTextBox" type="text" value="Enter your Username"


id="UsernameTextBox" style="height:25px;width:238px;" />

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.

Question: Which attribute makes a control a server control?


Creating a Microsoft® ASP.NET Web Form 3-17

Types of Server Controls

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.

HTML Server Controls


By default, HTML elements on a Web Form are not available to the server. HTML
elements are treated as plain text that is passed through to the browser. However,
you can add the runat="server" attribute and value to convert HTML elements to
HTML server controls. This changes the HTML elements to elements that you can
program by using server-side code.
3-18 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

br A self-closing element that <br />


adds a line break to the
page.

img A self-closing element that <img src="/login.png"


embeds an image on the alt="Log in to web application."
page. />

input Specifies different types of <input type="text"


input elements, including a name="UserName">
submit button, text box,
check box, radio button,
file selection control, and a
hidden control.

select Creates a selection “menu” <select size="3"


with at least one option. name="OptionList">
<option selected
value="Option1">
Option 1</option>
<option value="Option2">
Option 2</option>
<option value="Option3">
Option 3</option>
</select>

title Specifies the page title. <title>Login Page</title>


Creating a Microsoft® ASP.NET Web Form 3-19

Web Server Controls


Web server controls include form-type controls—such as buttons, lists, and text
boxes—and special-purpose controls, such as calendars. Web server controls are
more abstract than HTML server controls. Since the object model does not
necessarily reflect the HTML syntax, Web server controls are more flexible and
powerful than HTML server controls.
Web server controls are server controls that are created specifically for ASP.NET.
Unlike HTML server controls, Web server controls will not function if the
runat="server" attribute is missing.
Because Web server controls are based on a common object model, all controls
share several attributes, including asp:ControlType and an id attribute. Web server
controls exist in the System.Web.UI.WebControls namespace, and you can use
them in any Web Form.

Standard Web Server Controls


Standard controls contain two groups of controls: intrinsic controls, and complex
controls.
• Intrinsic controls. Intrinsic controls match the simple HTML elements, such as
buttons, lists, and text boxes. You use these controls in the same manner that
you use HTML server controls.
• Complex controls. Complex controls can either be controls that work with
static and dynamic data, controls that act as containers for other controls, or
controls that include multiple functions. An example of a complex control is
the Calendar control, which provides an appointment calendar that helps a
user select a date in the correct format.
3-20 Introduction to Web Development with Microsoft® Visual Studio® 2010

Intrinsic standard Web server controls correspond to simple HTML elements. The
following table describes some of the commonly used intrinsic Web server
controls.

Web server control


Web server control HTML control equivalent function
<asp:Button... /> <input type="submit" /> Creates a button that sends
a request to the server.

<asp:CheckBox... /> <input type="checkbox"> Creates a check box that


the user can select.

<asp:HyperLink... /> <a href="…" /> Creates a hyperlink to an


HTML anchor tag.

<asp:Image... /> <img src="…" /> Creates an image.

<asp:ImageButton... /> <input type="image" /> Creates a button that


incorporates the display of
an image, instead of text.

<asp:Label... /> <span> </span> Creates text that users


cannot edit.

<asp:ListBox... /> <select size="5"> Creates a list of choices,


</select> and enables multiple
selections.

<asp:Panel... /> <div> </div> Creates a borderless


division on the form that
serves as a container for
other controls.

<asp:RadioButton... /> <input type="radio"> Creates a single radio


button control.

<asp:Table... /> <table> </table> Creates a table.

<asp:TextBox... /> <input type="text" /> Creates a text box control.


Creating a Microsoft® ASP.NET Web Form 3-21

Complex standard controls insert complex functions into your Web Form. The
following table describes some of the complex controls.

Control Function

AdRotator Displays a predefined or random sequence of images.

Calendar Displays a graphic calendar on which users can select dates.

FileUpload Provides users with a way to upload a file from to the server.

Wizard Provides navigation and a UI to collect related data across


multiple steps.

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

Chart Enables you to create ASP.NET pages with simple, intuitive,


and visually compelling charts for complex statistical or
financial analysis.

DataList Displays rows of database information in a customizable


format.

DetailsView Displays a single row of data from a data source by using a


tabular layout, where each row field is displayed as a row of
its own.

FormView Displays a single row of data from a data source by using a


layout defined by a template.

GridView Displays tabular data in a grid.

ListView Displays data in a format that you define by using


templates and styles. Implicitly supports Edit, Insert, and
Delete operations, in addition to the sorting and paging
functionality. This is also true if the control is not bound to
a data source.

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.

Repeater Displays information from a data set by using a set of


HTML elements and controls that you specify. The
Repeater control repeats the element once for each record
in the data set.
Creating a Microsoft® ASP.NET Web Form 3-23

The following table describes some of the commonly used data source controls.

Control Function

AccessDataSource Connects to data from a Microsoft Access® database for


use with data-bound controls.

EntityDataSource Represents an Entity Data Model (EDM) to data-bound


controls in an ASP.NET application.

LinqDataSource Connects to data from either a database or an in-memory


data collection (such as an array), and exposes language-
integrated query (LINQ) to Web developers.

SiteMapDataSource Exposes navigation data retrieved from a site map


provider.

SqlDataSource Connects to data that is located in a relational data base,


such as Microsoft SQL Server®.

XmlDataSource Connects to data in XML format, whether hierarchical or


tabular.

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

The following table describes the validation controls.

Control Function

CompareValidator Requires that the input matches a second input or


existing field.

CustomValidator Requires that the input matches a condition such


as prime or odd numbers.

RangeValidator Requires that the input is within a specified range.

RegularExpressionValidator Requires that the input matches a specified format


such as a U.S. telephone number, or a strong
password that consists of numbers and letters.

RequiredFieldValidator Requires that the user enters some value before


the control is processed.

ValidationSummary Collects all the validation control error messages


for centralized display.

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

The following table describes the Login controls.

Control Function

ChangePassword Enables users to change the Web site password.

CreateUserWizard Adds a new user to the Web site.

Login Displays a user interface for user authentication, including


user name and password text boxes, and a Login button.

LoginName Displays a user's login name, if logged in.

LoginStatus Displays a login link for users who log in, and a logout link
for logged-in users.

LoginView Displays different information to anonymous users and


logged-in users.

PasswordRecovery Used to retrieve user passwords.

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

Menu Supports displaying a main menu and submenus, but also


allows you to define dynamic menus.

SiteMapPath Displays a navigation path/breadcrumb showing the current


page location.

TreeView Displays hierarchical data in a tree structure.


3-26 Introduction to Web Development with Microsoft® Visual Studio® 2010

Example of Equivalent Controls


The following example shows the HTML code for three button controls: an HTML
button, an HTML server control button, and a Web server control button. All
button controls appear identical on the user’s browser. The HTML button raises
only client-side events, while the HTML server control button and the Web server
control button raise server-side events.
The following example is of an HTML button control.

<input type="button" value="HTML Button" />

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.

<input type="button" value="HTML Server Control" id="Button1"


runat="server" />

The following example is of a Web server control button.

<asp:Button id="Button1" runat="server" Text="Web control" />

Question: Which types of server controls exist for ASP.NET?


Creating a Microsoft® ASP.NET Web Form 3-27

Saving View State

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.

Disabling and Enabling ViewState


By default, a Web Form saves the controls’ View state on the Web Form. However,
for Web Forms with multiple controls, the size of the __VIEWSTATE properties
value field can slow the performance. To maximize page performance, you might
want to disable the __VIEWSTATE attribute at the page level, and enable the View
state only for selected controls.
To disable the View state at the Web page level, set the EnableViewState attribute
of the Page directive to false. The following code illustrates this.

<%@ Page EnableViewState="false" %>

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.

<asp:ListBox id="ListBox1" EnableViewState="false" runat="server" />


Creating a Microsoft® ASP.NET Web Form 3-29

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.

<%@ Page ViewStateMode="Disabled" %>


...
<asp:ListBox id="ListBox1" " runat="server" ViewStateMode="Enabled" />

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.

<asp:HiddenField id="HiddenField1" runat="server" value="1"/>


Creating a Microsoft® ASP.NET Web Form 3-31

Adding and Configuring HTML Server Controls

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

HTML Server Control Example


You can use the drag-and-drop operation to move HTML elements from the HTML
tab of the Toolbox to the Web Form. You can then configure the controls by
setting the properties in the Properties window.
The following code shows a simple HTML text box control that is processed by the
client side browser.

<input id="Text1" type="text" />

The following code is generated when you use the drag and drop operation to
move the control from the Toolbox to the Web Form.

<input id="Text1" type="text" />

Adding the runat="server" attribute converts the element to an HTML server


control that is processed on the server side by ASP.NET.

<input id="Text1" type="text" runat="server" />

Question: What are the features offered by HTML server controls?


Creating a Microsoft® ASP.NET Web Form 3-33

Adding and Configuring Web Server Controls

Adding and Configuring Web Server Controls


To add and configure Web server controls, you need to perform the following
steps:
1. Open Visual Studio 2010, and on the File menu, click New Web Site.
2. In the left pane, click Visual Basic.
3. In the middle pane, click ASP.NET Empty Web Site.
4. In the Web location list, click File System, in the text box, type
C:\WebSite1\SampleWebSite, and then click OK.
5. In Solution Explorer, right-click the SampleWebSite web site project, and then
click Add New Item.
6. In the Add New Item dialog box, in the middle pane, click Web Form, in the
Name box, type Default.aspx, and then click Add.
7. In the Default.aspx window, click Design.
8. In the Default.aspx window, click Toolbox.
3-34 Introduction to Web Development with Microsoft® Visual Studio® 2010

9. In Toolbox, expand Standard, and then double-click the TextBox control.


10. In the Properties window, change the value of the (ID) property to
SampleTextBox, and the value of the Text property to Sample.
11. In Toolbox, expand Standard, and then double-click the Calendar control.
12. In the Properties window, change the value of the (ID) property to
SampleCalendar.

When rendered to the client, the TextBox control looks like the following code
example.

<input name="SampleTextBox" type="text" value="Sample"


id="SampleTextBox" />

This previous code is an example of a straight conversion from a TextBox server


control to an HTML INPUT element of type, text.

Question: What are the additional features offered by Web server controls?
Creating a Microsoft® ASP.NET Web Form 3-35

Discussion: Selecting the Appropriate Server Control

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.

HTML Server Controls


While the best practice is to avoid using HTML server controls and use Web server
controls instead, there are times when HTML server controls must be used. HTML
server controls are modified HTML elements that run on the server, instead of in
the client browser.
3-36 Introduction to Web Development with Microsoft® Visual Studio® 2010

You might use HTML server controls in the following situations:


• You prefer an HTML-like object model. HTML server controls have almost the
same HTML code as the basic HTML controls.
• You want to work with existing HTML pages, and you want to add Web Form
functionality quickly. Because HTML server controls map exactly to HTML
elements, you do not have to replace controls and risk substitution errors or
page formatting problems.
• Bandwidth is limited, and you must perform a large amount of client-side
processing to reduce bandwidth usage.

Web Server Controls


ASP.NET Web server controls approximate HTML controls. Additionally, they
include a number of new controls that currently do not exist in HTML.
You use Web server controls in the following situations:
• You prefer an object-oriented programming model. You can use object-
oriented programming, identify controls by their ID attribute, and easily
separate the page logic from the UI. By using Web server controls, you can also
create applications with nested controls and catch events at the container level.
• You must create a Web page that might be viewed by using a variety of
browsers. The logic inside the Web server controls is able to create HTML that
is tailored to the features that are available in the client's browser. You can
write code for the latest browsers without worrying about browser errors that
might restrict users who do not have the latest browser versions from
accessing all the functions of the Web page.
• You require specific functionality—such as a calendar or an advertisement—that
is available only as a Web server control.
• Your bandwidth is not limited, and the request-response cycles of Web server
controls will not cause bandwidth problems.
Creating a Microsoft® ASP.NET Web Form 3-37

Lab: Creating a Microsoft ASP.NET Web Form

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:

• User name: Student

• 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

Section 1: Visual Basic


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.

f Task 1: Open an existing ASP.NET Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M3\VB folder.

f Task 2: Add a Web Form to the Web site


• Add the InsertCustomer.aspx Web Form to the CustomerManagement Web
site, by using the Add New Item dialog box.

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

Exercise 2: Adding and Configuring Server Controls in a


Web Form
The main tasks for this exercise are as follows:
1. Add an existing style sheet to the Web Form.
2. Create a table-style layout in the Web Form.
3. Add the server controls to the Web Form and configure their basic properties.
4. Set the non-trivial control properties.
5. Apply a predefined style to the Web Form.

Note: In this exercise, you are creating a two-column table using CSS for holding various
controls used for displaying and managing Customer data.

f Task 1: Add an existing style sheet to the Web Form


• Reference the Styles/Site.css file in the InsertCustomer Web Form, relative to
the root folder, by using the Manage Styles window.
• Press CTRL+S to save InsertCustomer.aspx.
• View the styles added in the style sheet by using the Manage Styles window.

f Task 2: Create a table-style layout in the Web Form


• In the InsertCustomer.aspx window, place the cursor between the opening
and closing div tags.
• Add a new div element from the Toolbox to the existing div element.

<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>

• Save the changes to the InsertCustomer Web Form.


• Use the Apply Styles window to apply the customerTable style to the
outermost div element. Apply div.customerTable from the Contextual
Selectors section of the Apply Styles window.
• Click the opening tag of the div element, which is a child element of the div
element with a class attribute value of customerTable.
• Create new style in the Apply Styles window, by using the New Style button.
• Name the new style div.customerTableRow by using the Selector box of the
New Style dialog box.
• Apply the style to the current document selection by using the Apply new
style to document selection check box.
• Define the new style in the existing Styles/Site.css CSS file.
• Set the layout of the new style to table-row, by using the display list of the
Layout category, and then close the New Style dialog box.
• Use the Apply Styles window to apply the customerTableLeftCol style to the
first child div element of the div element with a class attribute value of
customerTableRow.
• Use the Apply Styles window to apply the customerTableRightCol style to the
second child div element of the div element with a class attribute value of
customerTableRow.
Creating a Microsoft® ASP.NET Web Form 3-43

• 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>

• View the InsertCustomer Web Form in Design view.

Note: Notice that two equal-sized columns are added to the div element.

• View the InsertCustomer Web Form in Source view.


• Use the Apply Styles window to apply the customerTableFooter style to the
last child div element of the div element with class attribute value of
customerTable.
• Save the changes to the InsertCustomer Web Form and the Site.css file.
• In the CustomerManagement – Microsoft Visual Studio (Administrator)
window, on the File menu, click Save All.
• View the InsertCustomer Web Form in a Web browser.
3-44 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

f Task 4: Set the non-trivial control properties


• Set the MaxLength property of the CustomerFirstNameTextBox,
CustomerAddressTextBox, and CustomerEmailAddressTextBox controls to
50.
• Set the MaxLength property of the CustomerLastNameTextBox,
CustomerCityTextBox, CustomerStateTextBox, and
CustomerPhoneTextBox controls to 30.
• Set the MaxLength property of the CustomerZipCodeTextBox and
CustomerCreditLimitTextBox controls to 10.
• Open the InsertCustomer Web Form in the Source view.
• Set the MaxLength property of the CustomerWebAddressTextBox control to
80.
• Save the changes and view the InsertCustomer Web Form in a Web browser.
Creating a Microsoft® ASP.NET Web Form 3-47

f Task 5: Apply a predefined style to the Web Form


• Apply the predefined template style to the body element of the
InsertCustomer Web form.
• 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.

f Task 1: Open an existing ASP.NET Web site


• Log on to the 10267A-GEN-DEV virtual machine as Student, with the
password, Pa$$w0rd.
• Open Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M3\CS folder.

f Task 2: Add a Web Form to the Web site


• Add the InsertCustomer.aspx Web Form to the CustomerManagement Web
site by using the Add New Item dialog box.

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

Exercise 2: Adding and Configuring Server Controls in a


Web Form
The main tasks for this exercise are as follows:
1. Add an existing style sheet to the Web Form.
2. Create a table-style layout in the Web Form.
3. Add the server controls to the Web Form and configure their basic properties.
4. Set the non-trivial control properties.
5. Apply a predefined style to the Web Form.

Note: In this exercise, you are creating a two-column table using CSS for holding various
controls used for displaying and managing Customer data.

f Task 1: Add an existing style sheet to the Web Form


• Reference the Styles/Site.css file in the InsertCustomer Web Form, relative to
the root folder, by using the Manage Styles window.
• Press CTRL+S to save InsertCustomer.aspx.
• View the styles added in the style sheet by using the Manage Styles window.

f Task 2: Create a table-style layout in the Web Form


• In the InsertCustomer.aspx window, place the cursor between the opening
and closing div tags.
• Add a new div element from the Toolbox to the existing div element.

<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>

• Save the changes to the InsertCustomer Web Form.


• Use the Apply Styles window to apply the customerTable style to the
outermost div element. Apply div.customerTable from the Contextual
Selectors section of the Apply Styles window.
• Click the opening tag of the div element, which is a child element of the div
element with a class attribute value of customerTable.
• Create new style in the Apply Styles window, by using the New Style button.
• Name the new style div.customerTableRow by using the Selector box of the
New Style dialog box.
• Apply the style to the current document selection by using the Apply new
style to document selection check box.
• Define the new style in the existing Styles/Site.css CSS file.
• Set the layout of the new style to table-row, by using the display list of the
Layout category, and then close the New Style dialog box.
• Use the Apply Styles window to apply the customerTableLeftCol style to the
first child div element of the div element with a class attribute value of
customerTableRow.
• Use the Apply Styles window to apply the customerTableRightCol style to the
second child div element of the div element with a class attribute value of
customerTableRow.
Creating a Microsoft® ASP.NET Web Form 3-51

• 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>

• View the InsertCustomer Web Form in Design view.

Note: Notice that two equal-sized columns are added to the div element.

• View the InsertCustomer Web Form in Source view.


• Use the Apply Styles window to apply the customerTableFooter style to the
last child div element of the div element with class attribute value of
customerTable.
• Save the changes to the InsertCustomer Web Form and the Site.css CSS style
sheet file.
• View the InsertCustomer Web Form in a Web browser.

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 4: Set the non-trivial control properties


• Set the MaxLength property of the CustomerFirstNameTextBox,
CustomerAddressTextBox, and CustomerEmailAddressTextBox controls to
50.
• Set the MaxLength property of the CustomerLastNameTextBox,
CustomerCityTextBox, CustomerStateTextBox, and
CustomerPhoneTextBox controls to 30.
• Set the MaxLength property of the CustomerZipCodeTextBox and
CustomerCreditLimitTextBox controls to 10.
• Open the InsertCustomer Web Form in the Source view.
• Set the MaxLength property of the CustomerWebAddressTextBox control to
80.
• Save the changes and view the InsertCustomer Web Form in a Web browser.
Creating a Microsoft® ASP.NET Web Form 3-55

f Task 5: Apply a predefined style to the Web Form


• Apply the predefined template style to the body element of the
InsertCustomer Web form.
• 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

1. What are the advantages of Web Form controls?


2. What type of Web server controls are used in the lab?
Creating a Microsoft® ASP.NET Web Form 3-57

Module Review and Takeaways

Review Questions and Answers


1. How can you verify that a Web page with an .aspx extension in an ASP.NET
Web site is a Web Form?
2. How can you verify that a Web page with an .aspx extension contains intrinsic
ASP.NET Web server controls?
3. What type of markup or script does a Web server control generate on the
client?
A Web server control generates HTML and JavaScript, if the Web server
3-58 Introduction to Web Development with Microsoft® Visual Studio® 2010

Real-World Issues and Scenarios


1. You want to add a page to your Web application that you can work with by
using server-side code. What is the easiest way to implement this?
You add a new item by using the Web Form item template.
2. You want to add a title to a Web Form. What is the easiest way to implement
this?
You specify a value for the title attribute of the Page directive.

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

Methods for Implementing Code

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 and Inline Code

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

The following are examples of inline code.

[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>

<script Language="C#" runat="server">


private void Button1_Click(object sender, System.EventArgs e)
{
...
}
</script>

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

With code-behind files, it is also possible to implement a class in two or more


separate code files by using the Partial/partial keyword. The following code
shows how you can use the Partial/partial keyword for working with partial
classes.

[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;

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
}
4-10 Introduction to Web Development with Microsoft® Visual Studio® 2010

The entire content of the Default.aspx.vb and Default.aspx.cs code-behind files


have been shown, and not just the class definition. However, there is a difference in
the generated code for Visual Basic and Visual C#. Visual Basic does not add the
namespaces used for a Web Form, because they are automatically referenced or
imported through the project settings. Visual C# also adds the event handler
method for the Page.OnLoad event, because it is more difficult to add this code
manually in Visual C# than in Visual Basic. This event handler is used in most Web
Forms.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-11

Using Code-Behind Files

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

Linking .aspx and Code-Behind Files


The .aspx file must be associated with the code-behind file. To accomplish this,
Visual Studio 2010 adds the following three attributes to the Page directive of the
.aspx page:
• CodeBehind. This attribute specifies the name of the compiled file that
contains the class associated with the page. CodeBehind is used with Web
Forms in a Web application project (WAP).
• CodeFile. This attribute specifies a path to the referenced code-behind file for a
Web Form page. This attribute is used together with the Inherits attribute to
associate a code-behind source file with a Web page. CodeFile is used with
Web Forms in a Web Site project (WSP).
• Inherits. This attribute allows the .aspx page to inherit from a class in the
code-behind file. The Inherits attribute defines a code-behind class for the
page to inherit. This can be any class derived from the Page class. This
attribute is used with the CodeFile attribute, which contains the path to the
source file for the code-behind class.

Note: The Inherits attribute is case sensitive in Visual C#, and case insensitive in Visual
Basic.

In addition to the three attributes mentioned, the AutoEventWireup attribute


indicates whether page event autowiring is enabled for a Web Forms page.

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

Compilation and Deployment


Visual Studio 2010 supports two types of Web application projects: WAP and
WSP. Both offer different types of compilation.
• WAP. When building your project, the code is compiled into Microsoft
intermediate language (MSIL) and is contained in a single assembly, which is
usually placed in the Bin subfolder of the project folder. This allows you to
easily deploy just the markup and the compiled assembly. Upon first
application request, the compiled assembly is copied to the temporary
ASP.NET files folder, where it is JIT compiled into binary code that the
operating system can run. This causes a slight delay in responding to the first
request, when compared with subsequent requests.
• WSP. By default, an ASP.NET Web site is not precompiled. Instead, ASP.NET
compiles your Web site the first time a page is requested. This is also known as
in-place compilation. The application is compiled into one or more assemblies
in the temporary ASP.NET files folder upon first request. Deploying an
ASP.NET Web site is convenient, because it allows you to make modifications
to a Web Form or code-behind file, and deploy the Web Form to the server
without compiling the source code.

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

What Are Event Handlers?

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

Examples of an Event Handler


Many Web Forms allow the user to enter information, and then click a Submit
button, which generates an event. An event handler written for this click event may
send the user information to a Microsoft SQL Server® database, upload a file to the
Web server, or simply redirect the user to a different page. The following are
examples of event handler code.

[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");
}

Question: How are types of events classified for ASP.NET?


Adding Functionality to a Microsoft® ASP.NET Web Form 4-19

What Are Client-Side Event Handlers?

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

You can retrieve a reference to the ClientScriptManager class from the


ClientScript property of the Page object. Client-side event handlers never have
direct access to server resources. For example, you cannot use a client-side script to
directly access a SQL Server database.

Uses of Client-Side Event Handlers


Client-side event handlers are useful for events that you want to generate
immediately. Client-side event handlers do not require a round trip to the Web
server. This means that it is not necessary to send information to the Web server
and wait for a response.
For example, you may want to validate information in a text box before it is
submitted to the server. You can use client-side scripts to validate the information
quickly and effectively before sending the information to the Web server for further
processing. Client-side script can be used to improve user experience with richer
and more responsive Web pages that perform almost like traditional client
applications.
4-22 Introduction to Web Development with Microsoft® Visual Studio® 2010

What Are Server-Side Event Handlers?

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.

Server-Side Event Handlers


Server-side event handlers consist of compiled code that resides on the Web server.
You can use server-side event handlers to handle events that are generated from
both Web and HTML server controls. Server-side event handlers have access to
server resources that are usually unavailable to client-side event handlers.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-23

The following examples specify a server-side event handler by using the


runat="server" attribute in the opening <script> tag.

[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

Programming language JavaScript Any .NET Framework–based language,


such as Visual Basic or Visual C#

Processed on client Yes No

Processed on server No Yes

Compiled No Yes

Interpreted Yes No

Access server-side No Yes


resources directly
4-24 Introduction to Web Development with Microsoft® Visual Studio® 2010

Although JavaScript is available in a few different implementations, it is still the


only cross-browser compatible programming language. If you use Windows®
Internet Explorer® exclusively for accessing an intranet portal, you can also use
Microsoft Visual Basic Scripting Edition (VBScript) for creating your client-side
code and event handlers.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-25

How Client-Side and Server-Side Event Handlers Are


Processed

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

Creating Server-Side Event Handlers

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

Creating a Server-Side Event Handler


When you double-click a control in Visual Studio 2010, Visual Studio creates an
empty event handler. When you use Visual Basic, Visual Studio 2010 also adds the
Handles keyword, which links the event handler to the control events. The
Handles keyword allows you to create multiple event handlers for a single event,
or a single event handler for multiple events.

Creating a Server-Side Event Handler in Visual Basic


In Visual Basic, the runat="server" attribute and the Handles statement are used to
create ASP.NET event handlers. The following HTML code shows a Web Form that
has a button with the ID attribute Button1, and the runat="server" attribute
indicates that the Click event for the button will be handled on the server.

[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

Creating a Server-Side Event Handler in Visual C#


In Visual C#, you add the event handler to the event property of the control. The
following HTML code shows a Web Form that has a button with the ID attribute
Button1, and the click event for the button that will be handled on the server.

[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

Demonstration: How to Create Server-Side Event Handlers

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";

7. View the event handler wiring up.


• In the Visual Basic programming language, notice the Handles statement
in the Button1_Click event handler.

[Visual Basic]
Protected Sub Button1_Click(ByVal sender As Object,
ByVal e As System.EventArgs) Handles Button1.Click

• In the Visual C# programming language, the procedure is bound to the


event handler by adding the attribute onclick to the markup. You can view
the following code from the Source view of the Default.aspx Web Form.

[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

9. Trigger the event handler by using the Button control.


• In the http://localhost:49157/WebSite1/Default.aspx - Internet Explorer
window, click the Button control on the Web Form. Notice that the text of
the label changes.
• In the http://localhost:49157/WebSite1/Default.aspx - Internet Explorer
window, click the Close button.
• In Visual Studio 2010, click the Default.aspx window, and then click
Design.
• In the Default.aspx window, click the Button control.
• In the Properties window of the Button control, change the ID property of
the Button control to SubmitButton.
• In the Default.aspx window, double-click the Button control to open the
code-behind file. Notice that Button1 has been changed to SubmitButton
in the code-behind file.

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.

10. Save and view the Web Form in the browser


• On the File menu, click either Save Default.aspx.vb or
Save Default.aspx.cs.
• In Solution Explorer, right-click the Default.aspx Web Form, and then
click View in Browser.
4-34 Introduction to Web Development with Microsoft® Visual Studio® 2010

11. Trigger the event handler by using the Button control.


• In the http://localhost:49157/WebSite1/Default.aspx - Internet Explorer
window, click the Button control on the Web Form.

Note: Notice that the Click event handler still triggers when you use the new name of
the control.

• In the http://localhost:49157/WebSite1/Default.aspx - Internet Explorer


window, click the Close button.
• In the WebSite1 - Microsoft Visual Studio window, click the Close button.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-35

Working with Web Server Controls by Using Event


Handlers

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.

Reading Properties from a Web Server Control


In a server-side event handler, you can read information from a server control. The
following code contains a form with a Textbox and a Button control.

<form id="form1" runat="server">


<asp:TextBox ID="NameTextBox" runat="server" />
<asp:Button ID="SubmitButton" runat="server" />
</form>

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

The text typed in the NameTextBox control is retrieved by assigning it to the


greetingString variable.

[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”.

Setting Web Server Control Properties


You can output information directly to a Web server control by using the control’s
properties. For example, you may have a Label Web server control on the
ASP.NET page as follows.

<asp:Label ID="GreetingLabel" runat="server" Text="Greeting" />

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";

The reading and setting of control properties in server-side control events is


typically done when some sort of manipulation or calculation of the result must be
performed at the server-side. Otherwise, client-side interaction might be a better
option.
In most cases, page event handlers and server-control event handlers are used in
combination to read from and write to control properties when a page goes
through the page life cycle.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-37

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

• Explain how to create a class in Visual Studio 2010.


• Add member variables and constants to a class.
• Add properties and methods to a class.
• Add class constructors.
• Access components in an ASP.NET Web Form.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-39

What Are Types, Components, and Classes?

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

Types provide functionality in an application. You can use types to organize


functions, and give them a single name by which they are referenced. Types also
have properties and methods. Using properties, you can set the characteristics of a
type, whereas by using methods, you can invoke the actions of a type. When you
want to use a type and its methods, you must instantiate an instance of the type.

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.

Type and Component Sharing


If you build a type that calculates the salary increase that an employee receives, this
calculation is based on numerous formulas that are specific to your organization,
including current base salary, performance rating, and tenure at the company. The
calculations are very complex, and time-consuming to develop. In addition, the
company frequently changes the formula by which salary increases are calculated.
After you create the type, you can use the type with other applications by including
it in a project. For instance, you may have a Windows-based application that the
Human Resources department uses to determine an employee's new salary for the
next paycheck. You can also build a Web application that uses the same type to
allow employees to determine their new salary. You may also have a Windows
Communication Foundation (WCF) service that uses the same type.
By using a type to handle the calculations, you need to create the complicated
algorithm only once. After that, all applications can use the algorithm.
However, in this scenario, reusing the class creates a problem, because you also
need to manage the changes to the class. If one group makes changes to the class
in the application that they are using, these changes are not automatically shared
with other groups of developers. In addition, it is very unlikely that your
organization will share your source code with other organizations. Therefore, you
need to create a component that holds the type. If you create a component that
holds the type, when changes occur, only the type needs to be updated; you do not
have to update the applications that use the type.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-41

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

Changing the Namespace


In Visual C#, the namespace is by default contained in the class file, and you can
change it by editing the file. In Visual Basic, a default namespace for the class is
created with the same name as the project. You can also use the Namespace
keyword in Visual Basic as follows.

[Visual Basic]
Namespace YourComponentNamespace
Public Class Class1
End Class
End Namespace

f To change the project namespace name in Visual Basic


1. In Solution Explorer, right-click the project, and then click Properties.
2. On the Application tab, set the Root namespace to the new name for your
component.

Namespaces provide a logical grouping of classes that all .NET-compatible


development languages can use. Each namespace contains types that you can use
in your application. The namespaces are arranged hierarchically, which helps
reduce naming conflicts and increases the reusability of code. All namespaces
provided by Microsoft begin with either Microsoft or System, such as
Microsoft.VisualBasic or System.Web.
The following are important concepts that will be described in the coming
modules and lab exercises:
• Property: Specifies the objects behavior.
• Constructor: Initializes an object upon creation.
• Backing Fields: Also known as member variables, they provide the storage for
the properties.
• Methods: Used to perform actions upon the data in the contained type.
4-44 Introduction to Web Development with Microsoft® Visual Studio® 2010

Demonstration: How to Create a Class in Visual Studio 2010

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

d. In Solution Explorer, right-click Solution ‘WebSite1’ (1 Project), point to


Add, and then click New Project.
e. In the Add New Project dialog box, in the left pane, click either Visual
Basic or Visual C#, in the middle pane, click Class Library, in the Name
box, type HelloWorld, and then click OK.

Note: Notice that a default class (either Class1.vb or Class1.cs), is created in Solution
Explorer and opens in the Code editor window.

2. Rename the Class1.vb or Class1.cs file as Hello.vb or Hello.cs.


a. In Solution Explorer, right-click either Class1.vb or Class1.cs, click
Rename, change the text to Hello.vb or Hello.cs, and then press ENTER.
b. In the Microsoft Visual Studio message box, click Yes.
3. Create a method that returns a string on the Class file.
• Create a SayHello method that returns a string by using the following
code.

[Visual Basic]
Function SayHello() As String
Return "Hi from Visual Basic component."
End Function

[Visual C#]
public string SayHello()
{
return "Hi from C# component.";
}

4. Build the Class Library project.


• On the Build menu of Visual Studio 2010, click Build Solution.
4-46 Introduction to Web Development with Microsoft® Visual Studio® 2010

5. Add a reference to the HelloWorld Class Library project.


a. In Solution Explorer, right-click C:\...\WebSite1\, add then click Add
Reference.
b. On the Projects tab of the Add Reference dialog box, under
ProjectName, ensure that HelloWorld is selected, and then click OK.
c. In Solution Explorer, in the Bin folder, verify that the HelloWorld.dll
assembly has been copied.
d. In the WebSite1 - Microsoft Visual Studio window, click the Close button.
e. In the Microsoft Visual Studio message box, click Yes.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-47

Adding Member Variables and Constants to a Class

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

When adding groups of code to a class—especially if a group or block of code is


long—often it is preferred to enclose it in a region, which can be collapsed and
expanded as necessary. You create a region by using the keywords Region/region
followed by End Region/endregion. You need to prefix the region with a hash-sign
(#), as shown in the following example.

[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.

Question: What are member variables and constants?


4-50 Introduction to Web Development with Microsoft® Visual Studio® 2010

Adding Properties and Methods to a Class

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.

Adding the Methods for a Class


Many classes need at least one method for performing operations on the data
within the class. You can use the properties for this, but that is neither the intent
nor a best practice. The following examples show a single method for the
Customer class.

[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.

The distinction between properties and methods is important, and should be


reflected in how they are named, such as Name for property, and GetName for a
method. You should generally prefix a method with a verb.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-55

Adding Class Constructors

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

Public Sub New(ByVal id As Guid?)


' Initialize member backing fields with passed values
Me.ID = id
End Sub

[Visual C#]
/// <summary>
/// Default parameterless constructor
/// </summary>
public Customer()
{
// Initialize member backing fields with default values
this.ID = Guid.NewGuid();
}

public Customer(Guid? id)


{
// Initialize member backing fields with passed values
this.ID = id;
}

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

Accessing Components in an ASP.NET Web Form

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.

Referencing the DLL


Before you can use the types in a component, you must first add a reference to the
component project.
4-58 Introduction to Web Development with Microsoft® Visual Studio® 2010

f To add a reference to the component project


If your solution contains both the Web application and the component project,
you can add a reference to the project.
1. Open Visual Studio 2010.
2. On the File menu, click Open Project.
3. In the Open Project dialog box, in the Name box, type
D:\Labfiles\Starter\M4\VB\CustomerManagement.sln.
4. In Solution Explorer, right-click D:\Labfiles\Starter\M4\VB
\CustomerManagement, and then click Add Reference.
5. In the Add Reference dialog box, on the Projects tab, double-click the
required class library project, and then click OK.
The component is added to the References folder in Solution Explorer. The
reference makes the namespace of the component accessible to the
application.

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.

f To add a reference to the component DLL


1. Open your project in Visual Studio 2010.
2. In Solution Explorer, right-click the project, and then click Add Reference.
3. In the Add Reference dialog box, view the following tabs:
• .NET. Displays components that are part of both the .NET Framework
class library and other registered components.
• COM. Displays COM DLLs that have been registered on your computer.
• Project. Displays a list of all reusable components that were created from
local projects.
• Browse. If a component has not been registered as a .NET or COM
component, you can browse to where the component is located.
• Recent. Displays a list of components recently added to projects on your
computer.
Adding Functionality to a Microsoft® ASP.NET Web Form 4-59

4. Select the required component, and then click OK.


The component is added to the References folder (WAP) or Bin folder (WSP)
in Solution Explorer. The reference makes the namespace of the component
accessible to the application.

Instantiating the Object


After you add a reference to the component, you can instantiate the class object.
The following code lines declare a new variable named currentCustomer, of the
class Customer, in the ComponentNamespace namespace.

[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

Accessing the Object


After the object is instantiated, you can use it like any other object in your project.
All of the public properties and methods in the class are available for use. For
example, the following code passes one parameter to the GetTotalOrderAmount
function of the Customer class, and assigns the returned value to the total
variable.

[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

Page Event Life Cycle

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.

Page Event Life Cycle


The page event life cycle includes the following page events, which occur in the
following order:
1. Page_Init. Occurs after all controls have been initialized.
2. Page_Load. Occurs after the initialization of the controls and loading of all
controls.
3. Page_LoadComplete. Occurs after all the controls on the page have been
loaded. You can use this event to refer to values or assign values to all controls.
4-64 Introduction to Web Development with Microsoft® Visual Studio® 2010

4. Control events. Consist of change events (for example, Textbox1_Changed)


and action events (for example, Button1_Click).
5. Page_Unload. Occurs when the page is closed or when the control is passed
to another page.

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

The PostBack Process

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.

The Page.IsPostBack Property


Because the Page_Load event runs with every request for a page, all the code in the
Page_Load event will run each time the page is requested. However, if you use
postback events, all the code need not run again. You can use the Page.IsPostBack
property to ensure that the code runs only when the page is initially requested. The
following examples illustrate this.
4-68 Introduction to Web Development with Microsoft® Visual Studio® 2010

[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load

If Not Page.IsPostBack Then


' Executes only on initial page load.
End If

' This code executes on every request.


...
End Sub

[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Executes only on initial page load.
}

// This code executes on every request.


...
}
Adding Functionality to a Microsoft® ASP.NET Web Form 4-69

Demonstration: How to Handle Page Events

Key Points
In this demonstration, you will view the order of the page events, including the
event handlers and the page output.

Demonstration Steps

f To view the simple code and event handler


1. Open the EventOrder solution from the D:\Demofiles\M4\VB or
D:\Demofiles\M4\CS folder.
2. Run the Web application.
3. Switch to Visual Studio 2010, and view the simple code and the Page_Unload
event handler.
4. Switch to Internet Explorer, and check the Postback event.
4-70 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Note: The EventOrder.sln solution file in the D:\Demofiles\M4\CS or


D:\Demofiles\M4\VB folder contains a complete solution for this demonstration.

f To view the order of page events


1. Open the EventOrder solution from the D:\Demofiles\M4\VB or
D:\Demofiles\M4\CS folder.
• On the Start menu of 10267A-GEN-DEV, point to All Programs,
click Microsoft Visual Studio 2010, and then click Microsoft Visual
Studio 2010.
• On the File menu of Visual Studio 2010, click Open Project.
• In the Open Project dialog box, in the File name, type either
D:\Demofiles\M4\CS\EventOrder.sln or
D:\Demofiles\M4\VB\EventOrder.sln, and then click Open.
2. Run the Web application.
• On the Debug menu of Visual Studio 2010, click Start Without
Debugging.

Note: In the http://localhost:49241/EventOrder/ - Internet Explorer window, notice that


all the events have output to the label on the left.

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

• In the Default.aspx.vb or Default.aspx.cs window, show the simple code


and the Page_Unload event handler, which also outputs to the label, but
is not shown on the rendered page because the output rendering is
completed at this stage.

[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";
}

4. Switch to Internet Explorer, and check the Postback event.


a. Click the Internet Explorer taskbar button in the taskbar.
b. In the http://localhost:49241/EventOrder/ - Internet Explorer window,
click the Postback button.
c. In the EventOrder - Microsoft Visual Studio window, click the Close
button.
d. In the http://localhost:49241/EventOrder/default.aspx - Internet Explorer
window, click the Close button.

Question: Describe the use of the Events button in the Properties window.
4-72 Introduction to Web Development with Microsoft® Visual Studio® 2010

Lab: Adding Functionality to a Microsoft


ASP.NET Web Form

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

Section 1: Visual Basic


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.

2. Open the code-behind file for an existing Web Form.

f Task 1: Open an existing Web site


• Log on to 10267A-GEN-DEV virtual machine as Student, with the password
Pa$$w0rd.
• Open Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M4\VB folder.

f Task 2: Open the code-behind file for an existing Web Form


• Open the code-behind file of the InsertCustomer Web Form, by using the
View Code context menu command.

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

Exercise 2: Creating Event Procedures


The main tasks for this exercise are as follows:
1. Create an event procedure for the Click event of the Insert button.
2. Create an event procedure for the Click event of the Cancel button.
3. Create an event procedure for the Page_Load event.
4. Create an event procedure for the Page_LoadComplete event.
5. Create an event procedure for the Page_Unload event.

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

f Task 3: Create an event procedure for the Page_Load event


• Create an event procedure for the Page_Load event.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Me.Load

End Sub

f Task 4: Create an event procedure for the Page_LoadComplete event


• Create an event procedure for the Page_LoadComplete event.

Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Me.LoadComplete

End Sub

f Task 5: Create an event procedure for the Page_Unload event


• Create an event procedure for the Page_Unload event.

Protected Sub Page_Unload(ByVal sender As Object, ByVal e As


System.EventArgs) Handles Me.Unload

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

Exercise 3: Creating an Entity Component


The main tasks for this exercise are as follows:
1. Create an entity component.
2. Add the class member fields
3. Add the properties.
4. Add the constructors.
5. Reference CustomerManagementEntities project from CustomerManagement
project.
6. Add a customer member declaration.

f Task 1: Create an entity component


• Create the CustomerManagementEntities class library project by using the
Class Library project item in the Add New Project dialog box. Place the new
project in the D:\Labfiles\Starter\M4\VB folder.

Note: Notice that the CustomerManagementEntities class library project is added to


the solution.

• Rename the default class file Class1.vb, to Customer.vb.

f Task 2: Add the class member fields


• In the Customer class, add a region named Class member fields, just below
the class declaration.

#Region "Class member fields"


#End Region

• 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.

Private customerFirstName As String = Nothing


Adding Functionality to a Microsoft® ASP.NET Web Form 4-79

• 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.

Private customerLastName As String = 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.

Private customerAddress As String = Nothing

• Append the remaining backing fields by using a code snippet named


Customer class backing fields. The code snippet has been supplied by the
senior developer, and is placed in the My Code Snippets folder. Place the
cursor on and right-click the line following the declaration of the
customerAddress backing field, and insert the snippet by clicking Insert
Snippet.

Private customerZipCode As String = Nothing


Private customerCity As String = Nothing
Private customerState As String = Nothing
Private customerCountryID As Guid? = Nothing
Private customerPhone As String = Nothing
Private customerEmailAddress As String = Nothing
Private customerWebAddress As String = Nothing
Private customerCreditLimit As Integer = 0
Private customerNewsSubscriber As Boolean = False
Private customerCreatedDate As DateTime? = Nothing
Private customerCreatedBy As String = Nothing
Private customerModifiedDate As DateTime? = Nothing
Private customerModifiedBy As String = Nothing

f Task 3: Add the properties


• In the Customer class, add a region named Properties, below the Class
member fields region.

#Region "Properties"
#End Region
4-80 Introduction to Web Development with Microsoft® Visual Studio® 2010

• In the Customer class, within the Properties region, append an auto-


implemented public property named ID, of nullable type Guid.

''' <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

Set(ByVal value As String)


' Null value?
If Value Is Nothing Then
Me.customerFirstName = String.Empty
Else
' Only get the first 50 characters
If (Value.Length > 50) Then
Me.customerFirstName = value.Substring(0, 50)
Else
Me.customerFirstName = value
End If
End If
End Set
End Property
Adding Functionality to a Microsoft® ASP.NET Web Form 4-81

• 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

Set(ByVal value As String)


' Null value?
If value Is Nothing Then
Me.customerLastName = String.Empty
Else
' Only get the first 30 characters
If (value.Length > 30) Then
Me.customerLastName = value.Substring(0, 30)
Else
Me.customerLastName = value
End If
End If
End Set
End Property
4-82 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, 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

Set(ByVal value As String)


' Null value?
If value Is Nothing Then
Me.customerAddress = String.Empty
Else
' Only get the first 50 characters
If (value.Length > 50) Then
Me.customerAddress = value.Substring(0, 50)
Else
Me.customerAddress = value
End If
End If
End Set
End Property
Adding Functionality to a Microsoft® ASP.NET Web Form 4-83

• Append the remaining properties within the Properties region, by using a


code snippet named Customer class properties. The code snippet has been
supplied by the senior developer, and is placed in the My Code Snippets
folder. Place the cursor on and right-click the line following the declaration of
the Address property, and insert the snippet by clicking Insert Snippet.

''' <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>

(Code continued on the following page.)


4-84 Introduction to Web Development with Microsoft® Visual Studio® 2010

Public Property City() As String


Get
Return Me.customerCity
End Get
Set(ByVal value As String)
' Null value?
If value Is Nothing Then
Me.customerCity = ""
Else
' Only get the first 30 characters
If (value.Length > 30) Then
Me.customerCity = value.Substring(0, 30)
Else
Me.customerCity = value
End If
End If
End Set
End Property

''' <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

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-85

''' <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>

(Code continued on the following page.)


4-86 Introduction to Web Development with Microsoft® Visual Studio® 2010

Public Property EmailAddress() As String


Get
Return Me.customerEmailAddress
End Get
Set(ByVal value As String)
If (value Is Nothing) Then
Me.customerEmailAddress = ""
Else
' Only get the first 50 characters
If (value.Length > 50) Then
Me.customerEmailAddress = value.Substring(0, 50)
Else
Me.customerEmailAddress = value
End If
End If
End Set
End Property

''' <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

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-87

''' <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>

(Code continued on the following page.)


4-88 Introduction to Web Development with Microsoft® Visual Studio® 2010

Public Property CreatedDate() As DateTime?


Get
Return Me.customerCreatedDate
End Get
Private Set(ByVal value As DateTime?)
' Date in the past?
If (value < DateTime.Now) Then
Me.customerCreatedDate = DateTime.Now
Else
Me.customerCreatedDate = value
End If
End Set
End Property

''' <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>

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-89

Public Property ModifiedDate() As DateTime?


Get
Return Me.customerModifiedDate
End Get
Set(ByVal value As DateTime?)
' Date in the past?
If value < DateTime.Now Then
Me.customerModifiedDate = DateTime.Now
Else
Me.customerModifiedDate = value
End If
End Set
End Property

''' <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

f Task 4: Add the constructors


• In the Customer class, add a region named Constructors below the
Properties region.

#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

• Append the remaining properties within the Constructors region by using a


code snippet named Customer class constructors. The code snippet has been
supplied by the senior developer, and is placed in the My Code Snippets
folder. Place the cursor on and right-click the line following the default
parameterless constructor, and insert the snippet by clicking Insert Snippet.

''' <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>

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-91

''' <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>
''' <remarks></remarks>
Public Sub New(ByVal id As Guid?, ByVal firstName As String, ByVal
lastName As String,
ByVal address As String, ByVal zipCode As String, ByVal city
As String, ByVal state As String,
ByVal countryID As Guid?, ByVal phone As String, ByVal
emailAddress As String,
ByVal webAddress As String, ByVal creditLimit As Integer,
ByVal newsSubscriber As Boolean,
ByVal createdDate As DateTime?, ByVal createdBy As String,
ByVal modifiedDate As DateTime?,
ByVal modifiedBy As String)

' Initialize member backing fields with passed values


Me.ID = id
Me.FirstName = firstName
Me.LastName = lastName
Me.Address = address
Me.ZipCode = zipCode
Me.City = city
Me.State = state
Me.CountryID = countryID
Me.Phone = phone
Me.EmailAddress = emailAddress
Me.WebAddress = webAddress
Me.CreditLimit = creditLimit
Me.NewsSubscriber = newsSubscriber

If Not createdDate Is Nothing Then


Me.CreatedDate = createdDate
Else
Me.CreatedDate = DateTime.Now
End If

Me.CreatedBy = createdBy
Me.ModifiedDate = modifiedDate
Me.ModifiedBy = modifiedBy
End Sub

• Save the changes to Customer.vb.


• Build the component, and fix any errors.
4-92 Introduction to Web Development with Microsoft® Visual Studio® 2010

f Task 5: Reference CustomerManagementEntities project from


CustomerManagement project
• Add a reference to the CustomerManagement project by using the Add
Reference dialog box. Reference the CustomerManagementEntities project
from the CustomerManagement project.

f Task 6: Add a customer member declaration


• Open the InsertCustomer.aspx.vb file.
• In the InsertCustomer.aspx.vb code window, add a private class member
declaration of the Customer class in the CustomerManagementEntities
namespace, named currentCustomer, and initialize to Nothing.

Private currentCustomer As CustomerManagementEntities.Customer =


Nothing

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

Exercise 4: Handling Page and Control Events


The main tasks for this exercise are as follows:
1. Instantiate the Customer object.
2. Populate the UI controls.
3. Destroy the objects.
4. Handle the user cancellation.
5. Save the customer information.

f Task 1: Instantiate the Customer object


• Instantiate the Customer object by using the following code.

''' <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

• Appending the following code to the InsertCustomer class.

''' <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

f Task 2: Populate the UI controls


• In the InsertCustomer class, populate the server controls in the UI by using
the values from the private Customer object currentCustomer.

''' <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

f Task 3: Destroy the objects


• In the InsertCustomer class, destroy the objects used in the class that are not
automatically handled by the garbage collector.

''' <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

f Task 4: Handle the user cancellation


• In the InsertCustomer class, handle user cancellation by redirecting to the
home page.

''' <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

f Task 5: Save the customer information


• In the InsertCustomer class, prepare for saving the customer input
information to persistent storage when the user clicks the Insert button.

''' <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

• Save the changes to InsertCustomer.aspx.vb.


• Build the solution and fix any errors.
• Close Visual Studio 2010.

Note: Notice that the validation successfully completes.

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.

2. Open the code-behind file for an existing Web Form.

f Task 1: Open an existing Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M4\CS folder.

f Task 2: Open the code-behind file for an existing Web Form


• Open the code-behind file of the InsertCustomer Web Form, by using the
View Code context menu command.

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

Exercise 2: Creating Event Procedures


The main tasks for this exercise are as follows:
1. Create an event procedure for the Click event of the Insert button.
2. Create an event procedure for the Click event of the Cancel button.
3. Create an event procedure for the Page_LoadComplete event.
4. Create an event procedure for the Page_Unload event.

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

f Task 3: Create an event procedure for the Page_LoadComplete event


protected void Page_LoadComplete(object sender, EventArgs e)
{

f Task 4: Create an event procedure for the Page_Unload event


protected void Page_Unload(object sender, EventArgs e)
{

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

Exercise 3: Creating an Entity Component


The main tasks for this exercise are as follows:
1. Create an entity component.
2. Add the class member fields.
3. Add the properties.
4. Add the constructors.
5. Reference CustomerManagementEntities project from CustomerManagement
project.
6. Add a customer member declaration.

f Task 1: Create an entity component


• Create the CustomerManagementEntities class library project by using the
Class Library project item in the Add New Project dialog box. Place the new
project in the D:\Labfiles\Starter\M4\CS folder.

Note: Notice that the CustomerManagementEntities class library project is added to


the solution.

• Rename the default class, Class1.cs, file as Customer.cs.

f Task 2: Add the class member fields


• In the Customer class, add a region named Class member fields, just below
the class declaration.

#region Class member fields


#endregion

• 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.

private string customerFirstName = null;


Adding Functionality to a Microsoft® ASP.NET Web Form 4-103

• 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.

private string customerLastName = 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.

private string customerAddress = null;

• Append the remaining backing fields by using a code snippet named


Customer class backing fields. The code snippet has been supplied by the
senior developer, and is placed in the My Code Snippets folder. Place the
cursor on and right-click the line following the declaration of the
customerAddress backing field, and insert the snippet by clicking Insert
Snippet.

private string customerZipCode = null;


private string customerCity = null;
private string customerState = null;
private Guid? customerCountryID = null;
private string customerPhone = null;
private string customerEmailAddress = null;
private string customerWebAddress = null;
private int customerCreditLimit = 0;
private bool customerNewsSubscriber = false;
private DateTime? customerCreatedDate = null;
private string customerCreatedBy = null;
private DateTime? customerModifiedDate = null;
private string customerModifiedBy = null;
4-104 Introduction to Web Development with Microsoft® Visual Studio® 2010

f Task 3: Add the properties


• In the Customer class, add a region named Properties, below the Class
member fields region.

#region Properties
#endregion

• In the Customer class, within the Properties region, append an auto-


implemented public property named ID, of nullable type Guid.

/// <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

• Append the remaining properties within the Properties region, by using a


code snippet named Customer class properties. The code snippet has been
supplied by the senior developer, and is placed in the My Code Snippets
folder. Place the cursor on and right-click the line following the declaration of
the Address property, and insert the snippet by clicking Insert Snippet.

/// <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

(Code continued on the following page.)


4-108 Introduction to Web Development with Microsoft® Visual Studio® 2010

// Only get the first 30 characters


if (value.Length > 30)
this.customerCity = value.Substring(0, 30);
else
this.customerCity = value;
}
}

/// <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;
}
}

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-109

/// <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;
}
}

(Code continued on the following page.)


4-110 Introduction to Web Development with Microsoft® Visual Studio® 2010

/// <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;
}
}

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-111

/// <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;
}

(Code continued on the following page.)


4-112 Introduction to Web Development with Microsoft® Visual Studio® 2010

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;
}

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-113

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;
}
}

f Task 4: Add the constructors


• In the Customer class, add a region named Constructors, below the
Properties region.

#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

• Append the remaining properties within the Constructors region by using a


code snippet named Customer class constructors. The code snippet has been
supplied by the senior developer, and is placed in the My Code Snippets
folder. Place the cursor on and right-click the line following the default
parameterless constructor, and insert the snippet by clicking Insert Snippet.

/// <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)

(Code continued on the following page.)


Adding Functionality to a Microsoft® ASP.NET Web Form 4-115

{
// 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;
}

• Save the changes to Customer.cs.


• Build the component, and fix any errors.

f Task 5: Reference CustomerManagementEntities project from


CustomerManagement project
• Add a reference to the CustomerManagement project by using the Add
Reference dialog box. Reference the CustomerManagementEntities project
from the CustomerManagement project.
4-116 Introduction to Web Development with Microsoft® Visual Studio® 2010

f Task 6: Add a customer member declaration


• Open the InsertCustomer.aspx.cs file.
• In the InsertCustomer.aspx.cs code window, add a private class member
declaration of the Customer class in the CustomerManagementEntities
namespace named currentCustomer, and initialize to null.

private CustomerManagementEntities.Customer currentCustomer =


null;

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

Exercise 4: Handling Page and Control Events


The main tasks for this exercise are as follows:
1. Instantiate the Customer object.
2. Populate the UI controls.
3. Destroy the objects.
4. Handle the user cancellation.
5. Save the customer information.

f Task 1: Instantiate the Customer object


• Instantiate the Customer object by using the following code.

/// <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

• Append the following code to the InsertCustomer class.

/// <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

f Task 2: Populate the UI controls


• In the InsertCustomer class, populate the server controls in the UI by using
the values from the private Customer object, currentCustomer.

/// <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

f Task 3: Destroy the objects


• In the InsertCustomer class, destroy the objects used in the class that are not
automatically handled by the garbage collector.

/// <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;
}

f Task 4: Handle the user cancellation


• In the InsertCustomer class, handle user cancellation by redirecting to the
home page.

/// <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

f Task 5: Save the customer information


• In the InsertCustomer class, prepare to save the customer input information
to persistent storage when the user clicks the Insert button.

/// <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;
}

• Save the changes to InsertCustomer.aspx.cs.


• Build the solution, and fix any errors.
• Close Visual Studio 2010.

Note: Notice that the validation successfully completed.

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

Review Questions and Answers


1. How can you run code only, when a Web page loads for the first time?
2. What is the default event procedure for common controls?
3. How can you add items to a list in Design view?
4-124 Introduction to Web Development with Microsoft® Visual Studio® 2010

Module Review

Review Questions and Answers


1. What is the advantage of code-behind files when you add functionality to a
Web Form?
2. How is an event procedure associated with the event of a server control?
3. How can you use a component in your Visual Studio 2010 project?
Adding Functionality to a Microsoft® ASP.NET Web Form 4-125

Real-World Issues and Scenarios


1. You want to be able to have a designer work on a Web Form simultaneously
while a developer works on the code for the Web Form. What is the easiest
way to implement this?
Use a Web Form with a code-behind file.
2. You want to add page events to a code-behind file, but you do not want to
manually have to wire up the event handlers. What is the easiest way to
implement this?
Specify a value of true for the AutoEventWireUp attribute of the Page
directive.

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

• Describe content pages.


• Create a content page.
• Describe nested master pages.
• Describe the runtime behavior of master pages.
• Add a master page to an existing Web application project.
• Describe the advantages of master pages.
Module 5: Implementing Master Pages and User Controls 5-5

What Are Master Pages?

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.

Master Page Features


The file extension for a master page is changed from .aspx to .master.aspx—for
example, MasterPage.master. The Master directive is used instead of the Page
directive, as follows.

[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

Creating a Master Page

Creating a Master Page


To create a master page, you need to perform the following steps:
1. In Solution Explorer, right-click the project, and then click Add New Item.
2. In the Add New Item dialog box:
a. In the left pane, click Visual Basic or Visual C#.
b. In the middle pane box, click Master Page.
c. In the Name box, type a name for the master page.
d. Select the Place code in a separate file check box, if you want to use a
code-behind file.
e. Select the Select master page check box, if you want to nest the master
page.
f. Click Add.
Module 5: Implementing Master Pages and User Controls 5-9

Setting the Layout of a Master Page


The master page defines how the pages in your site look. It can contain any
combination of static text and controls. A master page also contains one or more
content placeholders that designate where dynamic content will appear when
pages are displayed.
In this example, you will use a table to help you position elements on the page.
You will start by creating a layout table to hold the master page elements. You will
then position the content placeholder control that is already on the page.

X Create a layout table for the master page


To create a layout table for the master page, perform the following steps:
1. Switch to Design view.
2. From the drop-down list at the top of the Properties window, select
DOCUMENT, and then in the DOCUMENT list, click a background
distinctive color in the BgColor box. The color you select is not important.
3. Click the page where you want to place the layout table, such as in a div
element.
4. On the Table menu, click Insert Table.
5. In the Insert Table dialog box, in the Rows box, type 3, and then click OK.
The template defines the arrangement of rows and cells in the table. The
template that you have selected creates three rows, and two cells/columns.
6. In the Properties window, apply the following settings:
• In the middle row, click the leftmost column, and set its Width to 48.
• Click the top row, and set its Height to 48.
• Click the bottom row, and set its Height to 48.
7. Select all cells in the table, set BgColor to a different color other than the
background color, and then set valign to top.

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.

Question: What is the main purpose of creating master pages?


5-10 Introduction to Web Development with Microsoft® Visual Studio® 2010

What Are Content Pages?

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.

Content Page Features


You can reference a master page by using the MasterPageFile attribute in the Page
directive of the content page, as indicated in the follow examples.

[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.

<pages masterPageFile="MasterPage.master" />

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

Creating a Content Page

Creating a Content Page


To create a content page, you perform the following steps:
1. Open the CustomerManagement.sln file from the D:\Labfiles\Starter\M5\VB
folder.
2. In Solution Explorer, right-click D:\Labfiles\Starter\M5\VB
\CustomerManagement, and then click Add New Item.
3. In the Add New Item dialog box, in the left pane, click either Visual Basic or
Visual C#.
4. In the middle pane, click Web Form.
5. In the Name box, type a name for the content page, and then select the Place
code in a separate file check box, to use a code-behind file.
6. Select the Select master page check box, and then click Add.
7. In the Select a Master Page dialog box, click the master page, and then click
OK.
5-14 Introduction to Web Development with Microsoft® Visual Studio® 2010

The ContentPlaceHolder controls on the specified master page are automatically


referenced by using the Content controls on the new content page, as follows.

[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>

Unlike nested master pages, you cannot specify a new ContentPlaceHolder


control in a content page. Nested master pages are covered in the next topic, but
essentially, a nested master page is when one master page is based on another
master page.

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

What Are Nested Master Pages?

Key Points
Master pages can be nested, with one master page referencing another as its
master.

Nesting Master Pages


You can create nested master pages to create parent master pages and child master
pages. The parent master page can define the overall layout of the Web site, and
the child master pages can further define the layout of specific areas of the site. For
example, a large site can contain an overall master page that defines the look and
feel of the site. Partners of the large site can then define their child master pages
that reference the site master, which defines the look and feel for the partner's
content.
Nested master pages reference the parent master by using the MasterPageFile
attribute as part of the Master directive.
5-16 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Nested Master Page Examples


The following examples show a simple nested master page configuration.
Module 5: Implementing Master Pages and User Controls 5-17

This first two examples display the parent master files.

[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

These two examples display the child master files.

[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>

Question: What is the main purpose of using nested master pages?


5-20 Introduction to Web Development with Microsoft® Visual Studio® 2010

Runtime Behavior of Master Pages

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

4. The content of the individual Content controls is merged into the


corresponding ContentPlaceHolder controls on the master page.
5. ASP.NET renders the final merged page to the browser.

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

Adding a Master Page to an Existing Web Application


Project

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

Discussion: Advantages of Master Pages

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

• Easily create a shared header or footer.


• Nest master pages, which allows you fine-grained control over the layout of
each content page, all based on an overall layout.
• Optionally override or keep default content from master pages.
• Make the same change to every page of your application by changing a single
file, which is helpful when managing large applications that contain thousands
of pages.
5-26 Introduction to Web Development with Microsoft® Visual Studio® 2010

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

• Explain how to convert a Web Form to a user control.


• Explain how to convert a Web Form to a user control.
• Explain how to add a user control to a Web Form.
5-28 Introduction to Web Development with Microsoft® Visual Studio® 2010

What Are User Controls?

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.

User Control Features


A user control consists of HTML and code, but because user controls are used by
Web Forms, they do not contain the top-level HTML elements, such as the html,
body, or form elements.
When a Web Form uses a user control, the user control participates in the event
life cycle for the Web Form.
Because a user control is an ASP.NET page, it has its own page logic. For example,
a user control handles its postback event in its Page_Load event handler.

User Controls Code-Behind Files


User controls contain the Control directive, which is the equivalent of the Page
directive that is contained in a Web Form. If you choose to place the code for the
user control in a separate code-behind file, then the Control directive references
the code-behind file. You can include only one Control directive per .ascx file.
The following examples contain the Control directive for a user control named
WebUserControl.

[Visual Basic]

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="WebUserControl.ascx.vb" Inherits="WebUserControl" %>

[Visual C#]

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
5-30 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.”

User Controls, Web Server Controls, and Components


You must be able to distinguish between user controls, Web server controls, and
components. The following table describes the specificities of components and
control.

Components and controls Description

Component A component—also called a class library in Visual


Studio 2010—provides logic only; it does not have a
user interface.

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

Advantages and Disadvantages of Using User Controls

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.

Advantages of User Controls


User controls have numerous functions; for example, you can create headers and
navigation bars, or repeat blocks of code in a Web application project or Web site
project. User controls also offer the following advantages when you develop a Web
application:
• User controls are self-contained. User controls provide separate variable
namespaces, which means that none of the methods and properties of the user
control conflict with any existing methods or properties of the hosting page.
5-32 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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.

Disadvantages of User Controls


User controls come with a few disadvantages when you develop a Web application:
• User interface and code can be duplicated. When sharing a user control
between Web applications, it is difficult to maintain the UI and code, because
if it is generic, you will need to modify all instances of a user control. If the
code for the user control is generic or is not logically abstract, you need to
rewrite or modify the code for each applied usage.
• Code is visible. The code-behind file is visible to anyone who has access to the
deployed Web application, unless you precompile the Web application.

Sharing User Controls


You can share a single user control with all the pages in a Web application.
However, the .aspx pages in one Web application cannot host a user control from
another Web application. To use a user control in multiple Web applications, you
must copy the user control to the virtual root folder of each Web application.
To share controls with multiple Web applications, you can create a Web custom
control, which acts like a shareable user control that you can add to the Toolbox in
a Web application. Web custom controls are more difficult to create than user
controls. This is because, unlike user controls, you cannot create Web custom
controls by using Visual Studio 2010; all development is done through code only.
To create a Web custom control, you create a class that derives from the Control or
WebControl class.
Module 5: Implementing Master Pages and User Controls 5-33

Converting a Web Form to a User Control

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.

Converting an Existing Web Form to a User Control


You can easily modify a Web Form to convert it to a user control. The following is
the process for converting a Web Form to a content page:
• Remove all top-level HTML elements from the Web Form, including the html,
head, body, and form elements.
• Change the existing Page directive to a Control directive. Remove all directive
attributes, with the exception of Language, AutoEventWireup (if present),
CodeFile, and Inherits.
5-34 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

• Add a ClassName attribute to the Control directive. The ClassName attribute


enables the user control to be strongly typed when you add it to a page.
• Rename the file to a name that reflects its purpose, and then change the file
extension from .aspx to .ascx. Your Web Form is a user control.

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.

Converting a Code-Behind File into a User Control


You can also convert a code-behind file into a user control by performing the
following steps:
1. Rename the .aspx file so that the file name extension is .ascx.
2. Rename the code-behind file with either of the file name extensions .ascx.vb or
.ascx.cs, depending on which programming language the code-behind file is in.
3. Open the code-behind file, and change the class from which it inherits from
Page to UserControl.
4. In the .ascx file, perform the following steps:
a. Remove the html, body, and form elements from the page.
b. Change the Page directive to a Control directive.
c. Remove all attributes of the Control directive, except Language,
AutoEventWireup (if present), CodeFile, and Inherits.
d. In the Control directive, change the CodeFile attribute to point to the
renamed code-behind file.
5. Include a className attribute in the Control directive. This allows the user
control to be strongly typed when it is added to a page.
Module 5: Implementing Master Pages and User Controls 5-35

Demonstration: How to Convert a Web Form to a User


Control

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" %>

a. In Solution Explorer, right-click InsertCustomer.aspx, and then click


Open.
b. In the InsertCustomer.aspx window, locate the Page directive, and then
change it 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" %>

4. Add a ClassName property with a value of InsertCustomer to the Control


directive.

[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

• In the InsertCustomer.aspx window, add the following code at the end of


the Control directive.

ClassName="InsertCustomer"

5. In the InsertCustomer.aspx window, remove all the top-level HTML elements,


such as the DOCTYPE, html, head, body, title, link, and form elements.

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"

(Code continued on the following page.)


5-38 Introduction to Web Development with Microsoft® Visual Studio® 2010

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"

(Code continued on the following page.)


Module 5: Implementing Master Pages and User Controls 5-39

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" />
&nbsp;<asp:Button ID="CustomerCancelButton" runat="server"
Text="Cancel" />
</div>

[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"

(Code continued on the following page.)


5-40 Introduction to Web Development with Microsoft® Visual Studio® 2010

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"

(Code continued on the following page.)


Module 5: Implementing Master Pages and User Controls 5-41

runat="server" MaxLength="40"></asp:TextBox>
</div>
</div>
<div class="customertablefooter">
</div>
<asp:Button ID="CustomerInsertButton" runat="server"
Text="Insert"
onclick="CustomerInsertButton_Click" />
&nbsp;<asp:Button ID="customerCancelButton" runat="server"
Text="Cancel"
onclick="CustomerCancelButton_Click" />
</div>

6. Save the InsertCustomer.aspx Web Form.


• In the CustomerManagement – Microsoft Visual Studio (Administrator)
window, on the File menu, click Save InsertCustomer.aspx.
7. Rename the Web Form from InsertCustomer.aspx to InsertCustomer.ascx.
a. In Solution Explorer, right-click InsertCustomer.aspx, click Rename,
change the file name to InsertCustomer.ascx, and then press ENTER.
b. In the Microsoft Visual Studio message box, click Yes.
8. Open either the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs user
control code-behind file, and change its base class from System.Web.UI.Page
to System.Web.UI.UserControl.

[Visual Basic]
Partial Class InsertCustomer
Inherits System.Web.UI.UserControl

[Visual C#]
public partial class InsertCustomer : System.Web.UI.UserControl

a. In Solution Explorer, right-click either InsertCustomer.ascx.vb or


InsertCustomer.ascx.cs, and then click Open.
5-42 Introduction to Web Development with Microsoft® Visual Studio® 2010

b. In the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs code window,


locate the InsertCustomer class, and change its property from
System.Web.UI.Page to 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

• In the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs code window, in


the Page_LoadComplete event method, select and right-click the
following code, and then click Cut.

[Visual Basic]
' Populate the UI controls
populateUI()

[Visual C#]
// Populate the UI controls
populateUI();

• In the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs code window,


append the copied code 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();
}

10. In the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs code window, delete


the Page_LoadComplete event method.
11. Build the solution.
• In the CustomerManagement – Microsoft Visual Studio (Administrator)
window, on the Build menu, click Build Solution.
5-44 Introduction to Web Development with Microsoft® Visual Studio® 2010

12. Save and close the user control code-behind file.


a. In the CustomerManagement – Microsoft Visual Studio (Administrator)
window, on the File menu, click Save InsertCustomer.ascx.vb or Save
InsertCustomer.ascx.cs.
b. In the InsertCustomer.ascx.vb or InsertCustomer.ascx.cs code window,
click the Close button.
c. In the InsertCustomer.ascx window, click the Close button.
d. In the CustomerManagement – Microsoft Visual Studio (Administrator)
window click Close button.
Module 5: Implementing Master Pages and User Controls 5-45

Adding a User Control to a Web Form

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.

Including User Controls


You include a user control in an ASP.NET Web Form by using the Register
directive. The following code illustrates this.

<%@ Register src="WebUserControl.ascx" tagname="WebUserControl"


tagprefix="uc1" %>

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

Placing the User Control in a Web Form


After you register the user control by using the Register directive, you can place the
user control tag in the Web Form the same way you would place a Web server
control in a Web Form. The following code adds a user control to a Web Form.

<uc1:WebUserControl ID="WebUserControl1" runat="server" />

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.

Setting Public Properties


If the user control that you have added to the Web Form has public properties,
check if the properties need to be set to initialize the user control. The properties
can be set declaratively in the markup, in the Properties window, or can be
accessed from code.
The following example sets the Name property of the user control to the value
Gregory Weber.

[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.

User Control Example


The following are additional examples that show an ASP.NET Web page that
contains a user control. The user control is in the file Spinner.ascx, in the Controls
folder. On the page, the control is registered to use the prefix uc, and the tag name
Spinner. The user control properties MinValue and MaxValue are set
declaratively.
Module 5: Implementing Master Pages and User Controls 5-47

[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

Lab: Implementing Master Pages and User


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 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:

• Add and apply a master page in a Web application.


• Convert a Web Form to a content page.
• Add navigation to the master page.
• Convert a Web Form into a user control.
• Create a content page.
• Insert a user control on the content page.

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

Section 1: Visual Basic


Exercise 1: Adding and Applying a Master Page
The main tasks for this exercise are as follows:

1. Add a master page to an existing Web site.

2. Initialize the style controls and elements on the master page.

3. Define a ContentPlaceHolder control on the master page.

X Task 1: Add a master page to an existing Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M5\VB folder.
• Add a new master page named Site.master, to the CustomerManagement
Web site.

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.

<head runat="server" id="MainHead">

• In the Site.master window, change the id property of the form element to


MainForm.

<form id="MainForm" runat="server">

• 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.

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />


5-52 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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.

<title>Contoso Customer Management</title>

X Task 3: Define a ContentPlaceHolder control on the master page


• Remove the ContentPlaceHolder from the head element.

<asp:ContentPlaceHolder id="head" runat="server">


</asp:ContentPlaceHolder>

• Change the id property of the ContentPlaceHolder control within the div


element to MainContentPlaceHolder.

<div class="content">
<asp:ContentPlaceHolder id="MainContentPlaceHolder"
runat="server">
</asp:ContentPlaceHolder>

</div>

• Save the master page.

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

Exercise 2: Converting Web Forms to Content Pages and


User Controls
The main tasks for this exercise are as follows:

1. Convert the default Web Form into a content page.

2. Add navigation to the master page.

3. Convert the Web Form into a user control.

4. Create a content page and insert a user control.

X Task 1: Convert the default Web Form into a content page


• Open the Default.aspx Web Form.
• In the Default.aspx window, in the Page directive, add a MasterPageFile
property, with a value of ~/Site.master, by using the following code.

<%@ Page Language="VB" AutoEventWireup="false"


CodeFile="Default.aspx.vb"
Inherits="_Default" MasterPageFile="~/Site.master"%>

• 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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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

• In the Default.aspx window, add a server-side Content control.

<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.

X Task 2: Add navigation to the master page


• Add a breadcrumb to the master page by adding a SiteMapPath control
named MainSiteMapPath, wrapped in a div element with a class attribute
value of siteMapPath. Add the new div element below the existing div
element with a class attribute value of appTitle.

<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>

• Make the menu layout horizontal by applying the Orientation attribute.

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.

<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px"


/>
<StaticHoverStyle BackColor="White" ForeColor="Black" />
<DynamicHoverStyle BackColor="White" ForeColor="Black" />
<DynamicMenuItemStyle ItemSpacing="2px" HorizontalPadding="5px"
VerticalPadding="2px" />
5-56 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add a SiteMapDataSource control named MainSiteMapDataSource to the


master page, after the closing tag of the div element, with a class attribute
value of menu. The SiteMapDataSource control should not show the starting
node.

<asp:SiteMapDataSource ID="MainSiteMapDataSource" runat="server"


ShowStartingNode="false" />

• Format the Site.master master page.


• Add the D:\Labfiles\Starter\M5\web.sitemap site map file to the project.
• Modify the div.menu style, by using the Manage Styles window. The menu
style must have the following definition:
• Category: Position
• position: relative
• z-index: 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.
Module 5: Implementing Master Pages and User Controls 5-57

X Task 3: Convert the Web Form into a user control


• Open the InsertCustomer.aspx Web Form, and change its Page directive to a
Control directive.

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer" %>

• Add a ClassName property with a value of Customer to the Control directive.

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="InsertCustomer.aspx.vb" Inherits="InsertCustomer"
ClassName="Customer" %>

• Change the Inherits property value from InsertCustomer to Customer.

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="InsertCustomer.aspx.vb" Inherits="Customer"
ClassName="Customer" %>

• Change the CodeFile property value from InsertCustomer.aspx.vb to


Customer.aspx.vb.

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="Customer.aspx.vb" Inherits="Customer"
ClassName="Customer" %>

• 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

<%@ Control Language="VB" AutoEventWireup="false"


CodeFile="Customer.ascx.vb" Inherits="Customer"
ClassName="Customer" %>
<div class="customerTable">
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerFirstNameLabel" runat="server"
Text="First Name:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerFirstNameTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerLastNameLabel" runat="server"
Text="Last Name:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerLastNameTextBox"
runat="server"></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="CustomerZipCodeLabel" runat="server"
Text="Zip Code:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerZipCodeTextBox"
runat="server" MaxLength="10"></asp:TextBox>
</div>
</div>

(Code continued on the following page.)


Module 5: Implementing Master Pages and User Controls 5-59

<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>

(Code continued on the following page.)


5-60 Introduction to Web Development with Microsoft® Visual Studio® 2010

<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" />
&nbsp;<asp:Button ID="CustomerCancelButton" runat="server"
Text="Cancel" />
</div>
</div>

• Save the InsertCustomer.aspx Web Form.


• Change the Web Form name from InsertCustomer.aspx to Customer.ascx.
Module 5: Implementing Master Pages and User Controls 5-61

• 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.

Partial Class InsertCustomer


Inherits System.Web.UI.UserControl

• Move the content from the Page_LoadComplete event method, and append it
to the Page_Load event method.

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

• Remove the Page_LoadComplete 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.

X Task 4: Create a content page and insert a user control


• Add a new content page named InsertCustomer.aspx, with a code-behind file
based on the Site.master master page.
• Open the InsertCustomer.aspx content page in the Design view, and drag the
Customer.ascx user control to the MainContentPlaceHolder control.
• Run the CustomerManagement Web application.
• Verify the Contoso Customer Management Web site, by clicking New on the
Customers menu.
5-62 Introduction to Web Development with Microsoft® Visual Studio® 2010

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:

1. Add a master page to an existing Web site.

2. Initialize the style controls and elements on the master page.

3. Define a ContentPlaceHolder control on the master page.

X Task 1: Add a master page to an existing Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M5\CS folder.
• Add a new master page named Site.master, to the CustomerManagement
Web site.

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.

<head runat="server" id="MainHead">

• In the Site.master window, change the id property of the form element to


MainForm.

<form id="MainForm" runat="server">

• 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.

<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />


5-64 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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.

<title>Contoso Customer Management</title>

X Task 3: Define a ContentPlaceHolder control on the master page


• Remove the ContentPlaceHolder from the head element.

<asp:ContentPlaceHolder id="head" runat="server">


</asp:ContentPlaceHolder>

• Change the id property of the ContentPlaceHolder control within the div


element to MainContentPlaceHolder.

<div class="content">
<asp:ContentPlaceHolder id="MainContentPlaceHolder"
runat="server">
</asp:ContentPlaceHolder>

</div>

• Save the master page.

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

Exercise 2: Converting Web Forms to Content Pages and


User Controls
The main tasks for this exercise are as follows:

1. Convert the default Web Form into a content page.

2. Add navigation to the master page.

3. Convert the Web Form into a user control

4. Create a content page and insert a user control.

X Task 1: Convert the default Web Form into a content page


• Open the Default.aspx Web Form.
• In the Default.aspx window, in the Page directive, add a MasterPageFile
property with a value of ~/Site.master, by using the following code.

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs"
Inherits="_Default" MasterPageFile="~/Site.master"%>

• 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.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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

• In the Default.aspx window, add a server-side Content control.

<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.

X Task 2: Add navigation to the master page


• Add a breadcrumb to the master page by adding a SiteMapPath control
named MainSiteMapPath, wrapped in a div element with a class attribute
value of siteMapPath. Add the new div element below the existing div
element with a class attribute value of appTitle.

<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

• Make the menu layout horizontal, by applying the Orientation attribute.

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.

<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px"


/>
<StaticHoverStyle BackColor="White" ForeColor="Black" />
<DynamicHoverStyle BackColor="White" ForeColor="Black" />
<DynamicMenuItemStyle ItemSpacing="2px" HorizontalPadding="5px"
VerticalPadding="2px" />

• Add a SiteMapDataSource control named MainSiteMapDataSource to the


master page, after the closing tag of the div element, with a class attribute
value of menu. The SiteMapDataSource control should not show the starting
node.

<asp:SiteMapDataSource ID="MainSiteMapDataSource" runat="server"


ShowStartingNode="false" />

• Format the Site.master master page.


• Add the D:\Labfiles\Starter\M5\web.sitemap site map file to the project.
• Modify the div.menu style, by using the Manage Styles window. The menu
style must have the following definition:
• Selector: div.menu
• Define in: Styles/Site.css
• Category: Position
5-68 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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.

X Task 3: Convert the Web Form into a user control


• Open the InsertCustomer.aspx Web Form, and change its Page directive to a
Control directive.

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer" %>

• Add a ClassName property with a value of Customer to the Control directive.

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="InsertCustomer.aspx.cs" Inherits="InsertCustomer"
ClassName="Customer" %>

• Change the Inherits property value from InsertCustomer to Customer.

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="InsertCustomer.aspx.cs" Inherits="Customer"
ClassName="Customer" %>
Module 5: Implementing Master Pages and User Controls 5-69

• Change the CodeFile property value from InsertCustomer.aspx.cs to


Customer.aspx.cs.

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="Customer.aspx.cs" Inherits="Customer"
ClassName="Customer" %>

• 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.

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="Customer.ascx.cs" Inherits="Customer"
ClassName="Customer" %>
<div class="customerTable">
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerFirstNameLabel" runat="server"
Text="First Name:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerFirstNameTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerLastNameLabel" runat="server"
Text="Last Name:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerLastNameTextBox"
runat="server"></asp:TextBox>
</div>
</div>

(Code continued on the following page.)


5-70 Introduction to Web Development with Microsoft® Visual Studio® 2010

<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>

(Code continued on the following page.)


Module 5: Implementing Master Pages and User Controls 5-71

<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>

(Code continued on the following page.)


5-72 Introduction to Web Development with Microsoft® Visual Studio® 2010

<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" />
&nbsp;<asp:Button ID="CustomerCancelButton" runat="server"
Text="Cancel" OnClick="CustomerCancelButton_Click" />
</div>
</div>

• Save the InsertCustomer.aspx Web Form.


• Change the Web Form name from InsertCustomer.aspx to Customer.ascx.
• Open the Customer.ascx.cs 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.

public partial class Customer : System.Web.UI.UserControl

• Move the content from the Page_LoadComplete event method, and append it
to the Page_Load event method.

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-73

• Remove the Page_LoadComplete 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.

X Task 4: Create a content page and insert a user control


• Add a new content page named InsertCustomer.aspx, with a code-behind file
based on the Site.master master page.
• Open the InsertCustomer.aspx content page in the Design view, and drag the
Customer.ascx user control to the MainContentPlaceHolder control.
• Run the CustomerManagement Web application.
• Verify the Contoso Customer Management Web site by clicking New on the
Customers menu.

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

1. How will you programmatically attach master pages to an ASP.NET


application?
2. Why did you convert a Web Form into an ASP.NET user control in the lab?
Module 5: Implementing Master Pages and User Controls 5-75

Module Review and Key Takeaways

Review Questions and Answers


1. What is the file extension of a master page?
2. Which attribute overrides any master page setting specified in the web.config
file?
3. What is the file extension of a user control?
4. What are the disadvantages of user controls?
5-76 Introduction to Web Development with Microsoft® Visual Studio® 2010

Real-World Issues and Scenarios


1. You want to create a control that other developers can make changes to
without recompiling the code. What is the easiest way to implement this?
You should implement the controls as a user control.
2. You want to create an overall master page, but you want to dictate two
different types of layouts, based on the overall master page. What is the easiest
way to implement this?
You could create three master pages, with the first being the overall master
page, and the other two being nested master pages, based on the overall
master page.

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

What Is Input Validation?

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.

Verification of Control Values


You can use input validation to compare user input against a predetermined input
format. These predetermined input formats can include the number of characters,
the use of alphanumeric characters, the value range, a specific character string, or a
mathematical formula. For example, a user input control that requests a user
telephone number can have an attached input validation control that verifies that
users have entered numbers only in a specific telephone number format. Entering
letters or too few numbers triggers the input validation control to display an error
message, and requires users to re-enter the data.

Prevention of Page Processing


The server processes user input that matches the predetermined format. User
input that does not match the predetermined format triggers an error message,
and stops server processing. Further processing of the page is blocked until the
user corrects the input to meet the expected format, and resubmits the page
for processing. Server-side processing is not blocked automatically if an input
validation error occurs. Even if scripting has been disabled on the client and the
page is submitted to the server, the Page Load event is triggered. At this stage,
validation has not yet taken place, but it is possible to check if a page is valid—
meaning that all input is valid—by using the Page.Validate method.
Validating User Input 6-7

Protection Against Spoofing and Malicious Code


By running all the validation controls on the server side regardless of client-side
validation, ASP.NET protects against spoofing and malicious code:
• Spoofing. Spoofing occurs when users modify the HTML page that is sent to
them, and then return values that spoof valid data or an authorization check
pass. However, validation is susceptible to spoofing on the client side only,
because users can turn off client-side script by changing browser options and
not running the client-side validation code, which creates a false level of
authorization.

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.

Question: How do ASP.NET validation controls protect against spoofing and


malicious code attacks?
6-8 Introduction to Web Development with Microsoft® Visual Studio® 2010

Client-Side and Server-Side Validation

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

• Combine validation controls.


• Add validation controls to a Web Form.
• Position and configure validation controls on a Web Form.
6-12 Introduction to Web Development with Microsoft® Visual Studio® 2010

Overview of ASP.NET Validation Controls

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.

Validation control Function

RequiredFieldValidator Checks if a value has been entered into a control.


This is the only validation control that requires a
value. All other input validation controls will
accept an empty control as a valid response.

CompareValidator Compares the value in an input control to


another input control, fixed value, data type, or
file. For example, you can use this control to
perform password verification by comparing the
value of one control with another control.

RegularExpressionValidator Verifies that the entry matches a pattern that


has been defined by a regular expression. This
validation control allows you to check for
predictable sequences of characters, such as
those in social security numbers, e-mail addresses,
telephone numbers, and postal codes. Visual
Studio 2010 provides predefined patterns for
common expressions such as telephone numbers
and e-mail addresses.

RangeValidator Verifies that the user input is between two values.


For example, you can use this control to verify
that the user input matches the expected age
range. This control is similar to the
CompareValidator control.

CustomValidator Allows you to write the code to create the


validation expression. For example, you can use
this control to verify that the input value is a
prime number, or matches a value in a database.

ValidationSummary Displays a summary of all of the validation errors


for all the validation controls on the page. This
control is typically placed near the Submit button
to provide immediate feedback on the overall
page input status.
6-14 Introduction to Web Development with Microsoft® Visual Studio® 2010

Basic ASP.NET Validation Controls

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.

The RequiredFieldValidator Control


You can use the RequiredFieldValidator control to force a user to provide input in
an input control. Any character is a valid response with this validation control. No
input or blank spaces are invalid inputs with this control.
The RequiredFieldValidator control is typically used only on input controls that
are required to complete a requested process. For example, you would use a
RequiredFieldValidator control for the user name and password fields on a sign-
in page, but not for incidental information, such as an offer to become a preferred
Web site visitor.
Validating User Input 6-15

An option for the RequiredFieldValidator control is to have an initial value that is


neither an empty string nor blank. It is useful to have an initial value when you
have a default value for an input control, and you want the user to enter a different
value. To require a change to the initial value for the associated input control, set
the InitialValue property to match the initial value of the input control.
In the following markup example, a RequiredFieldValidator control verifies that
the TextBox control NameTextBox does not contain the value Enter your name
when validated. The comparison is case sensitive.

<asp:TextBox id="NameTextBox" runat="server" Text="Enter your name" />

<asp:RequiredFieldValidator id="NameRequiredFieldValidator"
runat="server" ControlToValidate="NameTextBox" InitialValue="Enter
your name" ErrorMessage="You must enter your name" Text="*" />

It is possible to leave a control validated by a RequiredFieldValidator blank, or


leave it with its default or initial value on the client side, while you are working on
the page. Also, the immediate error-checking feedback will not display when the
user fills out the input control and proceeds with the next. However, this changes
when you enter a value in the input. If you clear the input control or reset it to the
initial value, the error message displays immediately when the user completes the
input control.

The CompareValidator Control


You can use the CompareValidator control to test the user’s input against a
specific value, or against a second input control. The CompareValidator control is
often used where the risk of typographic errors is high, such as password fields
that conceal the user's actual input.
The CompareValidator control evaluates an empty input control as valid.
Therefore, if you need to ensure a value, combine the CompareValidator control
with the RequiredFieldValidator control. The CompareValidator control uses the
following common properties:
• ValueToCompare. This property references against a constant value, and is
used to validate against unchanged values, such as a minimum age limit. You
can use the CustomValidator control to compare against values that are likely
to change.
6-16 Introduction to Web Development with Microsoft® Visual Studio® 2010

• ControlToCompare. This property identifies another control to compare the


user input against. You can use this property to check for typographic errors
by having the user enter the same data in two adjacent fields.
If you set both the ValueToCompare and ControlToCompare properties, the
ControlToCompare property takes precedence.
• Type. This property specifies the data type. You can use this property if you
want to compare the value in an input control against one of the
System.String, System.Int32, System.Double, System.DateTime, and
System.Decimal .NET Framework data types. You can do this by specifying
the corresponding value from one of 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.
• Operator. This property specifies the comparison operator to use. Operators
are specified with the name of the comparison operators, such as: Equal,
NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and
DataTypeCheck.

In the following code example, a CompareValidator control verifies that the values
of the two TextBox controls, PasswordTextBox and
PasswordConfirmationTextBox, match.

<asp:TextBox id="PasswordTextBox" runat="server" Text="Enter your


password" TextMode="Password" />
<br />
<asp:TextBox id="PasswordConfirmationTextBox" runat="server"
Text="Confirm your password" TextMode="Password" />

<asp:CompareValidator id="PasswordCompareValidator" runat="server"


ErrorMessage="The entered passwords do not match."
ControlToCompare="PasswordTextBox"
ControlToValidate="PasswordConfirmationTextBox" Text="*" />

The RangeValidator Control


You can use the RangeValidator control to test if an input value is within a given
range. The range measured is inclusive, and both the minimum and maximum
values are considered valid. The RangeValidator control is typically used to verify
that the value entered—for example, age, height, salary, or number of children—
matches the expected range.
Validating User Input 6-17

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.

<asp:TextBox id="AgeTextBox" runat="server" Text="Enter your age" />


<asp:RangeValidator id="AgeRangeValidator" runat="server"
ControlToValidate="AgeTextBox" Type="Integer" MinimumValue="18"
MaximumValue="50" ErrorMessage="Applicants must be between 18 and 50
inclusive." Text="*" />

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

Regular Expression Characters


The following table describes a common set of control characters that you can
use to build your own custom regular expressions, whether used client-side or
server-side.

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.

+ 1 to n literals (at least 1).

[0-n] Integer value range from 0 to n.

{n} Length must be n characters.

| Separates multiple valid patterns.

\ Is a command character.

\w This command character matches any character.

\W This command character matches any non-character.

\d This command character matches any decimal digit.

\D This command character matches any non-digit character.

\. This command character must have a period.


6-20 Introduction to Web Development with Microsoft® Visual Studio® 2010

Example of a Simple Expression


The following markup example demonstrates how you can use a
RegularExpressionValidator control to check if a user has entered a valid e-mail
address.

<asp:TextBox id="EmailTextBox" runat="server" />

<asp:RegularExpressionValidator id="EmailRegexValidator"
runat="server" ControlToValidate="EmailTextBox" ErrorMessage="Use the
format username@organization.xxx" ValidationExpression="\w+@\w+\.\w+"
Text="*" />

The markup looks as follows, when rendered to a browser.

...
<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>

(Code continued on the following page.)


Validating User Input 6-21

<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[

var Page_ValidationActive = false;


if (typeof(ValidatorOnLoad) == "function") {
ValidatorOnLoad();
}

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

\w+ A string of at least one character.

@ An at sign (@).

\w+ A string of at least one character.

\. A period.

\w+ A string of at least one character.

A valid e-mail address for this control is: someone@example.com.


An invalid e-mail address for this control is: someone.com or someone@.com.

Example of a Complex Expression


The default Visual Studio 2010 e-mail regular expression is more complex than the
preceding example. The default e-mail pattern also limits the separation of terms
before and after the at sign (@) to xx.xx or xx-xx.
The default regular expression for e-mail addresses is as follows.

\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.

([-+.]\w+)* Matches one or more hyphens or a period (.), followed by a string of


at least one character.

@ Matches the literal at sign @.


Validating User Input 6-23

(continued)

Character Definition

\w+ Matches a string of at least one character.

([-.]\w+)* Matches a hyphen or period (.), and a string of at least one character.

\. Matches a period (.).

\w+ Matches a string of at least one character.

([-.]\w+)* Matches a hyphen or period (.), and a string of at least one character.

A valid e-mail address for this control is: some-one@example.company.com.


An invalid e-mail address for this control is: some,one@example.company.com.
The RegularExpressionValidator control will evaluate an empty input control as
valid, so if you need to ensure a value, combine the RegularExpressionValidator
control with the RequiredFieldValidator.

Question: For which validation purpose can you use the


RegularExpressionValidator control?
6-24 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Client-Side and Server-Side Validation


The CustomValidator control validates on the server side, but it can also validate
on the client side if the browser supports validation. Unlike the other validation
controls where ASP.NET creates the client and server validation code, you must
write the validation code for the CustomValidator control. You can set the
CustomValidator control as valid or invalid by using the IsValid property of
the args parameter.
Validating User Input 6-25

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.

<asp:CustomValidator ID="NumberCustomValidator" runat="server"


ClientValidationFunction="ClientValidationHandler"
OnServerValidate="ServerValidationHandler"
ControlToValidate="NumberTextBox" ErrorMessage="The number must be
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)

args.IsValid = (args.Value Mod 2 = 0)


End Sub

[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.

Question: When could you use the CustomValidator control?


Validating User Input 6-27

Combining Validation Controls

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

Multiple Validation Controls on a Single Input Control


You can associate multiple validation controls to a single input control. This many-
to-one association of validation controls allows you to check user input for more
than one validation requirement.
The following code examples display a single input control for a telephone
number. A RequiredFieldValidator control checks for content in the input
control, a RegularExpressionValidator control checks the format of the input
control, and a CustomValidator control compares the input with a database of
telephone numbers.
• Input control. The following code defines the TextBox control to validate.

<asp:TextBox id="PhoneTextBox" runat="server" />

• RequiredFieldValidator control. The following code defines the


RequiredFieldValidator control that verifies that there is an input in
PhoneTextBox.

<asp:RequiredFieldValidator id="PhoneRequiredFieldValidator"
runat="server" ErrorMessage="The telephone number is required."
ControlToValidate="PhoneTextBox" Text="*" />

• RegularExpressionValidator control. The following code defines the


RegularExpressionValidator control that verifies that the input in
PhoneTextBox matches the United States telephone number pattern.

<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="*" />

• CustomValidator control. The following code defines the CustomValidator


control that calls the method PhoneServerValidationHandler, which
compares the input in PhoneTextBox with a database of telephone numbers.

<asp:CustomValidator id="PhoneCustomValidator"
OnServerValidate="PhoneServerValidationHandler" runat="server"
ErrorMessage="This telephone number is not recognized"
ControlToValidate="PhoneTextBox" Text="*" />
Validating User Input 6-29

Demonstration: Adding Validation Controls to a Web Form

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 >

• In the Order.aspx window, place the cursor next to the


DueDateRequiredFieldValidator control.
• In the Toolbox, expand Validation, and then double-click
RangeValidator.
Validating User Input 6-31

• In Properties window, in the (ID) box, type DueDateRangeValidator, in


the ControlToValidate list, click DueDateTextBox, and in the Type list,
click Date. In the Text box, type *, in the ErrorMessage box, type The
Due Date must be valid., and then press ENTER.
• In Solution Explorer, right-click Order.aspx, and then click View Code.
• In the Order.aspx.vb or Order.aspx.cs window, in the Page_Load event
handler, append the following code.

[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();

• In the Order.aspx.vb or Order.aspx.cs window, click the Close button.


• In the Microsoft Visual Studio message box, click Yes.
7. Add a RegularExpressionValidator control named
CustomerEmailAddressRegularExpressionValidator for the
CustomerEmailAddressTextBox control, with an asterisk (*) as the error
message, and \w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* as the validation
expression.

<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

• In Properties window, in the (ID) box, type


CustomerEmailAddressRegularExpressionValidator, in the
ControlToValidate list, click CustomerEmailAddressTextBox, and in the
ErrorMessage box, type The Email Address must be valid.. In the Text
box, type *, in the ValidationExpression box, type
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*, and then press ENTER.
8. Add a ValidationSummary control named OrderValidationSummary, below
the two Button controls.

<asp:ValidationSummary ID="OrderValidationSummary"
runat="server"></asp:ValidationSummary>

• In the Order.aspx window, place the cursor next to the


OrderCancelButton TextBox control, and then press ENTER.
• In the Toolbox, expand Validation, and then double-click
ValidationSummary.
• In Properties window, in the (ID) box, type OrderValidationSummary.
9. Save the Order Web Form, and view the changes in the browser.
• In the Validation– Microsoft Visual Studio window, on the File menu,
click Save Order.aspx.
• In Solution Explorer, right-click Order.aspx, and then click View in
Browser.

Note: Notice that today’s date has been added to the Order Date box.

10. Save the order.


• In the Order Entry – Windows Internet Explorer window, click the Save
button.

Note: Notice that there is an asterisk next to the Due Date box, and an error message in
the validation summary at the bottom.

11. Specify an invalid due date, and save the order.


• In the Order Entry – Windows Internet Explorer window, in the Due Date
box, type a date that is 31 days from today’s date, in the format m/d/yyyy,
and then click the Save button.
Validating User Input 6-33

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.

12. Specify a valid due date, and save the order.


• In the Order Entry – Windows Internet Explorer window, in the Due Date
box, type a date that is 30 days or less from today’s date, in the format
m/d/yyyy, and then click the Save button.

Note: Notice that there are no validation errors.

13. Specify an invalid email address and save the order.


• In the Order Entry – Windows Internet Explorer window, in the Email
Address box, type claus@cohowinery, and then click the Save button.

Note: Notice that there is an asterisk next to the Email Address box, and an error
message in the validation summary at the bottom.

14. Specify a valid email address, and save the order.


• In the Order Entry – Windows Internet Explorer window, in the Email
Address box, type claus@cohowinery.com, and then click the Save
button.

Note: Notice that there are no validation errors.

15. Close Windows® Internet Explorer®.


• In the Order Entry – Windows Internet Explorer window, click the Close
button.

Question: Why do validation controls share the same validation properties?


6-34 Introduction to Web Development with Microsoft® Visual Studio® 2010

Positioning and Configuring Validation Controls on a Web


Form

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.

<asp:ValidatorType id="ID of validator" runat="server"


ControlToValidate="ID of control"
ErrorMessage="Error message for error summary"
Display="Static | Dynamic | None"
Text="Text to display next to the input control">
</asp:ValidatorType>
Validating User Input 6-35

ASP.NET input validation controls contain two error message properties—an


ErrorMessage property, and a Text property—both of which can be displayed at
the location of the input validation control. The distinction between these two
error message properties is as follows:
• ErrorMessage. This property is the error message that displays at the location
of a validation control when the validation control is triggered, if the Text
property is not set. This message will also be included in a
ValidationSummary control, if you use one on the Web Form.
• Text. This property is the alternative text that will display at the location of
the validation control when both the ErrorMessage property and Text
property are used and the validation control is triggered. If you use a
ValidationSummary control to collect error messages, you typically use a red
asterisk (*) to the right of the invalid input control to indicate the location of
the error.

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" />

Setting the Display Property


The Display property sets the spacing of error messages from multiple validation
controls on a Web Form. The Display property affects only error messages at the
validation control location. Messages that are displayed in the
ValidationSummary are not affected by the Display property.
6-36 Introduction to Web Development with Microsoft® Visual Studio® 2010

The following table describes the Display property options.

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

Adding the ValidationSummary Control

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

Display Text and Error Messages


The ValidationSummary control can display a message box or a text area, with
a static header and a list of errors. Depending on the value of the DisplayMode
property, you can display the error messages as a bulleted list or as a single
paragraph. You can use the ValidationSummary control for larger forms, which
have a comprehensive form validation process. It is user-friendly to have all the
possible validation errors reported to the user in a single and easily identifiable
manner. ValidationSummary controls are usually placed near the Submit button
so that all the error messages are visible to the user when the input validation
controls are triggered.
The following HTML code example demonstrates a typical ValidationSummary
control.

<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

Programmatically Validating Web Forms

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()

' Is page valid?


If Not Me.IsValid Then
' Loop through validation controls to see which
' generated the error(s)
For Each controlValidator As IValidator In Validators
If controlValidator.IsValid = False Then
...
End If
Next
End If
End If
6-42 Introduction to Web Development with Microsoft® Visual Studio® 2010

[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)
{
...
}
}
}
}

Question: How do you verify if the content of a control or a page is valid?


Validating User Input 6-43

Lab: Validating User Input

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:

• Add validation controls.


• Configure validation controls.
• Add server-side validation.

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

Section 1: Visual Basic


Exercise 1: Adding Validation Controls
The main tasks for this exercise are as follows:

1. Open an existing Web site.

2. Add validation controls to the user control.

f Task 1: Open an existing Web site


• Log on to 10267A-GEN-DEV virtual machine as Student with the password,
Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M6\VB folder.

f Task 2: Add validation controls to the user control


• View the markup of the Customer user control.
• Add a RequiredFieldValidator control named
CustomerFirstNameRequiredFieldValidator, for the
CustomerFirstNameTextBox control.

<asp:RequiredFieldValidator
ID="CustomerFirstNameRequiredFieldValidator"
ControlToValidate="CustomerFirstNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerLastNameRequiredFieldValidator, for the
CustomerLastNameTextBox control.

<asp:RequiredFieldValidator
ID="CustomerLastNameRequiredFieldValidator"
ControlToValidate="CustomerLastNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
Validating User Input 6-47

• Add a RequiredFieldValidator control named


CustomerAddressRequiredFieldValidator, for the
CustomerAddressTextBox control.

<asp:RequiredFieldValidator
ID="CustomerAddressRequiredFieldValidator"
ControlToValidate="CustomerAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerZipCodeRequiredFieldValidator, for the
CustomerZipCodeTextBox control.

<asp:RequiredFieldValidator
ID="CustomerZipCodeRequiredFieldValidator"
ControlToValidate="CustomerZipCodeTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCityRequiredFieldValidator, for the CustomerCityTextBox
control.

<asp:RequiredFieldValidator
ID="CustomerCityRequiredFieldValidator"
ControlToValidate="CustomerCityTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCountryRequiredFieldValidator, for the
CustomerCountryDropDownList control.

<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
6-48 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add a RequiredFieldValidator control named


CustomerWebAddressRequiredFieldValidator, for the
CustomerWebAddressTextBox control.

<asp:RequiredFieldValidator
ID="CustomerWebAddressRequiredFieldValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCreditLimitRequiredFieldValidator, for the
CustomerCreditLimitTextBox control.

<asp:RequiredFieldValidator
ID="CustomerCreditLimitRequiredFieldValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RegularExpressionValidator control named


CustomerEmailAddressRegularExpressionValidator, for the
CustomerEmailAddressTextBox control.

<asp:RegularExpressionValidator
ID="CustomerEmailAddressRegularExpressionValidator"
ControlToValidate="CustomerEmailAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>

• Add a RegularExpressionValidator control named


CustomerWebAddressRegularExpressionValidator, for the
CustomerWebAddressTextBox control.

<asp:RegularExpressionValidator
ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
Validating User Input 6-49

• Add a RangeValidator control named CustomerCreditLimitRangeValidator,


for the CustomerCreditLimitTextBox control.

<asp:RangeValidator ID="CustomerCreditLimitRangeValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
MinimumValue="500" MaximumValue="50000"
ErrorMessage="RangeValidator"></asp:RangeValidator>

• Add a ValidationSummary control named CustomerValidationSummary, for


the CustomerInsertButton control.

<asp:ValidationSummary ID="CustomerValidationSummary"
runat="server"></asp:ValidationSummary>

• Format the Customer.ascx user control.


• Save the Customer user control, and view the changes in the browser.
• Test the functionality of the Customer user control.
• Close Windows® Internet Explorer®.

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

Exercise 2: Configuring Validation Controls


The main tasks for this exercise are as follows:

1. Remove validation from the Cancel button.

2. Add error indicators and error messages to the validation controls.

3. Set the e-mail address and credit limit validation controls.

f Task 1: Remove validation from the Cancel button


• View the default Response.Redirect method of the Cancel button.

''' <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

• Disable the validation caused by the CustomerCancelButton control by


setting the CausesValidation property in the user control to false.

<asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel"


CausesValidation="false" />

• 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

f Task 2: Add error indicators and error messages to the validation


controls
• Add a Text property with the value of * to the
CustomerFirstNameRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerFirstNameRequiredFieldValidator control to The Customer First
Name must be filled in.
• Add a Text property with the value of * to the
CustomerLastNameRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerLastNameRequiredFieldValidator control to The Customer Last
Name must be filled in.
• Add a Text property with the value of * to the
CustomerAddressRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerAddressRequiredFieldValidator control to The Address must be
filled in.
• Add a Text property with the value of * to the
CustomerZipCodeRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerZipCodeRequiredFieldValidator control to The Zip Code must be
filled in.
• Add a Text property with the value of * to the
CustomerCityRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCityRequiredFieldValidator control to The City must be filled in.
• Add a Text property with the value of * to the
CustomerCountryRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCountryRequiredFieldValidator control to A country must be
selected.
• Add a Text property with the value of * to the
CustomerEmailAddressRegularExpressionValidator control.
6-52 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Change the ErrorMessage property in the


CustomerEmailAddressRegularExpressionValidator control to The Email
Address must be valid.
• Add a Text property with the value of * to the
CustomerWebAddressRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerWebAddressRequiredFieldValidator control to The Web Address
must be filled in.
• Add a Text property with the value of * to the
CustomerWebAddressRegularExpressionValidator control.
• Change the ErrorMessage property in the
CustomerWebAddressRegularExpressionValidator control to The Web
Address must be valid.
• Add a Text property with the value of * to the
CustomerCreditLimitRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCreditLimitRequiredFieldValidator control to The Credit Limit
must be filled in.
• Add a Text property with the value of * to the
CustomerCreditLimitRangeValidator control.
• Change the ErrorMessage property in the
CustomerCreditLimitRangeValidator control to The Credit Limit must be
within the valid range.
• Save the Customer user control, and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
in the Email Address box, type contoso.com, press the TAB key, in the Web
Address box, type www.contoso, and then press the TAB key again.

Note: If an AutoComplete message box displays, click No.

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

• In the Contoso Customer Management – Windows Internet Explorer window,


click the Insert button.

Note: Notice the error indicator and error messages next to the First Name, Last Name,
Address, Zip Code, City, Country, and Credit Limit controls.

• Close Windows® Internet Explorer®.

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.

• Close Windows® Internet Explorer®.


• Add a Display property with the value of Dynamic to the
CustomerWebAddressRequiredFieldValidator control to change the display
of the error indicator text.
• Add a Display property with the value of Dynamic to the
CustomerCreditLimitRequiredFieldValidator control to change the display
of the error indicator text.
• Save the Customer user control, and view the changes in the browser.
• Click the Insert button.

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.

• Close Windows® Internet Explorer®.


6-54 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add a ValidationExpression property with the value of


\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* to the
CustomerEmailAddressRegularExpressionValidator control.
• Add a ValidationExpression property with the value of
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* to the
CustomerWebAddressRegularExpressionValidator control.
• Set the Type property with the value of Integer to the
CustomerCreditLimitRangeValidator control.
• Change the MinimumValue property of the
CustomerCreditLimitRangeValidator control to 0.
• Save the Customer user control, and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
in the Email Address box, type claus@contoso.com, in the Web Address
box, type http://www.contoso.com, and then click the Insert button.

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

Exercise 3: Adding Server-Side Validation


The main task for this exercise is to validate the Customer user control.

f Task 1: Validate the Customer User Control


• Open the Customer.ascx.vb code window.
• Add the code to validate the user control within the
CustomerInsertButton_Click event handler method.

''' <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

' Add the current user name


currentCustomer.CreatedBy = Context.User.Identity.Name
' Add the user credit limit
currentCustomer.CreditLimit = 50000
End Sub
6-56 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add postback validation to the Page_Load event handler method.

''' <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()

' Did page validation succeed?


If Not Page.IsValid Then
Return
End If
End If

' Instantiate Customer


instantiateCustomerObject()
' Populate the UI controls
populateUI()
End Sub

• Disable the client-side validation for the CustomerCountryDropDownList


control by setting the EnableClientScript property of the
CustomerCountryRequiredFieldValidator control to false.

<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

• Zip Code: 98052


• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com

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.

• Close Windows® Internet Explorer®.


• Remove the EnableClientScript property for the
CustomerCountryRequiredFieldValidator control to enable the client-side
validation for the CustomerCountryDropDownList control, and format and
save the Customer user control.

<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected."
Text="*"></asp:RequiredFieldValidator>

• In the CustomerManagement – Microsoft Visual Studio window, click the


Close button.

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:

1. Open an existing Web site.

2. Add validation controls to the user control.

f Task 1: Open an existing Web site


• Log on to 10267A-GEN-DEV virtual machine as Student with the password,
Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M6\CS folder.

f Task 2: Add validation controls to the user control


• View the markup of the Customer user control.
• Add a RequiredFieldValidator control named
CustomerFirstNameRequiredFieldValidator, for the
CustomerFirstNameTextBox control.

<asp:RequiredFieldValidator
ID="CustomerFirstNameRequiredFieldValidator"
ControlToValidate="CustomerFirstNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerLastNameRequiredFieldValidator, for the
CustomerLastNameTextBox control.

<asp:RequiredFieldValidator
ID="CustomerLastNameRequiredFieldValidator"
ControlToValidate="CustomerLastNameTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
Validating User Input 6-59

• Add a RequiredFieldValidator control named


CustomerAddressRequiredFieldValidator, for the
CustomerAddressTextBox control.

<asp:RequiredFieldValidator
ID="CustomerAddressRequiredFieldValidator"
ControlToValidate="CustomerAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerZipCodeRequiredFieldValidator, for the
CustomerZipCodeTextBox control.

<asp:RequiredFieldValidator
ID="CustomerZipCodeRequiredFieldValidator"
ControlToValidate="CustomerZipCodeTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCityRequiredFieldValidator, for the CustomerCityTextBox
control.

<asp:RequiredFieldValidator
ID="CustomerCityRequiredFieldValidator"
ControlToValidate="CustomerCityTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCountryRequiredFieldValidator, for the
CustomerCountryDropDownList control.

<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>
6-60 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add a RequiredFieldValidator control named


CustomerWebAddressRequiredFieldValidator, for the
CustomerWebAddressTextBox control.

<asp:RequiredFieldValidator
ID="CustomerWebAddressRequiredFieldValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RequiredFieldValidator control named


CustomerCreditLimitRequiredFieldValidator, for the
CustomerCreditLimitTextBox control.

<asp:RequiredFieldValidator
ID="CustomerCreditLimitRequiredFieldValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator
>

• Add a RegularExpressionValidator control named


CustomerEmailAddressRegularExpressionValidator, for the
CustomerEmailAddressTextBox control.

<asp:RegularExpressionValidator
ID="CustomerEmailAddressRegularExpressionValidator"
ControlToValidate="CustomerEmailAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>

• Add a RegularExpressionValidator control named


CustomerWebAddressRegularExpressionValidator, for the
CustomerWebAddressTextBox control.

<asp:RegularExpressionValidator
ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionV
alidator>
Validating User Input 6-61

• Add a RangeValidator control named CustomerCreditLimitRangeValidator,


for the CustomerCreditLimitTextBox control. The minimum value is 500 and
the maximum value is 50000.

<asp:RangeValidator ID="CustomerCreditLimitRangeValidator"
ControlToValidate="CustomerCreditLimitTextBox" runat="server"
MinimumValue="500" MaximumValue="50000"
ErrorMessage="RangeValidator"></asp:RangeValidator>

• Add a ValidationSummary control named CustomerValidationSummary, for


the CustomerInsertButton control.

<asp:ValidationSummary ID="CustomerValidationSummary"
runat="server"></asp:ValidationSummary>

• Format the Customer.ascx user control.


• Save the Customer user control, and view the changes in the browser.
• Test the functionality of the Customer user control.
• Close Windows® Internet Explorer®.

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

Exercise 2: Configuring Validation Controls


The main tasks for this exercise are as follows:

1. Remove validation from the Cancel button.

2. Add error indicators and error messages to the validation controls.

3. Set the e-mail address and credit limit validation controls.

f Task 1: Remove validation from the Cancel button


• View the default Response.Redirect method of the Cancel button.

/// <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");
}

• Disable the validation caused by the CustomerCancelButton control by


setting the CausesValidation property in the user control to false.

<asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel"


OnClick="CustomerCancelButton_Click" CausesValidation="false" />

• 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

f Task 2: Add error indicators and error messages to the validation


controls
• Add a Text property with the value of * to the
CustomerFirstNameRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerFirstNameRequiredFieldValidator control to The Customer First
Name must be filled in.
• Add a Text property with the value of * to the
CustomerLastNameRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerLastNameRequiredFieldValidator control to The Customer Last
Name must be filled in.
• Add a Text property with the value of * to the
CustomerAddressRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerAddressRequiredFieldValidator control to The Address must be
filled in.
• Add a Text property with the value of * to the
CustomerZipCodeRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerZipCodeRequiredFieldValidator control to The Zip Code must be
filled in.
• Add a Text property with the value of * to the
CustomerCityRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCityRequiredFieldValidator control to The City must be filled in.
• Add a Text property with the value of * to the
CustomerCountryRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCountryRequiredFieldValidator control to A country must be
selected.
• Add a Text property with the value of * to the
CustomerEmailAddressRegularExpressionValidator control.
6-64 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Change the ErrorMessage property in the


CustomerEmailAddressRegularExpressionValidator control to The Email
Address must be valid.
• Add a Text property with the value of * to the
CustomerWebAddressRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerWebAddressRequiredFieldValidator control to The Web Address
must be filled in.
• Add a Text property with the value of * to the
CustomerWebAddressRegularExpressionValidator control.
• Change the ErrorMessage property in the
CustomerWebAddressRegularExpressionValidator control to The Web
Address must be valid.
• Add a Text property with the value of * to the
CustomerCreditLimitRequiredFieldValidator control.
• Change the ErrorMessage property in the
CustomerCreditLimitRequiredFieldValidator control to The Credit Limit
must be filled in.
• Add a Text property with the value of * to the
CustomerCreditLimitRangeValidator control.
• Change the ErrorMessage property in the
CustomerCreditLimitRangeValidator control to The Credit Limit must be
within the valid range.
• Save the Customer user control and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
in the Email Address box, type contoso.com, press the TAB key, in the Web
Address box, type www.contoso, and then press the TAB key.

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

• In the Contoso Customer Management – Windows Internet Explorer window,


click the Insert button.

Note: Notice the error indicator and error messages next to the First Name, Last Name,
Address, Zip Code, City, Country, and Credit Limit controls.

• Close Windows® Internet Explorer®.

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.

• Close Windows® Internet Explorer®.


• Add a Display property with the value of Dynamic to the
CustomerWebAddressRequiredFieldValidator control to change the display
of the error indicator text.
• Add a Display property with the value of Dynamic to the
CustomerCreditLimitRequiredFieldValidator control to change the display
of the error indicator text.
• Save the Customer user control, and view the changes in the browser.
• Click the Insert button.

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.

• Close Windows® Internet Explorer®.


6-66 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add a ValidationExpression property with the value of


\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* to the
CustomerEmailAddressRegularExpressionValidator control.
• Add a ValidationExpression property with the value of
\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* to the
CustomerWebAddressRegularExpressionValidator control.
• Set the Type property with the value of Integer to the
CustomerCreditLimitRangeValidator control.
• Change the MinimumValue property of the
CustomerCreditLimitRangeValidator control to 0.
• Save the Customer user control and view the changes in the browser.
• In the Contoso Customer Management – Windows Internet Explorer window,
in the Email Address box, type claus@contoso.com, in the Web Address
box, type http://www.contoso.com, and then click the Insert button.

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

Exercise 3: Adding Server-Side Validation


The main task for this exercise is to validate the Customer user control.

f Task 1 : Validate the Customer User Control


• Open the Customer.ascx.cs code window.
• Add the code to validate the user control within the
CustomerInsertButton_Click event handler method.

/// <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;

// Add the current user name


currentCustomer.CreatedBy = Context.User.Identity.Name;
// Add the user credit limit
currentCustomer.CreditLimit = 50000;
}
6-68 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Add postback validation to the Page_Load event handler method.

protected void Page_Load(object sender, EventArgs e)


{
if (Page.IsPostBack)
{
// Validate Page
Page.Validate();

// Did page validation succeed?


if (!Page.IsValid)
return;
}

// Instantiate Customer
instantiateCustomerObject();
// Populate the UI controls
populateUI();
}

• Disable the client-side validation for the CustomerCountryDropDownList


control, by setting the EnableClientScript property of the
CustomerCountryRequiredFieldValidator control to false.

<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.

• Close Windows® Internet Explorer®.


• Remove the EnableClientScript property for the
CustomerCountryRequiredFieldValidator control to enable the client-side
validation for the CustomerCountryDropDownList control, and format and
save the Customer user control.

<asp:RequiredFieldValidator
ID="CustomerCountryRequiredFieldValidator"
ControlToValidate="CustomerCountryDropDownList" runat="server"
ErrorMessage="A country must be selected."
Text="*"></asp:RequiredFieldValidator>

• In the CustomerManagement – Microsoft Visual Studio window, click the


Close button.

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

Review Questions and Answers


1. Why have you added the RegularExpressionValidator control for the e-mail
address field?
2. Why do you use a ValidationSummary control?
6-72 Introduction to Web Development with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions and Answers


1. Which control will you use to perform the following validation tasks?

Real-World Issues and Scenarios


1. You want to make sure that an input control is always filled in by the user, but
you also want it to be in a specific format. What is the easiest way to add this?
Add a RequiredFieldValidator and a RegularExpressionValidator control.
2. None of the intrinsic ASP.NET validation controls fit your validation needs.
What would you do to solve the issue?
Create a new CustomValidator control, and add the validation logic as code.
Validating User Input 6-73

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

Discussion: Types of Errors

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.

Determining Whether the Bug Should Be Fixed


There are a number of factors that determine whether or not a bug should be fixed:
• Is the bug too costly to fix at that stage of the development?
• Is it a serious flaw or a minor inconvenience?
• Is there a workaround?
Troubleshooting Microsoft® ASP.NET Web Applications 7-9

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.

Locating the Bug Without Using the Debugger


When you decide to fix a bug, you need to find the source of the error. The
simplest way to do this is to start looking at the input and output of the
application, and manually checking where the bug starts occurring. When you
find a single class or a single method that is responsible for the bug, you can start
looking at each individual line of code—either manually, or by commenting out
lines of code to locate exactly which line of code is responsible for the bug. This
process can be accompanied by sending the output of the intermediary results to a
file or the user interface (UI); eventually, you will locate the bug. In general, you
search for and locate the bug at runtime, when an action—such as user input—leads
to an unexpected error or result.

Fixing the Bug


After you have found the problem line or lines of code, you need to fix them
according to the specification of the particular method or class that you are
working with. Based on the type of bug found, you have to determine how to fix
it. Some errors require simple fixes, such as removing a line of code that is not
needed; others require a new expression or calculation. There are also other bugs
that after extensive research require you to redesign an entire class or even a
module.
While it is entirely possible to locate and fix a bug manually, it is more convenient
to fix bugs by using various tools. In most cases, it will save time if you use one or
more tools for debugging your code. Visual Studio 2010 provides you with the
Visual Studio 2010 debugger, and Microsoft .NET Framework objects and
constructs that help you fix bugs. The Visual Debugger tool helps you set
breakpoints, and step through the code line by line. You set a breakpoint on a
specific line of code. When the line of code is hit at runtime, the code opens in the
debugger. At this point, you can examine the code to fix it, and then proceed
through the code that follows, line by line, if needed.

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

The following table lists the methods of the Debug class.

Method Description

Debug.Write Use this method to write a string of text of your choice, or


to write the output from an object’s ToString method.
The message or string of text is written to the trace
listeners in the Listeners collection.

Debug.WriteLine Use this method to write a line of text of your choice, or


to write the output from an object’s ToString method.
The message or string of text, followed by a line
terminator, is written to the trace listeners in the Listeners
collection.

Debug.WriteIf Use this method to conditionally write a string of text of


your choice, or to write conditionally the output from an
object’s ToString method.

Debug.Print Use this method to write a formatted line of text of your


choice.

Debug.Assert Use this method to display a message if a specified


condition is false.
The call stack that is being shown in the dialog box when
calling Debug.Assert contains the same information as
the Call Stack window within Visual Studio 2010 in a
break state.

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

Gathering Debug Information at Run Time

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

Methods for Printing Debug Information

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

Debugging a Web Application

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.

Enabling Web Application Debugging


You must enable debugging—if you want to debug your Web application—and you
need to do this in the web.config file. You need to locate the opening compilation
element that is found within the system.web element, and then set the value of the
debug attribute to true. The following code examples show how to set the value of
the debug attribute.
Troubleshooting Microsoft® ASP.NET Web Applications 7-19

[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>

Adding and Removing Breakpoints


If you want the execution of your Web application to pause at specific points in
your code, you can add a breakpoint. You need to first locate the line of code to
which you want to add the breakpoint, and then press the F9 key, or click Toggle
Breakpoint on the Debug menu. To remove the breakpoint, press F9 again, or
click Toggle Breakpoint on the Debug menu. By default, the lines of code with the
breakpoints are highlighted in a white text color on a dark red background color.
If you have many breakpoints and you decide to remove them all, you can press
CTRL+SHIFT+F9, or click Delete All Breakpoints on the Debug menu to remove
all the breakpoints using a single action. You will be prompted to confirm this
action.

Running in Debug Mode


To run your application in debug mode, you must press F5, or click Start
Debugging on the Debug menu. If debugging has not yet been enabled at this
point, you will be prompted to enable debugging by the appearance of the
Debugging Not Enabled message box. In the message box, simply click OK to
enable debugging. This will modify the web.config file.
7-20 Introduction to Web Development with Microsoft® Visual Studio® 2010

Stepping Through Code


When the debugger reaches the line with the breakpoint, execution pauses. You
can then step through the code and examine the logic of your application.
Press F10, or click Step Over on the Debug menu, if you want the current line of
code to be executed without stepping into any of the underlying code (such as a
method in the same class, or a method in another class). Execution will pause on
the next line of code.
Press F11, or click Step Into on the Debug menu, if you want to step into the
underlying code of the current line of code to be executed, if there is any.
Execution will pause on the next line of code in the underlying code. By default,
properties are normally stepped over, because they generally do not contain any
complex logic, but it is possible to step into a property. You can right-click the line
of code that is calling the property getter or setter, then, on the context menu,
point to Step Into Specific, and then click
NamespaceName.ClassName.set_PropertyName.

Use Debugger Variable Windows


The Visual Studio 2010 debugger provides several windows, collectively known as
variable windows, for displaying variable information during debugging. These
windows are: Autos, Locals, Watch, and Watch1 through Watch 4. Each variable
window has a grid with three columns: Name, Value, and Type. The Autos and
Locals windows display names of the variables that are added automatically, in the
Name column.
In the Watch window, the Name column is where you can add your own variables
or expressions. The Value and Type columns display the value and data type of the
corresponding variable or expression result. You can edit the value of a variable in
the Value column.

f To display a variable window


• On the Debug menu, choose Windows, and then choose the name of the
variable window you want to display. To display these menu items, the
debugger must be running or in break mode; you cannot access these menu
items or display these windows in design mode.

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.

Remote Debugging Monitor


When you perform remote debugging, you can use the Remote Debugging
Monitor—or msvsmon.exe—which is a small application to which Visual Studio 2010
connects. You can either install the Remote Debugging Monitor on the remote
computer, or run the monitor remotely from a shared folder.
By default, the Remote Debugging Monitor runs as a Windows®-based application.
To debug in ASP.NET or another server environment, you can configure the
monitor to run as a Windows service by using the Visual Studio 2010 Remote
Debugger Configuration Wizard. You can start this wizard from the Visual Studio
Tools folder on the Start menu.
7-22 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Remote Debugging Setup


Visual Studio 2010 supports remote debugging from one computer to another.
When you perform remote debugging, the host computer can be any platform that
supports Visual Studio 2010. Reasons for performing remote debugging are when
the program you are debugging is on the Web server, or if the program is
performing differently on your computer.

Question: In what scenarios will you perform remote debugging?


Troubleshooting Microsoft® ASP.NET Web Applications 7-23

Lesson 2
Tracing in ASP.NET

Tracing is the process of receiving informative messages about the execution of a


Web application at runtime—that is, it is a way to monitor the execution of your
Web application. These informative messages from the Web application can help
you identify problems or analyze performance in a manner that does not affect the
program's output. This includes recording any exception details, and recording the
program flow. Tracing is typically used in a production environment, or a similar
environment in which you cannot perform debugging. Tracing statements can
remain in your code when you release your Web application, because by default,
tracing is not enabled, which means any trace output is ignored. You can then
enable tracing when you find an error, or if you have a performance issue. So,
tracing is useful when it is impractical to use the debugger. Visual Studio 2010
provides the TraceContext class for this purpose.
This lesson describes how to use the TraceContext class to implement tracing in a
Web application.
7-24 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Question: What is the purpose of using tracing functionality?


Troubleshooting Microsoft® ASP.NET Web Applications 7-27

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.

<%@ Page ... Trace="True" TraceMode="SortByCategory" %>

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

Tracing a Web Application

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.

Enabling Web Application Tracing


The following code examples show how you can enable page-level tracing.

[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

Request Details Contains information about the request: session


identification (ID), time of request, type of request, and
request status.

Trace Information Contains output from standard and custom trace


statements. The From First(s) column contains the total time
from execution until the trace is run, and the From Last(s)
column displays the increment duration.
This is a very useful section for debugging. The timing
information located here is valuable when profiling and
searching for methods in your application that take too long
to execute.

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.

Session State Contains information about values stored in Session state, if


any.

Application State Contains information about values stored in Application


state, if any.

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

Headers Collection Displays a list of request and response message header


name/value pairs.

Form Collection Displays a list of controls, and their values on the form that is
posted.

Querystring Displays a list of values passed in the URL.


Collection

Server Variables List of all the server variables and their values.

You can view trace information at the bottom of each page.


Troubleshooting Microsoft® ASP.NET Web Applications 7-35

The following screen shot displays the requests in the trace viewer:

Question: How will you view trace information?


7-36 Introduction to Web Development with Microsoft® Visual Studio® 2010

Lab: Troubleshooting Microsoft ASP.NET Web


Applications

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:

• Debug a Web application to view runtime information.


• Enable and implement tracing in a Web application.

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

Section 1: Visual Basic


Exercise 1: Debugging a Web Application
The main tasks for this exercise are as follows:

1. Open an existing ASP.NET Web site.

2. Enable debugging of the CustomerManagement Web project.

3. Add debug output statements to the user control.

4. Find and fix a bug.

f Task 1: Open an existing ASP.NET Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M7\VB folder.

f Task 2: Enable debugging of the CustomerManagement Web project


• Open the web.config file of the CustomerManagement Web project.
• Set the debug attribute of the compilation element to true.

<compilation debug="true" strict="false" explicit="true"


targetFramework="4.0" />

• Save and close the web.config file.

f Task 3: Add debug output statements to the user control


• Open the Customer user control.
• Import the System.Diagnostics namespace.

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.

Debug.WriteLine("Page Postback detected in Page_Load")

• 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.

Debug.WriteLineIf(Not Page.IsPostBack, "No Page Postback detected


in Page_Load")

• At the end of the Page_Unload event handler, send the message, “Page has
been unloaded” to the trace listeners.

Debug.WriteLine("Page has been unloaded")

• 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.

Debug.WriteLine("Customer has been inserted in


CustomerInsertButton_Click");

• At the end of the private populateUI method, send the message, “UI controls
have been populated” to the trace listeners.

Debug.WriteLine("UI controls have been populated")

• At the end of the private instantiateCustomerObject method, send the


message, “Customer object has been instantiated” to the trace listeners.

Debug.WriteLine("Customer object has been instantiated")

• Save the user control code file.


• Add a default item to the Country DropDownList control.
• In the Customer.ascx.vb window, right-click and then click View
Designer.
• In the Customer.ascx window, click the CustomerCountryDropDownList
control.
Troubleshooting Microsoft® ASP.NET Web Applications 7-41

• 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

f Task 4: Find and fix a bug


• Run the CustomerManagement Web application to test its functionality.
• Create a new customer, by using the following information:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com

Note: Notice that the value for the Credit Limit box is set to 0 by default.

• Click the Insert button.

Note: Notice that the value for the Credit Limit box is set to 50, which is incorrect.

• Close Windows Internet Explorer®.


• Add a breakpoint in the Page_Load event handler method in the line of code
that calls the instantiateCustomerObject method.

instantiateCustomerObject();

• Run the Web application in debug mode.


• In the Contoso Customer Management – Windows Internet Explorer window,
on the Customers menu, click New.
• Step into the instantiateCustomerObject method.
• Step over the first line of code and then check for postback in the
instantiateCustomerObject method.
• Add a watch to the Text property of the CustomerCreditLimitTextBox
control.
• Continue to debug the Web application.
Troubleshooting Microsoft® ASP.NET Web Applications 7-43

• 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: Notice that in the Watch 1 window, the value of the


CustomerCreditLimitTextBox Text property is set to 0.

• Step over the call to the instantiateCustomerObject method.


• Step over the call to the populateUI method.

Note: In the Watch1 window, notice that the value for the
CustomerCreditLimitTextBox is changed to 50.

• Stop debugging the Web project.


• Examine the code in the populateUI method that assigns a value to the
CustomerCreditLimitTextBox.Text property.

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

• Save and close the class file.


Troubleshooting Microsoft® ASP.NET Web Applications 7-45

• Run the Web application to verify the Credit Limit value.


• Create a new customer, by using the following information:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com
• Click the Insert button.

Note: Notice that the value for the Credit Limit box is still 0.

• Close Windows Internet Explorer®.

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

Exercise 2: Tracing a Web Application


The main tasks for this exercise are as follows:
1. Enable application-level tracing of the CustomerManagement Web project.
2. Implement application tracing.

f Task 1: Enable application-level tracing of the CustomerManagement


Web project
• Add a trace element to the web.config file as the first element within the
system.web, and set the value of the enabled attribute to true.

<trace enabled="true" />

• Save and close the web.config file.

f Task 2: Implement application tracing


• Run the Web application, and view the trace details.
• 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
• View the trace details for the application, by using the
http://localhost:1111/CustomerManagement/trace.axd URL in the
browser.
Troubleshooting Microsoft® ASP.NET Web Applications 7-47

• View the details for the InsertCustomer.aspx Web page.


• In the http://localhost:1111/CustomerManagement/trace.axd - Windows
Internet Explorer window, click View Details of /InsertCustomer.aspx
corresponding to the Verb, GET.

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.

• Close Windows Internet Explorer®.

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:

1. Open an existing ASP.NET Web site.

2. Enable debugging of the CustomerManagement Web project.

3. Add debug output statements to the user control.

4. Find and fix the bug.

f Task 1: Open an existing ASP.NET Web site


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M7\CS folder.

f Task 2: Enable debugging of the CustomerManagement Web project


• Open the web.config file of the CustomerManagement Web project.
• Set the debug attribute of the compilation element to true.

<compilation debug="true" targetFramework="4.0">

• Save and close the web.config file.

f Task 3: Add debug output statements to the user control


• Open the Customer user control.
• Import the System.Diagnostics namespace to the user control.

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.

Debug.WriteLine("Page Postback detected in Page_Load");

• 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.

Debug.WriteLineIf(Not Page.IsPostBack, "No Page Postback detected


in Page_Load");

• At the end of the Page_Unload event handler, send the message, “Page has
been unloaded” to the trace listeners.

Debug.WriteLine("Page has been unloaded");

• 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.

Debug.WriteLine("Customer has been inserted in


CustomerInsertButton_Click");

• At the end of the private populateUI method, send the message, “UI controls
have been populated” to the trace listeners.

Debug.WriteLine("UI controls have been populated");

• At the end of the private instantiateCustomerObject method, send the


message, “Customer object has been instantiated” to the trace listeners.

Debug.WriteLine("Customer object has been instantiated");

• Save the user control code file.


• Add a default item to the Country DropDownList control.
• In the Customer.ascx.cs window, right-click and then click View Designer.
• In the Customer.ascx window, click the CustomerCountryDropDownList
control.
• Click the Smart Tag button, and then click Edit Items.
7-50 Introduction to Web Development with Microsoft® Visual Studio® 2010

• 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 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

f Task 4: Find and fix a bug


• Run the CustomerManagement Web application to test its functionality.
• Create a new customer, by using the following information:
• First Name: Claus
• Last Name: Hansen
• Address: 4567 Main St.
• Zip Code: 98052
• City: Buffalo
• State: NY
• Web Address: http://www.cohowinery.com

Note: Notice that the value for the Credit Limit box is set to 0 by default.

• Click the Insert button.

Note: Notice that the value for the Credit Limit box is set to 50, which is incorrect.

• Close Windows Internet Explorer®.


• Add a breakpoint in the Page_Load event handler method in the line of code
that calls the instantiateCustomerObject method.

instantiateCustomerObject();

• Run the Web application in debug mode.


• Step into the instantiateCustomerObject method.
• Step over the first line of code and the check for postback in the
instantiateCustomerObject method.
• Add a watch to the Text property of the CustomerCreditLimitTextBox
control.
• Continue to debug the Web application.
7-52 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

Note: Notice that in the Watch 1 window, the value of the


CustomerCreditLimitTextBox Text property is set to 0.

• Step over the call to the instantiateCustomerObject method.


• Step over the call to the populateUI method.

Note: In the Watch1 window, notice that the value for the
CustomerCreditLimitTextBox is changed to 50.

• Stop debugging the Web project.


• Examine the code in the populateUI method that assigns a value to the
CustomerCreditLimitTextBox.Text property.

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.

this.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.

this.customerCreditLimit = value;
7-54 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Save and close the class file.


• Run the Web application to verify the Credit Limit value.
• 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: Notice that the value for the Credit Limit box is still 0.

• Close Windows Internet Explorer®.

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

Exercise 2: Tracing a Web Application


The main tasks for this exercise are as follows:
1. Enable application-level tracing of the CustomerManagement Web project.
2. Implement application tracing.

f Task 1: Enable application-level tracing of the CustomerManagement


Web project
• Add a trace element to the web.config file as the first element within the
system.web, and set the value of the enabled attribute to true.

<trace enabled="true" />

• Save and close the web.config file.

f Task 2: Implement application tracing


• Run the Web application, and view the trace details.
• 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
• View the trace details for the application, by using the
http://localhost:1110/CustomerManagement/trace.axd URL in the
browser. View the details for the InsertCustomer.aspx Web page.
• In the http://localhost:1110/CustomerManagement/trace.axd - Windows
Internet Explorer window, click View Details of /InsertCustomer.aspx
corresponding to the Verb, GET.
7-56 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.

• Close Windows Internet Explorer®.

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

Review Questions and Answers


1. What are the steps required to enable page-level tracing?
2. How will you explicitly turn on tracing in a component by using code?
7-58 Introduction to Web Development with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions and Answers


1. What is the difference between the System.Diagnostics.Trace object and the
System.Diagnostics.Debug object?
2. What is the difference between page-level tracing and application-level tracing?
3. How do you enable application-level tracing?
4. What are the types of errors that you need to handle when you develop
applications?
Troubleshooting Microsoft® ASP.NET Web Applications 7-59

Real-World Issues and Scenarios


1. In a method, you want to write the value of a variable to the trace listeners, but
only if a specific condition is true. What is the easiest way to implement this?
Call the Debug.WriteIf method.
2. On a production server, you need to start tracing, but you do not want the
users to see the trace output on each page they request. How will you
implement this?
You enable application-level tracing, and use the trace viewer trace.axd to view
the trace output.

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

Because of the importance of data storage in Web applications, you must be


familiar with the data access methods that ADO.NET provides for ASP.NET Web
Forms. ADO.NET is a part of the .NET Framework base class library that helps you
access and manipulate data. You can use ADO.NET to access and manage data in
both non-relational data sources, and relational database systems such as SQL
Server 2008. The two components in ADO.NET—data providers and DataSet—help
you connect to and access data sources.
This lesson explains what ADO.NET is, and how it works.

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.

Question: What is the primary use of ADO.NET?


8-6 Introduction to Web Development with Microsoft® Visual Studio® 2010

ADO.NET Object Model

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

Constraint Represents a constraint that can be enforced on one or more


DataColumn objects. A constraint is a rule that is used to
maintain the integrity of the data in a table. The abstract
Constraint base class has two derived classes that are used for
primary keys and/or unique column values by using the
UniqueConstraint class. The ForeignKeyConstraint class
determines whether the values in the related tables are also
deleted, set to null values, set to default values, or if no action
should be taken.

DataColumn Represents the schema of a single column in a DataTable.


Multiple DataColumn objects are used to specify the
structure or schema of a DataTable.

DataRelation Represents a parent/child relationship between two


DataTable objects. A DataRelation object is tied to an equal
number of DataColumn objects in two different DataTable
objects. The DataRelation object allows for navigation
between related data tables.

DataRow Represents a row of data in a DataTable object.

DataSet This is the general container object that represents an in-


memory database, consisting of one or more DataTable
objects, and zero or more DataRelation objects. This class is
serializable, and can be transported over the wire.

DataTable Represents one table of in-memory data. The structure of the


data is made of one or more DataColumn objects, and the
data is saved in DataRow objects. This class is serializable, and
can be transported over the wire.

DataTableReader Obtains the contents of one or more DataTable objects in the


form of one or more read-only, forward-only result sets.

DataView Represents a customized view of a DataTable, which can be


used for sorting, filtering, searching, editing, and navigation.
8-8 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Type name Type description

DbCommand Represents an SQL statement or stored procedure to run


against a data source. This type is generally split into four
different command objects when managing data—one for
selecting data, another for inserting data, a third for updating
data, and the fourth for deleting data.

DbConnection Represents the actual connection to a data source, and


connects by using a connection string.

DbDataAdapter Represents a database connection and a set of SQL commands


that are used to fill the DataSet and/or DataTable, and
update the data source. This type is the bridge between the
client-side and the server-side, and it uses a connection object
and command objects to perform its duties.

DbDataReader Reads a forward-only, read-only stream of rows from a data


source.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-9

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.

Question: How will you work with a DataSet to populate data?


8-10 Introduction to Web Development with Microsoft® Visual Studio® 2010

Overview of ADO.NET Entity Framework

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.

Mapping Objects to Data


Object-oriented programming poses a challenge for interacting with data storage
systems. Frequently, the organization of classes closely mirrors the organization
of relational database tables; however, the fit is not perfect. Multiple normalized
tables frequently correspond to a single class, and relationships between classes
are represented differently from relationships between tables. For example, to
represent the customer for a sales order, an Order class uses a property that
contains a reference to an instance of a Customer class, but an Order table row in
a database contains a foreign key column or set of columns with a value that
corresponds to a primary key value in the Customer table. A Customer class might
have a property named Orders that contains a collection of instances of the Order
class, but the Customer table in a database has no comparable column.
Existing solutions help to bridge this gap—which is frequently called an impedance
mismatch—by only mapping object-oriented classes and properties to relational
tables and columns. Instead of taking this traditional approach, the Entity
Framework maps relational tables, columns, and foreign key constraints in logical
models to entities and relationships in conceptual models. This enables greater
flexibility both in defining objects, and in optimizing the logical model.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-13

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.

Accessing and Changing Entity Data


The Entity Framework enables applications to access and change data that is
represented as entities and relationships in the conceptual model. Object Services
uses the EDM to translate object queries against entity types that are represented in
the conceptual model into data source-specific queries. Query results are
materialized into objects that Object Services manages.

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.

Data Platform Components


In .NET Framework 4, the ADO.NET Entity Framework provides the Data Platform
components that are listed in the following table.

Component Description

EDM A design specification that defines application data as sets of


entities and relationships. Data in this model supports object-
relational mapping and data programmability across
application boundaries. EDM data types and relationships are
defined in a conceptual model. This is an XML schema written
in conceptual schema definition language (CSDL). You use the
conceptual model to build programmable classes that
represent application data. You can extend these objects as
required to support various application needs.

Object Services Allows programmers to interact with the conceptual model


through a set of common language runtime (CLR) classes.
These classes can be automatically generated from the
conceptual model, or can be developed independently to
reflect the structure of the conceptual model. Object Services
also provide infrastructure support for the Entity Framework,
including services such as state management, change tracking,
identity resolution, loading and navigating relationships,
propagating object changes to database modifications, and
query building support for Entity SQL.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-15

(continued)

Component Description

LINQ to Entities A language-integrated query (LINQ) implementation that


allows you to create strongly-typed queries against the Entity
Framework object context by using LINQ expressions and LINQ
standard query operators. LINQ to Entities allows developers to
work against a conceptual model with a very flexible object-
relational mapping across SQL Server and third-party
databases.

Entity SQL A text-based query language designed to interact with an EDM.


Entity SQL is a SQL dialect that contains constructs for querying
in terms of higher-level modeling concepts, such as inheritance,
complex types, and explicit relationships. You can also use
Entity SQL directly with Object Services.

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.

EDM Tools The Entity Framework provides command-line tools, wizards,


and designers to facilitate building EDM applications. The
EntityDataSource control supports data binding scenarios
based on the EDM. The programming surface of the
EntityDataSource control is similar to other data source
controls in Microsoft Visual Studio®.
8-16 Introduction to Web Development with Microsoft® Visual Studio® 2010

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.

Creating a Connection by Using Server Explorer


Server Explorer—which is part of the Visual Studio 2010 IDE—allows you to
connect to data sources, create database objects, explore the properties of existing
objects, and preview the data. Whenever you explore the server of a data source,
the connection state is open; it remains open whenever the window has focus. This
can have an impact on availability, especially if the server is remote and heavily
used.
8-18 Introduction to Web Development with Microsoft® Visual Studio® 2010

f To connect to a SQL Server database


1. In Server Explorer, right-click Data Connections, and then click Add
Connection. The Add Connection dialog box appears.
2. In the Add Connection dialog box:
3. In the Data source box, ensure that the correct data provider and data source
type is selected.
• In the Add Connection dialog box, when you click Change, a Change
Data Source dialog box appears and enables you to choose your data
source type.
4. In the Server name box, type or select the name of the data source server.
5. In the Add Connection dialog box, under Log on to the server pane, click
either Use Windows Authentication or Use SQL Server Authentication. If
you select SQL Server authentication, provide your credentials.
6. Under Connect to a database, in the Select or enter a database name list,
select a database, and then click OK.

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.

Creating a Connection Programmatically


If you want your connection to be readily available from your code, you can create
a connection object programmatically. For creating a connection to SQL Server 7.0
or newer, you need to first import the System.Data.SqlClient namespace as
follows.

[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();

Note: Because a connection object uses an unmanaged resource, garbage collection


does not happen automatically. Therefore, you must close or dispose of the connection
object after using it. Otherwise, you will keep the connection to the server open, waste
valuable server resources, and potentially degrade server performance—or even deny
other users from accessing the server.

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

Another method to ensure the disposal of a connection object is to wrap it in a


Using/using statement, as in the following examples.

[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

Facilitating Data Transport Between Clients and Servers

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

• InsertCommand. Issues an SQL INSERT statement for inserting new data on


the server, whenever new data is created on the client.
• DeleteCommand. Issues an SQL DELETE statement for deleting data on the
server, whenever data is deleted on the client.

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.

Creating a DataAdapter Programmatically


If you want your data adapter to be readily available from your code, you can create
a DataAdapter object programmatically. For creating a DataAdapter object to
work with a SQL Server version 7.0 or newer database, you first need to import the
System.Data.SqlClient namespace. After importing the namespace, you can create
the SqlDataAdapter object as shown in the following code examples.

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)

' Assign command objects


ordersDataAdapter.SelectCommand = selectCommand
ordersDataAdapter.DeleteCommand = deleteCommand
ordersDataAdapter.InsertCommand = insertCommand
ordersDataAdapter.UpdateCommand = updateCommand

[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);

// Assign command objects


ordersDataAdapter.SelectCommand = selectCommand;
ordersDataAdapter.DeleteCommand = deleteCommand;
ordersDataAdapter.InsertCommand = insertCommand;
ordersDataAdapter.UpdateCommand = updateCommand;
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-25

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")

Dim updateIDParameter As New SqlParameter("@ID",


SqlDbType.UniqueIdentifier, 0, "ID")
Dim updateInvoiceDateParameter As New SqlParameter("@InvoiceDate",
SqlDbType.SmallDateTime, 0, "InvoiceDate")
...

Dim insertInvoiceDateParameter As New SqlParameter("@InvoiceDate",


SqlDbType.SmallDateTime, 0, "InvoiceDate")
...

' Assign parameters to command object


deleteCommand.Parameters.Add(deleteIDParameter)
updateCommand.Parameters.Add(updateIDParameter)
...

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");

SqlParameter updateIDParameter = new SqlParameter("@ID",


SqlDbType.UniqueIdentifier, 0, "ID");
SqlParameter updateInvoiceDateParameter = new
SqlParameter("@InvoiceDate", SqlDbType.SmallDateTime, 0,
"InvoiceDate");
...

SqlParameter insertInvoiceDateParameter = new


SqlParameter("@InvoiceDate", SqlDbType.SmallDateTime, 0,
"InvoiceDate");
...

// Assign parameters to command object


deleteCommand.Parameters.Add(deleteIDParameter);

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

Creating a DataReader Programmatically


If you want to create a fast, read-only, forward-only stream of rows from your
data source, you should create a DataReader object. For creating a DataReader
object to work with SQL Server 7.0 or newer, you first need to import the
System.Data.SqlClient namespace. After importing the namespace, you can
create your SqlDataReader object by using the ExecuteReader method of the
SqlCommand object, as the following code examples illustrate.

[Visual Basic]

Dim ordersDataReader As SqlDataReader = selectCommand.ExecuteReader()

' Any more rows?


While ordersDataReader.Read()
...
End While

' Always call Close when done


ordersDataReader.Close()

[Visual C#]

SqlDataReader ordersDataReader = selectCommand.ExecuteReader();

// Any more rows?


while (ordersDataReader.Read())
{
//...
}

// Always call Close when done


ordersDataReader.Close();

Notice how the SqlCommand object selectCommand is used to create the


DataReader object, which selects all the rows from the Orders table. When the
ExecuteReader method is called, the SqlConnection object that is associated with
the SqlCommand object must be open; otherwise, an exception is thrown.
8-28 Introduction to Web Development with Microsoft® Visual Studio® 2010

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

Retrieving Simple Data

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.

Retrieving Read-Only Data


You can use the Command object to call the ExecuteReader method, send the
SELECT command to the data source, and then have the results returned in a
DataReader object. You can then use the Read method of the DataReader object
to access the result set. If the SELECT command returns multiple result sets, you
can use the NextResult method to move to the next result set. Multiple result sets
are often the result of multiple SELECT statements. For example, the following
SelectCommand object is used with the SQL Server .NET Framework Data
Provider.

SELECT * FROM Orders;SELECT * FROM Customers


8-32 Introduction to Web Development with Microsoft® Visual Studio® 2010

Note that the two SELECT statements are separated by a semicolon.

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)

' Open connection


orderConnection.Open()

' Declare, instantiate and initialize datareader


Dim ordersDataReader As SqlDataReader = _
selectCommand.ExecuteReader()

' Any rows returned?


If Not ordersDataReader.HasRows Then
' ...
Else
' Any more rows?
While ordersDataReader.Read()
...
End While
End If

' Close datareader


ordersDataReader.Close()
' Close connection
orderConnection.Close()
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-33

[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();

// Declare, instantiate and initialize datareader


SqlDataReader ordersDataReader = selectCommand.ExecuteReader();

// Any rows returned?


if (!ordersDataReader.HasRows)
{
...
}
else
{
// Any more rows?
while (ordersDataReader.Read())
{
...
}
}

// 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.

SELECT ID FROM Orders WHERE CreatedBy=’Weber’

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)

' Open connection


orderConnection.Open()

' Get scalar value


Dim name As String = CType(selectCommand.ExecuteScalar(), String)

' Close connection


orderConnection.Close()
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-35

[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();

// Get scalar value


string name = (string) selectCommand.ExecuteScalar();

// Close connection
orderConnection.Close();
8-36 Introduction to Web Development with Microsoft® Visual Studio® 2010

Retrieving Non-Simple Data

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

Working with the DataSet Programmatically


To create a DataSet object, you can use one of two constructors, where the first
constructor does not take any parameters, and the second constructor takes the
name of the dataset. The following code examples show how you can declare and
instantiate a DataSet.

[Visual Basic]
Dim ordersDataSet As New DataSet("OrdersDataSet")

[Visual C#]
DataSet ordersDataSet = new DataSet("OrdersDataSet");

Populating the DataSet


After you have created a DataSet object, you can populate the DataSet object by
using a DataAdapter object. You can call the Fill method on the DataAdapter
object, and then specify the name of the DataTable object that is created for you
within the DataSet. The following code examples create and populate the Orders
table. The schema of the Orders table in the database is automatically copied to the
Orders DataTable object.

[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 DataRow and DataColumn classes are primary components of a DataTable


class, where the DataColumn objects make up the structure of the DataTable, and
the DataRow objects contain the actual data. You can use a DataRow object and its
properties and methods to retrieve and evaluate the values in a DataTable object.
The DataRowCollection represents the actual DataRow objects that are in the
DataTable object, and the DataColumnCollection contains the DataColumn
objects that define the schema of the DataTable object. The Rows property of the
DataTable object provides programmatic access to the DataRowCollection. The
Columns property of the DataTable object provides programmatic access to the
DataColumnCollection.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-39

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);
};

Both the DataRowCollection and DataColumnCollection objects have a Count


property that allows you to determine the number of rows or columns in a
DataTable object. The following code examples illustrate this.

[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.

Manipulating Data by Using a DataAdapter Object


The following code examples illustrate how you can insert a new row of data
locally.
8-42 Introduction to Web Development with Microsoft® Visual Studio® 2010

[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

' Insert new row locally


ordersDataSet.Tables("Orders").Rows.Add(newOrderDataRow)

' Update data source


ordersDataAdapter.Update(ordersDataSet, "Orders")

[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;

// Insert new row locally


ordersDataSet.Tables["Orders"].Rows.Add(newOrderDataRow);
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-43

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")

' Update row locally


orderDataRow("ModifiedDate") = DateTime.Now
orderDataRow("ModifiedBy") = currentUser.Name

[Visual C#]
// Find row
DataRow orderDataRow =
ordersDataSet.Tables["Orders"].Rows.Find("a05c7f53-9c4e-de11-aa78-
0003ffa70544");

// Update row locally


orderDataRow["ModifiedDate"] = DateTime.Now;
orderDataRow["ModifiedBy"] = currentUser.Name;

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")

' Delete row locally


orderDataRow.Delete()

[Visual C#]
// Find row
DataRow orderDataRow =
ordersDataSet.Tables["Orders"].Rows.Find("20389eb1-f24f-de11-aa78-
0003ffa70544");

// Delete row locally


orderDataRow.Delete();
8-44 Introduction to Web Development with Microsoft® Visual Studio® 2010

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");

Question: What is the main purpose of using the DataAdapter object?


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-45

Data to Server Controls by Using the IDE

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.

Displaying Data on a Web Form


After you create a connection to a database, you can use Server Explorer to add
data directly to a Web Form. In Server Explorer, if you drag a table to the Text
Editor in Design view, Visual Studio 2010 creates a GridView control and a
SqlDataSource control by default:
• GridView control. Displays the values of a data source in a table where each
column represents a field, and each row represents a record. Optionally, a user
can select, sort, and edit the items that are displayed in the control.
• SqlDataSource control. Enables you to use a server control to access data that
is located in a relational database, such as SQL Server databases.
8-46 Introduction to Web Development with Microsoft® Visual Studio® 2010

Visual Studio 2010 automatically sets the ConnectionString and Command


properties of the SqlDataSource, as shown in the following code.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="<%$ ConnectionStrings:OrderConnectionString1 %>"
DeleteCommand="DELETE FROM [Orders] WHERE [ID] = @ID"
InsertCommand="INSERT INTO [Orders] ([ID], [CustomerID],
[InvoiceDate], [CreatedDate], [CreatedBy], [ModifiedDate],
[ModifiedBy]) VALUES (@ID, @CustomerID, @InvoiceDate, @CreatedDate,
@CreatedBy, @ModifiedDate, @ModifiedBy)"
ProviderName="<%$
ConnectionStrings:OrderConnectionString1.ProviderName %>"
SelectCommand="SELECT [ID], [CustomerID], [InvoiceDate],
[CreatedDate], [CreatedBy], [ModifiedDate], [ModifiedBy] FROM
[Orders]"
UpdateCommand="UPDATE [Orders] SET [CustomerID] = @CustomerID,
[InvoiceDate] = @InvoiceDate, [CreatedDate] = @CreatedDate,
[CreatedBy] = @CreatedBy, [ModifiedDate] = @ModifiedDate, [ModifiedBy]
= @ModifiedBy WHERE [ID] = @ID">
...
</asp:SqlDataSource>

The following markup shows the OrderConnectionString1 connection string


setting in the web.config file, which is referred to in the previous markup.

<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.

<asp:GridView ID="GridView1" runat="server"


AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" EmptyDataText="There are no data records
to display.">
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-47

At this stage, you can view the Web Form in a browser to display the data from the
data source.

Setting Data Source and Control Display Properties


You can use the SqlDataSource control in conjunction with a data-bound control
to retrieve data from a relational database. You can also display, edit, and sort data
on a Web Form by using little or no code. When you select a SqlDataSource
control, you can use the Properties window to set its properties.
The SqlDataSource control includes the following main properties:
• ConnectionString. The connection string to connect to the database.
• ProviderName. The name of the .NET Data Provider assembly.

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.

Question: What is the purpose of using the SqlDataSource control?


8-48 Introduction to Web Development with Microsoft® Visual Studio® 2010

Lab: Managing Data in an ASP.NET 4.0 Web


Application

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

Section 1: Visual Basic


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.

f Task 1: Open an existing ASP.NET Web project


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M8\VB folder.

f Task 2: Add a SQL Server 2008 Express Database


• Add a new database folder named App_Data, and an existing database to the
database folder, D:\LabFiles\Starter\M8\CustomerManagement.mdf.

f Task 3: Add a data control source to the user control


• Open the Customer user control in Design view.
• Add a SqlDataSource control to the user control to connect to an SQL Server
database.
• Rename the SqlDataSource control as CountriesSqlDataSource.
• Save the Customer user control.
8-52 Introduction to Web Development with Microsoft® Visual Studio® 2010

f Task 4: Configure a data source control


• In Design view, with the CountriesSqlDataSource control selected, display
the Smart Tag.
• Open the Configure Data Source Wizard, connect to the
CustomerManagement.mdf database, and then create a new connection
string named CustomerManagementConnectionString.
• Configure the SELECT statement to include the ID and Name columns from
the Countries table.
• Test the query, and check whether you get the correct data from the Countries
table.

Note: Ensure that the returned rows include the values for the ID and Name columns for
various countries.

• Save the Customer user control.


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-53

Exercise 2: Binding a Server Control to a Data Source


The main tasks in this exercise are as follows:
1. Bind the DropDownList control to a data source.
2. Pass the values to the Customer object.

f Task 1: Bind the DropDownList control to a data source


• Open the Customer user control in Source view.
• Locate the markup for the CustomerCountryDropDownList control.
• Remove the static ListItem element from the
CustomerCountryDropDownList control.

<asp:ListItem>USA</asp:ListItem>

• Bind the CustomerCountryDropDownList control to the


CountriesSqlDataSource control by using the DataSourceID attribute.

DataSourceID="CountriesSqlDataSource"

• Set the value field of the CustomerCountryDropDownList control to the ID


column of the database by using the DataValueField attribute.

DataValueField="ID"

• Set the text field of the CustomerCountryDropDownList control to the Name


column of the database by using the DataTextField attribute.

DataTextField="Name"

• Build the user control, and fix any errors.

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

f Task 2: Pass the values to the Customer object


• Open the Customer user control in the Code view.
• Locate the code for the private instantiateCustomerObject method and pass
the selected value of the CustomerCountryDropDownList control to the
Customer class constructor by using the SelectedValue property wrapped in a
new Guid object.

' Instantiate new Customer object with user input


currentCustomer = New CustomerManagementEntities.Customer(
Nothing, CustomerFirstNameTextBox.Text,
CustomerLastNameTextBox.Text,
CustomerAddressTextBox.Text, CustomerZipCodeTextBox.Text,
CustomerCityTextBox.Text,
CustomerStateTextBox.Text, New
Guid(CustomerCountryDropDownList.SelectedValue),
CustomerPhoneTextBox.Text,
CustomerEmailAddressTextBox.Text,
CustomerWebAddressTextBox.Text,
CustomerNewsSubscriberCheckBox.Checked,
Integer.Parse(CustomerCreditLimitTextBox.Text), DateTime.Now,
"", Nothing, "")

• Build the user control, and fix any errors.


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-55

Exercise 3: Modifying a Data Source


The main tasks for this exercise are as follows:
1. Create the Customers Web Form.
2. Add the SqlDataSource control to the Web Form.
3. Configure the SqlDataSource control.
4. Add the ListView control to the Web Form.
5. Add code to manually save a customer to a data source.
6. Update sitemap to enable view all customers.
7. Create a customer and verify the Data Source.

f Task 1: Create the Customers Web Form


• Create the Customers Web Form based on the master page, Site.master.
• Open the Customers Web Form in the Design view.

f Task 2: Add the SqlDataSource control to the Web Form


• Add the SqlDataSource control to the Customers.aspx Web Form.
• Rename the SqlDataSource control as CustomersSqlDataSource.
• Save the Customers Web Form.

f Task 3: Configure the SqlDataSource control


• In Design view, with the CustomersSqlDataSource control selected, display
the Smart Tag.
• Open the Configure Data Source Wizard.
• Select the CustomerManagementConnectionString connection string for the
CustomersSqlDataSource control.
• Configure the SELECT statement to include all the columns from the
Customers table, and ensure that it is possible to manipulate the data in the
data source, and use optimistic concurrency.
• Save the Customers Web Form.
8-56 Introduction to Web Development with Microsoft® Visual Studio® 2010

f Task 4: Add the ListView control to the Web Form


• Add the ListView control to the Customers Web Form.
• Rename the ListView control as CustomersListView.
• Bind the CustomersListView control to the CustomersSqlDataSource control
by using the Smart Tag.
• Enable paging in the CustomersListView control.
• Save the Customers Web Form.
• Build the user control, and fix any errors.
• View the Customers Web Form in the browser.
• Close Windows® Internet Explorer®.

f Task 5: Add code to manually save a customer to a data source


• Open the Customer user control in the Code view.
• Import the namespace used for accessing a SQL Server 2008 database,
System.Data.SqlClient.
• Import the namespace used with the disconnected ADO.NET layer,
System.Data.
• Import the namespace for reading the connection string from the web.config
file, System.Configuration.
• Locate the CustomerInsertButton_Click event handler.

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
Exit Sub
End If

' Add the current user name


currentCustomer.CreatedBy = Context.User.Identity.Name
' Add the user credit limit
currentCustomer.CreditLimit = 50000
End Sub
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-57

• Remove the assignment of the value 50000 to the CreditLimit property.

' Add the user credit limit


currentCustomer.CreditLimit = 50000

• Append the following code to the CustomerInsertButton_Click event


handler, by using a code snippet named ADO.NET Insert Customer. The
code snippet has been supplied by the senior developer, and is placed in the
My Code Snippets folder.

' Create and instantiate connection


Using customerManagementConnection As New SqlConnection()
' Initialize connection string from web.config
customerManagementConnection.ConnectionString =

ConfigurationManager.ConnectionStrings("CustomerManagementConnecti
onString").ConnectionString

' Open connection


customerManagementConnection.Open()
' Declare and instantiate data adapter
Dim customerManagementDataAdapter As New SqlDataAdapter()

' Declare and instantiate command objects


Dim selectCommand As New SqlCommand("SELECT * FROM Customers",
customerManagementConnection)
Dim insertCommand As New SqlCommand(
"INSERT INTO Customers (FirstName, LastName, Address,
ZipCode, City, State, CountryID, Phone, EmailAddress, " &
"Url, CreditLimit, NewsSubscriber, CreatedDate, CreatedBy)
VALUES(@FirstName, @LastName, @Address, @ZipCode, @City, @State, "
&
"@CountryID, @Phone, @EmailAddress, @WebAddress,
@CreditLimit, @NewsSubscriber, @CreatedDate, @CreatedBy)",
customerManagementConnection)

' Assign command objects


customerManagementDataAdapter.SelectCommand = selectCommand
customerManagementDataAdapter.InsertCommand = insertCommand

' Declare and instantiate parameter objects


Dim insertFirstNameParameter As New SqlParameter("@FirstName",
SqlDbType.NVarChar, 50, "FirstName")
Dim insertLastNameParameter As New SqlParameter("@LastName",
SqlDbType.NVarChar, 30, "LastName")

(Code continued on the following page.)


8-58 Introduction to Web Development with Microsoft® Visual Studio® 2010

Dim insertAddressParameter As New SqlParameter("@Address",


SqlDbType.NVarChar, 50, "Address")
Dim insertZipCodeParameter As New SqlParameter("@ZipCode",
SqlDbType.NVarChar, 10, "ZipCode")
Dim insertCityParameter As New SqlParameter("@City",
SqlDbType.NVarChar, 30, "City")
Dim insertStateParameter As New SqlParameter("@State",
SqlDbType.NVarChar, 30, "State")
Dim insertCountryIDParameter As New SqlParameter("@CountryID",
SqlDbType.UniqueIdentifier, 0, "CountryID")
Dim insertPhoneParameter As New SqlParameter("@Phone",
SqlDbType.VarChar, 30, "Phone")
Dim insertEmailAddressParameter As New
SqlParameter("@EmailAddress", SqlDbType.NVarChar, 50,
"EmailAddress")
Dim insertWebAddressParameter As New
SqlParameter("@WebAddress", SqlDbType.NVarChar, 80, "Url")
Dim insertCreditLimitParameter As New
SqlParameter("@CreditLimit", SqlDbType.Int, 0, "CreditLimit")
Dim insertNewsSubscriberParameter As New
SqlParameter("@NewsSubscriber", SqlDbType.Bit, 0,
"NewsSubscriber")
Dim insertCreatedDateParameter As New
SqlParameter("@CreatedDate", SqlDbType.SmallDateTime, 0,
"CreatedDate")
Dim insertCreatedByParameter As New SqlParameter("@CreatedBy",
SqlDbType.VarChar, 15, "CreatedBy")

' Assign parameters to command object


insertCommand.Parameters.Add(insertFirstNameParameter)
insertCommand.Parameters.Add(insertLastNameParameter)
insertCommand.Parameters.Add(insertAddressParameter)
insertCommand.Parameters.Add(insertZipCodeParameter)
insertCommand.Parameters.Add(insertCityParameter)
insertCommand.Parameters.Add(insertStateParameter)
insertCommand.Parameters.Add(insertCountryIDParameter)
insertCommand.Parameters.Add(insertPhoneParameter)
insertCommand.Parameters.Add(insertEmailAddressParameter)
insertCommand.Parameters.Add(insertWebAddressParameter)
insertCommand.Parameters.Add(insertCreditLimitParameter)
insertCommand.Parameters.Add(insertNewsSubscriberParameter)
insertCommand.Parameters.Add(insertCreatedDateParameter)
insertCommand.Parameters.Add(insertCreatedByParameter)

(Code continued on the following page.)


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-59

' Declare and instantiate dataset


Dim customerManagementDataSet As New
DataSet("CustomerManagementDataSet")
' Apply the full schema from the data source

customerManagementDataAdapter.FillSchema(customerManagementDataSet
, SchemaType.Source, "Customers")
customerManagementDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey
customerManagementDataAdapter.MissingMappingAction =
MissingMappingAction.Passthrough
' Populate Customers DataTable
customerManagementDataAdapter.Fill(customerManagementDataSet,
"Customers")

' Create new row locally


Dim newCustomerDataRow As DataRow =
customerManagementDataSet.Tables("Customers").NewRow()
newCustomerDataRow("ID") = Guid.NewGuid()
newCustomerDataRow("FirstName") = currentCustomer.FirstName
newCustomerDataRow("LastName") = currentCustomer.LastName
newCustomerDataRow("Address") = currentCustomer.Address
newCustomerDataRow("ZipCode") = currentCustomer.ZipCode
newCustomerDataRow("City") = currentCustomer.City
newCustomerDataRow("State") = currentCustomer.State
newCustomerDataRow("CountryID") = currentCustomer.CountryID
newCustomerDataRow("Phone") = currentCustomer.Phone
newCustomerDataRow("EmailAddress") =
currentCustomer.EmailAddress
newCustomerDataRow("Url") = currentCustomer.EmailAddress
newCustomerDataRow("CreditLimit") =
currentCustomer.CreditLimit
newCustomerDataRow("NewsSubscriber") =
currentCustomer.NewsSubscriber
newCustomerDataRow("CreatedDate") =
currentCustomer.CreatedDate
newCustomerDataRow("CreatedBy") = currentCustomer.CreatedBy

' Insert new row locally

customerManagementDataSet.Tables("Customers").Rows.Add(newCustomer
DataRow)

(Code continued on the following page.)


8-60 Introduction to Web Development with Microsoft® Visual Studio® 2010

' Update data source


If
customerManagementDataAdapter.Update(customerManagementDataSet,
"Customers") = 1 Then
' Instantiate new Customer object
currentCustomer = New
CustomerManagementEntities.Customer()
' Reload page to refresh with "blank" input controls
Response.Redirect("~/InsertCustomer.aspx")
End If
End Using

• Save the Customer code-behind file.

f Task 6: Update sitemap to enable view all customers


• Open the web.sitemap file.
• Append the new siteMapNode element to the Customers siteMapNode.

<siteMapNode title="All" description="View All Customers"


url="~/Customers.aspx" />

• Save and close the web.sitemap file.

f Task 7: Create a customer and verify the Data Source


• Build the CustomerManagement solution.
• Run the CustomerManagement Web application.
• Open the InsertCustomer Web Form, and click New on the Customers
menu.
• Create a new customer by using the following information, and then click the
Insert button:
• First Name: Kim
• Last Name: Abercrombie
• Address: 9876 Maine Road
• Zip Code: M24NG
• City: Manchester
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-61

• Country: Great Britain


• Phone: 0161-123 555
• Email Address: kim@litwareinc.com
• Web Address: http://www.litwareinc.com
• Credit Limit: 50000
• News Subscriber: Yes
• Check that the new customer has been added in the data source by using the
new Customers Web Form.
• Close Internet Explorer.

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.

f Task 1: Open an existing ASP.NET Web project


• Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.
• Open Microsoft Visual Studio 2010.
• Open the CustomerManagement solution from the
D:\Labfiles\Starter\M8\CS folder.

f Task 2: Add a SQL Server 2008 Express Database


• Add a new database folder named App_Data, and an existing database to the
database folder, D:\LabFiles\Starter\M8\CustomerManagement.mdf.

f Task 3: Add a data source control to the user control


• Open the Customer user control in Design view.
• Add a SqlDataSource control to the user control to connect to a SQL Server
database.
• Rename the SqlDataSource control as CountriesSqlDataSource.
• Save the Customer user control.
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-63

f Task 4: Configure a data source control


• In Design view, with the CountriesSqlDataSource control selected, display
the Smart Tag.
• Open the Configure Data Source Wizard, connect to the
CustomerManagement.mdf database, and then create a new connection
string named CustomerManagementConnectionString.
• Configure the SELECT statement to include the ID and Name columns from
the Countries table.
• Test the query, and check whether you get the correct data from the Countries
table.

Note: Ensure that the returned rows include the values for the ID and Name columns for
various countries.

• Save the Customer user control.


8-64 Introduction to Web Development with Microsoft® Visual Studio® 2010

Exercise 2: Binding a Server Control to a Data Source


The main tasks in this exercise are as follows:
1. Bind the DropDownList control to the data source.
2. Pass the values to the Customer object.

f Task 1: Bind the DropDownList control to a data source


• Open the Customer user control in Source view.
• Locate the markup for the CustomerCountryDropDownList control.
• Remove the static ListItem element from the
CustomerCountryDropDownList control.

<asp:ListItem>USA</asp:ListItem>

• Bind the CustomerCountryDropDownList control to the


CountriesSqlDataSource control by using the DataSourceID attribute.

DataSourceID="CountriesSqlDataSource"

• Set the value field of the CustomerCountryDropDownList control to the ID


column of the database by using the DataValueField attribute.

DataValueField="ID"

• Set the text field of the CustomerCountryDropDownList control to the Name


column of the database by using the DataTextField attribute.

DataTextField="Name"

• Build the user control, and fix any errors.


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-65

f Task 2: Pass the values to the Customer object


• Open the Customer user control in the Code view.
• Locate the code for the private instantiateCustomerObject method, and pass
the selected value of the CustomerCountryDropDownList control to the
Customer class constructor by using the SelectedValue property wrapped in a
new Guid object.

// Instantiate new Customer object with user input


currentCustomer = new CustomerManagementEntities.Customer(
null, CustomerFirstNameTextBox.Text,
CustomerLastNameTextBox.Text,
CustomerAddressTextBox.Text, CustomerZipCodeTextBox.Text,
CustomerCityTextBox.Text, CustomerStateTextBox.Text,
new Guid(CustomerCountryDropDownList.SelectedValue),
CustomerPhoneTextBox.Text,
CustomerEmailAddressTextBox.Text,
CustomerWebAddressTextBox.Text,
int.Parse(CustomerCreditLimitTextBox.Text),
CustomerNewsSubscriberCheckBox.Checked,
DateTime.Now, "", null, "");

• Build the user control, and fix any errors.


8-66 Introduction to Web Development with Microsoft® Visual Studio® 2010

Exercise 3: Modifying a Data Source


The main tasks in this exercise are as follows:
1. Create the Customers Web Form.
2. Add the SqlDataSource control to the Web Form.
3. Configure the SqlDataSource control.
4. Add the ListView control to the Web Form.
5. Add code to manually save a customer to a data source.
6. Update sitemap to enable view all customers.
7. Create a customer and verify the Data Source.

f Task 1: Create the Customers Web Form


• Create the Customers Web Form, based on the Site.master master page.
• Open the Customers Web Form in the Design view.

f Task 2: Add the SqlDataSource control to the Web Form


• Add the SqlDataSource control to the Customers.aspx Web Form.
• Rename the SqlDataSource control as CustomersSqlDataSource.
• Save the Customers Web Form.

f Task 3: Configure the SqlDataSource control


• In Design view, with the CustomersSqlDataSource control selected, display
the Smart Tag.

• Open the Configure Data Source Wizard.


• Select the CustomerManagementConnectionString connection string for the
CustomersSqlDataSource control.
• Configure the SELECT statement to include all the columns from the
Customers table, and ensure that it is possible to manipulate the data in the
data source, and use optimistic concurrency.

• Save the Customers Web Form.


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-67

f Task 4: Add the ListView control to the Web Form


• Add the ListView control to the Customers Web Form.
• Rename the ListView control as CustomersListView.
• Bind the CustomersListView control to the CustomersSqlDataSource control
by using the Smart Tag.
• Enable paging in the CustomersListView control.
• Save the Customers Web Form.
• Build the user control, and fix any errors.
• View the Customers Web Form in the browser.
• Close Internet Explorer.

f Task 5: Add code to manually save a customer to a data source


• Open the Customer user control in the Code view.
• Import the namespace used for accessing a SQL Server 2008 database,
System.Data.SqlClient.
• Import the namespace used with the disconnected ADO.NET layer,
System.Data.
• Import the namespace for reading the connection string from the web.config
file, System.Configuration.

• Locate the CustomerInsertButton_Click event handler.

protected void CustomerInsertButton_Click(object sender, EventArgs


e)
{
// Did page validation succeed?
if (!Page.IsValid)
return;

// Add the current user name


currentCustomer.CreatedBy = Context.User.Identity.Name;
// Add the user credit limit
currentCustomer.CreditLimit = 50000;
}
8-68 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Remove the assignment of the value 50000 to the CreditLimit property.

// Add the user credit limit


currentCustomer.CreditLimit = 50000;

• Append the following code to the CustomerInsertButton_Click event


handler, by using a code snippet named ADO.NET Insert Customer. The
code snippet has been supplied by the senior developer, and is placed in the
My Code Snippets folder.

// Create and instantiate connection


using (SqlConnection customerManagementConnection = new
SqlConnection())
{
// Initialize connection string from web.config
customerManagementConnection.ConnectionString =

ConfigurationManager.ConnectionStrings["CustomerManagementConnecti
onString"].ConnectionString;

// Open connection
customerManagementConnection.Open();
// Declare and instantiate data adapter
SqlDataAdapter customerManagementDataAdapter = new
SqlDataAdapter();

// Declare and instantiate command objects


SqlCommand selectCommand = new SqlCommand("SELECT * FROM
Customers",
customerManagementConnection);
SqlCommand insertCommand = new SqlCommand(
"INSERT INTO Customers (FirstName, LastName, Address,
ZipCode, City, State, CountryID, Phone, EmailAddress, " +
"Url, CreditLimit, NewsSubscriber, CreatedDate, CreatedBy)
VALUES(@FirstName, @LastName, @Address, @ZipCode, @City, @State, "
+
"@CountryID, @Phone, @EmailAddress, @WebAddress,
@CreditLimit, @NewsSubscriber, @CreatedDate, @CreatedBy)",
customerManagementConnection);

// Assign command objects


customerManagementDataAdapter.SelectCommand = selectCommand;
customerManagementDataAdapter.InsertCommand = insertCommand;

(Code continued on the following page.)


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-69

// Declare and instantiate parameter objects


SqlParameter insertFirstNameParameter = new
SqlParameter("@FirstName", SqlDbType.NVarChar, 50, "FirstName");
SqlParameter insertLastNameParameter = new
SqlParameter("@LastName", SqlDbType.NVarChar, 30, "LastName");
SqlParameter insertAddressParameter = new
SqlParameter("@Address", SqlDbType.NVarChar, 50, "Address");
SqlParameter insertZipCodeParameter = new
SqlParameter("@ZipCode", SqlDbType.NVarChar, 10, "ZipCode");
SqlParameter insertCityParameter = new SqlParameter("@City",
SqlDbType.NVarChar, 30, "City");
SqlParameter insertStateParameter = new SqlParameter("@State",
SqlDbType.NVarChar, 30, "State");
SqlParameter insertCountryIDParameter = new
SqlParameter("@CountryID", SqlDbType.UniqueIdentifier, 0,
"CountryID");
SqlParameter insertPhoneParameter = new SqlParameter("@Phone",
SqlDbType.VarChar, 30, "Phone");
SqlParameter insertEmailAddressParameter = new
SqlParameter("@EmailAddress", SqlDbType.NVarChar, 50,
"EmailAddress");
SqlParameter insertWebAddressParameter = new
SqlParameter("@WebAddress", SqlDbType.NVarChar, 80, "Url");
SqlParameter insertCreditLimitParameter = new
SqlParameter("@CreditLimit", SqlDbType.Int, 0, "CreditLimit");
SqlParameter insertNewsSubscriberParameter = new
SqlParameter("@NewsSubscriber", SqlDbType.Bit, 0,
"NewsSubscriber");
SqlParameter insertCreatedDateParameter = new
SqlParameter("@CreatedDate", SqlDbType.SmallDateTime, 0,
"CreatedDate");
SqlParameter insertCreatedByParameter = new
SqlParameter("@CreatedBy", SqlDbType.VarChar, 15, "CreatedBy");

// Assign parameters to command object


insertCommand.Parameters.Add(insertFirstNameParameter);
insertCommand.Parameters.Add(insertLastNameParameter);
insertCommand.Parameters.Add(insertAddressParameter);
insertCommand.Parameters.Add(insertZipCodeParameter);
insertCommand.Parameters.Add(insertCityParameter);
insertCommand.Parameters.Add(insertStateParameter);
insertCommand.Parameters.Add(insertCountryIDParameter);
insertCommand.Parameters.Add(insertPhoneParameter);
insertCommand.Parameters.Add(insertEmailAddressParameter);

(Code continued on the following page.)


8-70 Introduction to Web Development with Microsoft® Visual Studio® 2010

insertCommand.Parameters.Add(insertWebAddressParameter);
insertCommand.Parameters.Add(insertCreditLimitParameter);
insertCommand.Parameters.Add(insertNewsSubscriberParameter);
insertCommand.Parameters.Add(insertCreatedDateParameter);
insertCommand.Parameters.Add(insertCreatedByParameter);

// Declare and instantiate dataset


DataSet customerManagementDataSet = new
DataSet("CustomerManagementDataSet");
// Apply the full schema from the data source

customerManagementDataAdapter.FillSchema(customerManagementDataSet
, SchemaType.Source, "Customers");
customerManagementDataAdapter.MissingSchemaAction =
MissingSchemaAction.AddWithKey;
customerManagementDataAdapter.MissingMappingAction =
MissingMappingAction.Passthrough;
// Populate Customers DataTable
customerManagementDataAdapter.Fill(customerManagementDataSet,
"Customers");

// Create new row locally


DataRow newCustomerDataRow =
customerManagementDataSet.Tables["Customers"].NewRow();
newCustomerDataRow["ID"] = Guid.NewGuid();
newCustomerDataRow["FirstName"] = currentCustomer.FirstName;
newCustomerDataRow["LastName"] = currentCustomer.LastName;
newCustomerDataRow["Address"] = currentCustomer.Address;
newCustomerDataRow["ZipCode"] = currentCustomer.ZipCode;
newCustomerDataRow["City"] = currentCustomer.City;
newCustomerDataRow["State"] = currentCustomer.State;
newCustomerDataRow["CountryID"] = currentCustomer.CountryID;
newCustomerDataRow["Phone"] = currentCustomer.Phone;
newCustomerDataRow["EmailAddress"] =
currentCustomer.EmailAddress;
newCustomerDataRow["Url"] = currentCustomer.EmailAddress;
newCustomerDataRow["CreditLimit"] =
currentCustomer.CreditLimit;
newCustomerDataRow["NewsSubscriber"] =
currentCustomer.NewsSubscriber;
newCustomerDataRow["CreatedDate"] =
currentCustomer.CreatedDate;
newCustomerDataRow["CreatedBy"] = currentCustomer.CreatedBy;

(Code continued on the following page.)


Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-71

// Insert new row locally

customerManagementDataSet.Tables["Customers"].Rows.Add(newCustomer
DataRow);

// Update data source


if
(customerManagementDataAdapter.Update(customerManagementDataSet,
"Customers") == 1)
{
// Instantiate new Customer object
currentCustomer = new
CustomerManagementEntities.Customer();
// Reload page to refresh with "blank" input controls
Response.Redirect("~/InsertCustomer.aspx");
}
}

• Save the Customer code-behind file.

f Task 6: Update sitemap to enable view all customers


• Open the web.sitemap file.
• Append the new siteMapNode element to the Customers siteMapNode.

<siteMapNode title="All" description="View All Customers"


url="~/Customers.aspx" />

• Save and close the web.sitemap file.

f Task 7: Create a customer and verify the Data Source


• Build the CustomerManagement solution.
• Run the CustomerManagement Web application.
• Open the InsertCustomer Web Form.
• Create a new customer by using the following information, and then click the
Insert button:
• First Name: Kim
• Last Name: Abercrombie
8-72 Introduction to Web Development with Microsoft® Visual Studio® 2010

• Address: 9876 Maine Road


• Zip Code: M24NG
• City: Manchester
• Country: Great Britain
• Phone: 0161-123 555
• Email Address: kim@litwareinc.com
• Web Address: http://www.litwareinc.com
• Credit Limit: 50000
• News Subscriber: Yes
• Check that the new customer has been added in the data source by using the
new Customers Web Form.
• Close Internet Explorer.

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

Review Questions and Answers


1. How can you enable paging for a GridView control?
2. How do you connect to a SQL Server database?
8-74 Introduction to Web Development with Microsoft® Visual Studio® 2010

Module Review and Takeaways

Review Questions and Answers


1. How do you create a connection to a database in Visual Studio 2010?
2. Which object is used to facilitate transport from the data source to a DataSet
object and back again??
3. What is the main difference between a DataSet and a DataReader object?
Managing Data in a Microsoft® ASP.NET 4.0 Web Application 8-75

Real-World Issues and Scenarios


1. You need to connect to an Oracle database. What is the easiest way to connect
to the Oracle database?
Use the OLE DB .NET Framework Data Provider.
2. On a production server—where many connections are opened to the database—
it appears that after a few days of uptime, the Web server and the database
server slow down due to increased amount of memory and connection
resources being used. What is the first thing you should check?
You should check if you have closed your connection objects correctly.

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.

You might also like