Sei sulla pagina 1di 671

QuickStart Intelligence

O F F I C I A L

M I C R O S O F T

L E A R N I N G

P R O D U C T

10267A
Introduction to Web Development with
Microsoft Visual Studio 2010

Volume 1

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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, and Windows 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-47855
Released: 07/2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Introduction to Web Development with Microsoft Visual Studio 2010

iii

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

iv

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

vi

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Introduction to Web Development with Microsoft Visual Studio 2010

vii

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

viii

Introduction to Web Development with Microsoft Visual Studio 2010

Acknowledgements
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 ThomsenSubject 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 WrightTechnical 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Introduction to Web Development with Microsoft Visual Studio 2010

ix

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 .NETBased Languages
Lesson 1: Choosing a Programming Language

2-3

Lesson 2: Overview of Visual Studio 2010

2-13

Lesson 3: Creating a Simple Web Application

2-26

Lab: Creating Web Applications by Using Microsoft Visual Studio 2010


and Microsoft .NETBased Languages

2-41

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

Lab: Creating a Microsoft ASP.NET Web Form

3-27

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


Lesson 1: Working with Code-Behind Files

4-3

Lesson 2: Handling Server Control Events

4-11

Lesson 3: Creating Classes and Components by Using Visual Studio 2010

4-26

Lesson 4: Handling Page Events

4-44

Lab: Adding Functionality to a Microsoft ASP.NET Web Form

4-51

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

Lab: Implementing Master Pages and User Controls

5-35

Module 6: Validating User Input


Lesson 1: Overview of User Input Validation

6-3

Lesson 2: ASP.NET Validation Controls

6-8

Lesson 3: Validating Web Forms

6-28

Lab: Validating User Input

6-33

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Introduction to Web Development with Microsoft Visual Studio 2010

Module 7: Troubleshooting Microsoft ASP.NET Web Applications


Lesson 1: Debugging in ASP.NET

7-3

Lesson 2: Tracing in ASP.NET

7-17

Lab: Troubleshooting Microsoft ASP.NET Web Applications

7-25

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

Lesson 3: Managing Data

8-23

Lab: Managing Data in an ASP.NET 4.0 Web Application

8-36

Module 9: Managing Data Access Tasks by Using LINQ


Lesson 1: Overview of LINQ

9-3

Lesson 2: Managing XML Data by Using LINQ to XML

9-21

Lesson 3: Managing SQL Data by Using LINQ to SQL and


LINQ to Entities

9-40

Lab: Managing Data Access Tasks by Using LINQ

9-58

Module 10: Managing Data by Using Microsoft ASP.NET Dynamic Data


Lesson 1: Overview of ASP.NET Dynamic Data

10-3

Lesson 2: Applying ASP.NET Dynamic Data

10-24

Lesson 3: Customizing ASP.NET Dynamic Data Applications

10-34

Lab: Managing Data by Using ASP.NET Dynamic Data

10-46

Module 11: Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application


Lesson 1: Introduction to Ajax

11-3

Lesson 2: Creating an ASP.NET Ajax Application by Using the


Ajax Features for ASP.NET

11-9

Lesson 3: Extending an ASP.NET Web Forms Application by


Using the Ajax Control Toolkit

11-29

Lab: Creating a Microsoft ASP.NET Ajax-enabled


Web Forms Application

11-38

Module 12: Consuming Microsoft Windows Communication Foundation Services


Lesson 1: Overview of Windows Communication Foundation Services

12-3

Lesson 2: Calling Windows Communication Foundation Services

12-12

Lesson 3: Working with WCF Data Services

12-23

Lab: Consuming Windows Communication Foundation Services

12-36

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

About This Course

xi

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

xii

About This Course

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

About This Course

xiii

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

xiv

About This Course

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.

Module Reviews and Takeaways: Provide improved on-the-job reference material to boost
knowledge and skills retention.

Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when its
needed.

Course Companion Content on the http://www.microsoft.com/learning/companionmoc/ Site:


Searchable, easy-to-navigate digital content with integrated premium on-line resources designed to
supplement the Course Handbook.

Modules: Include companion content, such as questions and answers, detailed demo steps and
additional reading links, for each lesson. Additionally, they include Lab Review questions and answers
and Module Reviews and Takeaways sections, which contain the review questions and answers, best
practices, common issues and troubleshooting tips with answers, and real-world issues and scenarios
with answers.
Resources: Include well-categorized additional resources that give you immediate access to the most
up-to-date premium content on TechNet, MSDN, Microsoft Press

Student Course files on the http://www.microsoft.com/learning/companionmoc/ Site: Includes the


Allfiles.exe, a self-extracting executable file that contains all the files required for the labs and
demonstrations.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

About This Course

xv

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 Microsoft Virtual Server 2005 R2 with SP1 to perform the labs.
The following table shows the role of each virtual machine used in this course:
Virtual machine
10267A-GEN-DEV

Role
Stand-alone machine

Software Configuration
The following software is installed on each VM:

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

xvi

About This Course

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lesson 3: Overview of the Lab Application

1-26

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-5

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-7

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.

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 uniformlyfrom very small devices, to servers, to
the cloudby using the same programming model and tool chain throughout.

Question: What are the main advantages of using the .NET Framework to develop Web applications?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-8

Introduction to Web Development with Microsoft Visual Studio 2010

Components of the .NET Framework

Key Points
The .NET environment consists of various components that help you build and run .NETbased
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 factorssuch 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.

During development, CLR provides features that simplify development in multiple programming
languagesfor 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, objectoriented 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 libraryalso 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.NETbased applications. In addition, you can
extend classes by creating your own libraries. All applications and all Microsoft .NETbased 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-9

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#. Thirdparty organizations also can provide additional languages.

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

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
Explorer

Creates application domains to run managed controls. The .NET 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-10

Introduction to Web Development with Microsoft Visual Studio 2010

Runtime host

Description

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-11

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)

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-12

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson 2

Overview of ASP.NET

ASP.NET is a programming framework for building Web applications. ASP.NET Web Formswhich are
part of an ASP.NET Web applicationprovide 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.

Describe the process of generating and rendering markup and code.

Describe the ASP.NET dynamic compilation execution model.

Describe the ASP.NET extensions.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-13

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-14

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-15

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-16

Introduction to Web Development with Microsoft Visual Studio 2010

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.
The following table describes the various features of ASP.NET.
Feature

Description

Page and controls


framework

Page and controls framework encapsulates common UI 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
provider

ASP.NET always runs with a particular Windows identity; 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
functionality

ASP.NET provides intrinsic state management 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.

Health monitoring
and performance
features

ASP.NET includes features that enable you to monitor the 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-17

Feature

Description

Troubleshooting
support

ASP.NET takes advantage of the run-time debugging 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
services

ASP.NET supports Web-based WCF services. A Web-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
environment and
application life-cycle
management

ASP.NET includes an extensible hosting environment that controls the life


cycle of an application from the time a user first accesses a resourcesuch
as a page in the applicationto the time when which the application is shut
down.

Extensible designer
environment

ASP.NET includes enhanced designer support for Web server controls for
use with a visual design tool such as Visual Studio 2010.

ASP.NET Dynamic
Data

ASP.NET Dynamic Data is a framework that lets you easily create data-driven
ASP.NET Web applications. This is done by automatically discovering datamodel metadata at run time, and deriving UI behavior from it. ASP.NET
Dynamic Data is covered in Module 10.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-18

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-19

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-20

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.

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 pagenot

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-21

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 iteven on the live serverand 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-22

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

2.

1-23

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-24

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-25

connected to a data source, you can use ASP.NET Dynamic Data to create a fully functional and datadriven 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."

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-26

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-27

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-28

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-29

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

NewCreates a new customer row.


AllShows all customer rows.

Countries

NewCreates a new country row.


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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-30

Introduction to Web Development with Microsoft Visual Studio 2010

Field

Description

First Name

The first name of the customer is limited to 50 characters. This field is


mandatory.

Last Name

The last name of the customer is limited to 30 characters. This field is mandatory.

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 09, 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 readonly.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

Field

1-31

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

This is the 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. This
field is mandatory.

International
Dialing Code

This is the code or 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.

Internet Top Level


Domain

This is the country-specific Top-Level Domain (TLD) for Internet 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 validationwhich must take place on both client-side and server-sideincludes 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.

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 validationwhich
must take place on both client-side and server-sideincludes 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-32

Introduction to Web Development with Microsoft Visual Studio 2010

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
(T-SQL) function

Field name

Data type

Size

Required

Description

ID

uniqueidentifier

N/A

Yes

FirstName

nvarchar

50

Yes

This is the first name of the


customer. This is a nonunique, non-clustered index
that is sorted in ascending
order.

LastName

nvarchar

30

Yes

This is the last name of the


customer. This is a nonunique, 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, nonclustered index sorted in
ascending order.

State

nvarchar

30

No

This is the name of the state


or region in which the
customer lives.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

Field name

Data type

Default value /
Transact-SQL
(T-SQL) function

1-33

Size

Required

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


customers Web site.

CreditLimit

int

N/A

Yes

NewsSubscri
ber

bit

CreatedDate

smalldatetime

50,000

No

N/A

Yes

Description

This is the credit limit


assigned to the customer.
This indicates whether or not
the customer subscribes to
Contoso newsletters.

getdate()

This is the date that the


customer row is created in
the application. It is
automatically assigned by the
database.

The Countries table includes the following fields.


Default value /
Transact-SQL
(T-SQL) function

Field name

Data type

Size

Required

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
Format

varchar

30

No

This is the format for


displaying and entering a
phone number.

DialingCountry
Code

varchar

Yes

This is the 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-34

Introduction to Web Development with Microsoft Visual Studio 2010

Field name

Data type

Size

Required

Default value /
Transact-SQL
(T-SQL) function

Description
originates.

International
DialingCode

varchar

Yes

This is the code or 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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-35

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 Formlike the other Web forms in the applicationis based on the Site.master master
page. Users can browse to other Web Forms by using the Menu or SiteMapPath controls.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-36

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.

2.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

5.

6.

1-37

Explore how Dynamic Data works.

Run the solution.

On the Customers menu, click All.

On the Countries menu, click All.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-38

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.

2.

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


Name: WebSite1
Location: File system
Language: Visual Basic or Visual C#

3.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

4.

5.

6.

1-39

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.

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.

Add code to the Button Click event.

In the Default.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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-40

Introduction to Web Development with Microsoft Visual Studio 2010

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.

2.

Examine the ASP.NET folders.

3.

In Solution Explorer, review the ASP.NET folders, and if time allows create a new one.

Examine the Web Forms, designer code files, code-behind files, and class files.

4.

In Solution Explorer, notice the solution and project files, and identify where project references
go.

In Solution Explorer, review the various files.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-41

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-42

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?

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Exploring Microsoft ASP.NET Web Applications in Microsoft Visual Studio 2010

1-43

Tools
Tool

Purpose

Where to find it

Visual Studio 2010

Developing Web
applications

Start menu

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

1-44

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-1

Module 2
Creating Web Applications by Using Microsoft Visual
Studio 2010 and Microsoft .NETBased Languages
Contents:
Lesson 1: Choosing a Programming Language

2-3

Lesson 2: Overview of Visual Studio 2010

2-13

Lesson 3: Creating a Simple Web Application

2-26

Lab: Creating Web Applications by Using Microsoft Visual Studio 2010


and Microsoft .NETBased Languages

2-41

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased 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
programmers 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).
For a programming language to be compatible with the .NET Framework, the corresponding compilerat
build timemust 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 languageMSIL. 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-4

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson Objectives
After completing this lesson, you will be able to:

Describe the features of Visual Basic.

Describe the features of Visual C#.

Describe the scenarios for mixed-language environments.

Describe the considerations for choosing between Visual Basic and Visual C# for an application.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased 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.

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 Frameworkbased 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 33has been inserted by the editor by pressing ENTER, after typing the Implements
IDisposable statement.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-6

Introduction to Web Development with Microsoft Visual Studio 2010

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-7

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, Ajaxbased Web applications, device applications, and Silverlight
applications.

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 Frameworkbased languages. The default color displays keywords colored in blue, and
strings colored in red. Visual C# also provides a background compilation modelsimilar to Visual Basic
Text Editorin 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();
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-8

Introduction to Web Development with Microsoft Visual Studio 2010

8
9
10
11 }

}
#endregion

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.

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;

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 typefor example, Services.Customersthen the actual namespace for the type is
Services.Customers, because the default namespace is ignored. In addition, types in project subfolders

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-9

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 constructssuch as pointers
are allowed. By default, numeric operations are not checked, thus allowing numeric overflow and numeric
underflow.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-10

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-11

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-12

Introduction to Web Development with Microsoft Visual Studio 2010

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-13

Lesson 2

Overview of Visual Studio 2010

Visual Studio 2010 is a comprehensive tool for creating all types of .NET Frameworkbased 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-14

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. IntelliSensebased code completion enables you to quickly produce accurate code. Powerful, endto-end, cross-language debugging support helps you to make your applications more robust.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-15

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.

Debugging Support
Visual Studio 2010 supports debugging from your initial code, through to the applications 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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-16

Introduction to Web Development with Microsoft Visual Studio 2010

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.
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 Explorerwhich provides a graphical view of your solutionto organize and
manage all of your application projects and files.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-17

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
application

Creates an ASP.NET Web application with the basic server 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.

ASP.NET Ajax server


control

Creates custom ASP.NET Ajax server controls. This template 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 you require for
Entities Web site
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 you require for
LINQ To SQL Web site 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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-18

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:

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 elementssuch as
variable names and keywordsare 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 windowthe Class Name list on the left, and the Method Name list on the right. The Class Name

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-19

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.

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 optionsincluding adding, building and editing pagesright-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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-20

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-21

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-22

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-23

Question: What are the four views available for editors and designers?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-24

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-25

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-26

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-27

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.

2.

3.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-28

Introduction to Web Development with Microsoft Visual Studio 2010

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.

5.

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.

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-29

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.
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 Basicspecific 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 informationincluding assembly

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-30

Introduction to Web Development with Microsoft Visual Studio 2010

Type

Name

Description
version and assembly attributesabout the assembly.

Files

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.

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
Default.aspx.designer.vb

The design-time partial class for the Web Form.

Web.config

The Web configuration file that contains the configuration


settings for the Web application.

WebApplicationName.csproj or
WebApplicationName.vbproj

The XML document that contains references to all project


itemssuch as forms and classesin addition to project
references and compilation options.

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


or
WebApplicationName.vbproj.use
r

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-31

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-32

Introduction to Web Development with Microsoft Visual Studio 2010

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


About.aspx.vb or About.aspx.cs

This is the About Web Form and the corresponding code-behind file.
The Web form displays an About this Web site message.

Default.aspx, and

This is the Default Web Form and the corresponding code-behind file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

Folder/file name

Description

Default.aspx.vb or
Default.aspx.cs

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 Site.master.cs

This is the master page and the related code-behind file for the Web
site.

Web.config

This is configuration file for the Web site.

2-33

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-34

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-35

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-36

Introduction to Web Development with Microsoft Visual Studio 2010

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

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 filealso known as the ASP.NET application
fileis 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-37

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 stylessuch as fonts, colors, and spacingto Web
documents. Styles.css is the default style sheet file for the Web application.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-38

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.

2.

Create a Web application project.


a.
b.
c.

3.

4.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

In the Start Page Microsoft Visual Studio window, on the File menu, click New Project.
In the New Project dialog box, in the left pane, click either Visual Basic or Visual C#.
In the middle pane, click ASP.NET Web Application, and then click OK.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-39

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

Place the breakpoint by clicking the mouse at the beginning of the code where you check for the
PostBack.
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.

d.
e.
f.
g.

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.
Click the Button to post back to the server.
In the Default.aspx.vb or Default.aspx.cs code window, step through the lines of code by pressing
F10.
In the http://localhost:1186/Default.aspx-Original Source window, click the Close button.
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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-40

Introduction to Web Development with Microsoft Visual Studio 2010

Deploying a Web Application

Key Points
After creating and testing your Web applicationwhether based on the ASP.NET Web site or the ASP.NET
Web application templateyou 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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-41

Lab: Creating Web Applications by Using Microsoft


Visual Studio 2010 and Microsoft .NETBased
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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-42

Introduction to Web Development with Microsoft Visual Studio 2010

Password: Pa$$w0rd

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-43

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-44

Introduction to Web Development with Microsoft Visual Studio 2010

Section 1: 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.

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#

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.

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.

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 systembased ASP.NET site, and
added styles to the Web site.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-45

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.

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.

Task 2: Close Visual Studio 2010

Save modified files.

Close Visual Studio 2010.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-46

Introduction to Web Development with Microsoft Visual Studio 2010

Font-size: 22

Color: Gray

Save the changes, and view the default Web Form in a Web browser.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-47

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-48

Introduction to Web Development with Microsoft Visual Studio 2010

Section 2: 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.

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

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.

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.

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 systembased ASP.NET site, and
added styles to the Web site.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-49

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.

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.

Task 2: Close Visual Studio 2010

Save modified files.

Close Visual Studio 2010.

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.

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.

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:

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-50

Introduction to Web Development with Microsoft Visual Studio 2010

Font-family: Trebuchet MS

Font-size: 22

Color: Gray

Save the changes, and view the default Web Form in a Web browser.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-51

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-52

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft .NETBased Languages

2-53

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?

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


graphical interface for control
placement.

Visual Studio IDE

Solution Explorer

Displays the hierarchy of project


files, and enables you to move
and modify files.

Visual Studio IDE

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

2-54

Introduction to Web Development with Microsoft Visual Studio 2010

Tool

Function

Where to find it

Properties window

Enables you to adjust the


properties of documents, classes,
and controls.

Visual Studio IDE

Task List

Enables you to track the status of


tasks as you develop your
application.

Visual Studio IDE

Output

Displays status messages for


various features in IDE.

Visual Studio IDE

Toolbox

Enables you to use a drag-andVisual Studio IDE


drop operation on the controls in
your application.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lab: Creating a Microsoft ASP.NET Web Form

3-28

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-5

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

The attributes of a page directive include:

AutoEventWireUp. The AutoEventWireUp attribute is used to indicate if the event methods pagelevel events are automatically wired up. This means that the Page_Load event, for instance, is
automatically wired up to be caught and handledif you add the corresponding event handler and
add some code to itto 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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-6

Introduction to Web Development with Microsoft Visual Studio 2010

Note: When you create a Web Form and select the option to place code in a separate file (which
is the default), the CodeFile and Inherits attributes are used in a two-file configuration. Singlefile 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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-7

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>

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-8

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.

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-9

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-10

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 controlssuch as buttons, text boxes, and listsare 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.

Add and configure HTML server controls.

Add and configure Web server controls.

Determine the appropriate server control for a Web Form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-11

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-12

Introduction to Web Development with Microsoft Visual Studio 2010

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

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-13

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

An anchor element that


links to another page,
image, or other resource.

<a href="/Page2.aspx"
title="Go To Page 2.">Page 2</a>

br

A self-closing element
that adds a line break to
the page.

<br />

img

A self-closing element
that embeds an image on
the page.

<img src="/login.png"
alt="Log in to web application." />

input

Specifies different types of


input elements, including

<input type="text"

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-14

Introduction to Web Development with Microsoft Visual Studio 2010

Element
name

Description

Example

a submit button, text box,


check box, radio button,
file selection control, and
a hidden control.

name="UserName">

select

Creates a selection menu


with at least one option.

<select size="3"
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>

Web Server Controls


Web server controls include form-type controlssuch as buttons, lists, and text boxesand specialpurpose 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.

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

HTML control equivalent

Web server control 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

Web server control

HTML control equivalent

Web server control function

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

Creates a list of choices, 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.

3-15

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-16

Introduction to Web Development with Microsoft Visual Studio 2010

Control

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-17

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-18

Introduction to Web Development with Microsoft Visual Studio 2010

Control

Function

SiteMapPath

Displays a navigation path/breadcrumb showing the current page location.

TreeView

Displays hierarchical data in a tree structure.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-19

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-20

Introduction to Web Development with Microsoft Visual Studio 2010

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

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 pagesuch as a control that displays a grid of
datayou can disable the View state but not the control state.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-21

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-22

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-23

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-24

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-25

Question: What are the additional features offered by Web server controls?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-26

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-27

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 functionalitysuch as a calendar or an advertisementthat 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-28

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-29

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-30

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-31

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.

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.

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-32

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-33

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-34

Introduction to Web Development with Microsoft Visual Studio 2010

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.

Add the Label control from the Toolbox to the twelfth cell of the left column in the div element,
change the (ID) property to CustomerNewsSubscriberLabel, and then set the Text property to
News Subscriber:.

Add the CheckBox control from the Toolbox to the twelfth cell of the right column in the div
element, and change the (ID) property to CustomerNewsSubscriberCheckBox.

Save the changes, and view the InsertCustomer Web Form in a Web browser.

Add the Button control from the Toolbox to the footer of the table in the div element, change the
(ID) property to CustomerInsertButton, and then set the Text property to Insert.

Add the Button control from the Toolbox to the footer of the table in the div element, change the
(ID) property to CustomerCancelButton, and then set the Text property to Cancel.

Save the changes, and view the InsertCustomer Web Form in a Web browser.

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-35

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-36

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-37

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-38

Introduction to Web Development with Microsoft Visual Studio 2010

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

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.

3-39

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-40

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Web Form

3-41

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

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 tasksuch as using a Label control instead of a
TextBox controlto 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

3-42

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lesson 2: Handling Server Control Events

4-11

Lesson 3: Creating Classes and Components by Using Visual Studio 2010

4-26

Lesson 4: Handling Page Events

4-44

Lab: Adding Functionality to a Microsoft ASP.NET Web Form

4-51

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-3

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-4

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-5

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-6

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-7

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-8

Introduction to Web Development with Microsoft Visual Studio 2010

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)
{
}

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-9

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 filesthe .aspx page, and the code-behind filethat 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.

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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-10

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-11

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-12

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.

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>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-13

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-14

Introduction to Web Development with Microsoft Visual Studio 2010

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.
...
<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();");

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-15

The code requires that the JavaScript function be part of the markup. This can be either explicitas
shown in the preceding exampleor 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);

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-16

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 serverside 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.
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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-17

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 Frameworkbased 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
resources directly

No

Yes

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 clientside code and event handlers.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-18

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-19

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-20

Introduction to Web Development with Microsoft Visual Studio 2010

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-21

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.

2.

3.

4.

To log on 10267A-GEN-DEV, use the following user credentials:

User name: Student

Password: Pa$$w0rd

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-22

Introduction to Web Development with Microsoft Visual Studio 2010

5.

In Toolbox, under Standard, double-click the Label control.

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)
{
...
}

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-23

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-24

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-25

Setting Web Server Control Properties


You can output information directly to a Web server control by using the controls 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, clientside 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-26

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-27

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-28

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-29

Creating a Component

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.

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

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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-30

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-31

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.

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.

3.

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.

Create a method that returns a string on the Class file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-32

Introduction to Web Development with Microsoft Visual Studio 2010

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.

5.

On the Build menu of Visual Studio 2010, click Build Solution.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-33

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-34

Introduction to Web Development with Microsoft Visual Studio 2010

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 nothingthey 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.
When adding groups of code to a classespecially if a group or block of code is longoften 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-35

Question: What are member variables and constants?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-36

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-37

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

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

The two read-write properties, ID and Name, are public to any user of the class. Notice that the setters
and getterswhich are used to set and get the value of the property or the property-backing fieldcan
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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-38

Introduction to Web Development with Microsoft Visual Studio 2010

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-39

Adding Class Constructors

Key Points
Any classunless it is made abstractneeds 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.
[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)
{
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-40

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-41

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-42

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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:

4.

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

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();

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-43

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-44

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-45

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-46

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-47

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-48

Introduction to Web Development with Microsoft Visual Studio 2010

...

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-49

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

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-50

Introduction to Web Development with Microsoft Visual Studio 2010

2.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-51

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-52

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-53

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-54

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.

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.

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.

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

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-55

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.

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.

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

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

customerZipCode As String = Nothing


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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-56

Introduction to Web Development with Microsoft Visual Studio 2010

Private customerModifiedBy As String = Nothing

Task 3: Add the properties

In the Customer class, add a region named Properties, below the Class member fields region.
#Region "Properties"
#End Region

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

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)

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-57

' 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

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-58

Introduction to Web Development with Microsoft Visual Studio 2010

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

<summary>
The ID of the country in which the customer lives
</summary>
<value></value>
<returns></returns>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-59

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-60

Introduction to Web Development with Microsoft Visual Studio 2010

''' <remarks></remarks>
Public Property WebAddress() As String
Get
Return Me.customerWebAddress
End Get
Set(ByVal value As String)
If (value Is Nothing) Then
Me.customerWebAddress = ""
Else
' Only get the first 80 characters
If (value.Length > 80) Then
Me.customerWebAddress = value.Substring(0, 80)
Else
Me.customerWebAddress = value
End If
End If
End Set
End Property
''' <summary>
''' The current credit limit of the customer
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property CreditLimit() As Integer
Get
Return Me.customerCreditLimit
End Get
Set(ByVal value As Integer)
' Negative value?
If value < 0 Then
Me.customerCreditLimit = 0
Else
Me.customerCreditLimit = value
End If
End Set
End Property
''' <summary>
''' Does the customer subscriber to news?
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property NewsSubsriber() As Boolean
Get
Return Me.customerNewsSubscriber
End Get
Set(ByVal value As Boolean)
Me.customerNewsSubscriber = value
End Set
End Property
''' <summary>
''' The date the customer was created in the system
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property CreatedDate() As DateTime?
Get
Return Me.customerCreatedDate
End Get

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-61

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-62

Introduction to Web Development with Microsoft Visual Studio 2010

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

Task 4: Add the constructors

In the Customer class, add a region named Constructors below the Properties region.
#Region "Constructors"
#End Region

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>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-63

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

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-64

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-65

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.

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

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-66

Introduction to Web Development with Microsoft Visual Studio 2010

' 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

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-67

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-68

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-69

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.

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.

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.

Task 3: Create an event procedure for the Page_LoadComplete event


protected void Page_LoadComplete(object sender, EventArgs e)
{
}

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-70

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.

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.

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;

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

string customerZipCode = null;


string customerCity = null;
string customerState = null;
Guid? customerCountryID = null;
string customerPhone = null;
string customerEmailAddress = null;
string customerWebAddress = null;
int customerCreditLimit = 0;
bool customerNewsSubscriber = false;
DateTime? customerCreatedDate = null;
string customerCreatedBy = null;
DateTime? customerModifiedDate = null;

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-71

private string customerModifiedBy = null;

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-72

Introduction to Web Development with Microsoft Visual Studio 2010

else
this.customerLastName = value;

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

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
{

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

get
{
}
set
{

4-73

return this.customerCity;

// Null value?
if (value == null)
this.customerCity = "";
else
// 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;
}
}
/// <summary>
/// The customer phone number
/// </summary>
public string Phone
{
get
{
return this.customerPhone;

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-74

Introduction to Web Development with Microsoft Visual Studio 2010

}
set
{

// Null value?
if (value == null)
this.customerPhone = "";
else
// Only get the first 30 characters
if (value.Length > 30)
this.customerPhone = value.Substring(0, 30);
else
this.customerPhone = value;

/// <summary>
/// The customer e-mail address
/// </summary>
public string EmailAddress
{
get
{
return this.customerEmailAddress;
}
set
{
// Null value?
if (value == null)
this.customerEmailAddress = "";
else
// Only get the first 50 characters
if (value.Length > 50)
this.customerEmailAddress = value.Substring(0, 50);
else
this.customerEmailAddress = value;
}
}
/// <summary>
/// The customer Web address
/// </summary>
public string WebAddress
{
get
{
return this.customerWebAddress;
}
set
{
// Null value?
if (value == null)
this.customerWebAddress = "";
else
// Only get the first 80 characters
if (value.Length > 80)
this.customerWebAddress = value.Substring(0, 80);
else
this.customerWebAddress = value;
}
}
/// <summary>
/// The current credit limit of the customer
/// </summary>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-75

public int CreditLimit


{
get
{
return this.customerCreditLimit;
}
set
{
// Negative value?
if (value < 0)
this.customerCreditLimit = 0;
else
this.customerCreditLimit = value;
}
}
/// <summary>
/// Does the customer subscriber to news?
/// </summary>
public bool NewsSubscriber
{
get
{
return this.customerNewsSubscriber;
}
set
{
this.customerNewsSubscriber = value;
}
}
/// <summary>
/// The date the customer was created in the system
/// </summary>
public DateTime? CreatedDate
{
get
{
return this.customerCreatedDate;
}
private set
{
// Date in the past?
if (value < DateTime.Now)
this.customerCreatedDate = DateTime.Now;
else
this.customerCreatedDate = value;
}
}
/// <summary>
/// The name of the user creating the customer
/// </summary>
public string CreatedBy
{
get
{
return this.customerCreatedBy;
}
set
{
// Null value?
if (value == null)
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-76

Introduction to Web Development with Microsoft Visual Studio 2010

this.customerCreatedBy = "";
else
// Only get the first 15 characters
if (value.Length > 15)
this.customerCreatedBy = value.Substring(0, 15);
else
this.customerCreatedBy = value;

/// <summary>
/// The date the customer was last modified in the system
/// </summary>
public DateTime? ModifiedDate
{
get
{
return this.customerModifiedDate;
}
set
{
// Date in the past?
if (value < DateTime.Now)
this.customerModifiedDate = DateTime.Now;
else
this.customerModifiedDate = value;
}
}
/// <summary>
/// The name of the user who last modified the customer
/// </summary>
public string ModifiedBy
{
get
{
return this.customerModifiedBy;
}
set
{
// Null value?
if (value == null)
this.customerModifiedBy = "";
else
// Only get the first 15 characters
if (value.Length > 15)
this.customerModifiedBy = value.Substring(0, 15);
else
this.customerModifiedBy = value;
}
}

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-77

/// </summary>
public Customer()
{
// Initialize backing fields with default values
this.ID = Guid.NewGuid();
this.CreatedDate = DateTime.Now;
}

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-78

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-79

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.

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

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-80

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

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

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)

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-81

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-82

Introduction to Web Development with Microsoft Visual Studio 2010

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Adding Functionality to a Microsoft ASP.NET Web Form

4-83

Module Review and Takeaways

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?

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 typessuch as Integer or Stringit
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 wordincluding 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

4-84

Introduction to Web Development with Microsoft Visual Studio 2010

for local and private variables, as well as method parameters. See the next best practice regarding
public variables.

Member variablesalso known as backing fieldsas 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.

Follow a naming and casing convention when naming your methods. In this course, the naming
convention used describes the data it makes availablesuch as FirstNamebut never with the first
word of the name being a verbsuch as used for method names (GetFirstName). Casing uses the
same rules as for variablespublic 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 methodspublic
properties use Pascal Casing, whereas non-public properties use Camel Casing.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lab: Implementing Master Pages and User Controls

5-34

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-4

Introduction to Web Development with Microsoft Visual Studio 2010

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 pagefor example, the header that you want to
display on multiple pages of a Web site.
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.aspxfor 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#]

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-5

<%@ 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.
<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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-6

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-7

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.

7.

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-8

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

[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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-9

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>

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 controlsexcept script blocks
for server coderesults 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-10

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-11

</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
contentif anythat 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 contentif
anythat 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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-12

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-13

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-14

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>

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-15

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-16

Introduction to Web Development with Microsoft Visual Studio 2010

You may need to access some controls programmatically from the content pagefor 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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-17

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.
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 styleswhether inline or stored in a cascading style sheet (CSS) fileto
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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-18

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-19

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 controlswhich are components that run on the serveruser 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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-20

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 controlfor 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.
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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-21

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

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 componentalso called a class library in Visual Studio 2010provides


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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-22

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-23

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.

Advantages and Disadvantages of Using User Controls

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-24

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-25

Add properties to the user control to allow controlled access to the private dataif anythat 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.
b.
c.
d.

5.

Remove the html, body, and form elements from the page.
Change the Page directive to a Control directive.
Remove all attributes of the Control directive, except Language, AutoEventWireup (if present),
CodeFile, and Inherits.
In the Control directive, change the CodeFile attribute to point to the renamed code-behind file.

Include a className attribute in the Control directive. This allows the user control to be strongly
typed when it is added to a page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-26

Introduction to Web Development with Microsoft Visual Studio 2010

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.

3.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-27

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

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 elementif they existmust be removed.
Note: After removing all the top-level elements, you will get the following code.
[Visual Basic]
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer.aspx.vb"
Inherits="InsertCustomer" ClassName="InsertCustomer" %>
<div class="customertable">
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerNameLabel" runat="server"
Text="Name:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerNameTextBox" runat="server"
MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerAddressLabel" runat="server"
Text="Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerAddressTextBox"
runat="server" MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerPhoneLabel" runat="server"
Text="Phone:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerPhoneTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-28

Introduction to Web Development with Microsoft Visual Studio 2010

<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerZipCodeLabel" runat="server" Text="Zip
Code:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerZipCodeTextBox" runat="server"
MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerCityTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerStateTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerEmailAddressLabel"
runat="server" Text="Email Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerEmailAddressTextBox" runat="server"
MaxLength="40"></asp:TextBox>
</div>
</div>
<div class="customertablefooter">
</div>
<asp:Button ID="CustomerInsertButton" runat="server" Text="Insert" />
&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">

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-29

<asp:Label ID="CustomerAddressLabel" runat="server"


Text="Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerAddressTextBox" runat="server"
MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerPhoneLabel"
runat="server" Text="Phone:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerPhoneTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerZipCodeLabel" runat="server" Text="Zip
Code:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerZipCodeTextBox" runat="server"
MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerCityLabel" runat="server"
Text="City:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerCityTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerStateLabel" runat="server"
Text="State:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerStateTextBox" runat="server"
MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customertablerow">
<div class="customertableleftcol">
<asp:Label ID="CustomerEmailAddressLabel" runat="server" Text="Email
Address:"></asp:Label>
</div>
<div class="customertablerightcol">
<asp:TextBox ID="CustomerEmailAddressTextBox"
runat="server" MaxLength="40"></asp:TextBox>
</div>
</div>
<div class="customertablefooter">
</div>
<asp:Button ID="CustomerInsertButton" runat="server" Text="Insert"
onclick="CustomerInsertButton_Click" />
&nbsp;<asp:Button ID="customerCancelButton" runat="server" Text="Cancel"
onclick="CustomerCancelButton_Click" />

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-30

Introduction to Web Development with Microsoft Visual Studio 2010

</div>

6.

Save the InsertCustomer.aspx Web Form.

7.

8.

In the CustomerManagement Microsoft Visual Studio (Administrator) window, on the File


menu, click Save InsertCustomer.aspx.

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.

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.

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-31

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-32

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-33

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-34

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-35

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-36

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-37

Results: After completing this exercise, you will have created a master page named Site.master, and
defined a ContentPlaceHolder control on the master page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-38

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-39

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>

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:

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:

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-40

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.
<%@ 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>
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-41

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-42

Introduction to Web Development with Microsoft Visual Studio 2010

<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerEmailAddressLabel" runat="server" Text="Email
Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerEmailAddressTextBox" runat="server"
MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerWebAddressLabel" runat="server" Text="Web
Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerWebAddressTextBox" runat="server"
MaxLength="80"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCreditLimitLabel" runat="server" Text="Credit
Limit:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCreditLimitTextBox" runat="server"
MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerNewsSubscriberLabel" runat="server" Text="News
Subscriber:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:CheckBox ID="CustomerNewsSubscriberCheckBox" runat="server" />
</div>
</div>
<div class="customerTableFooter">
<asp:Button ID="CustomerInsertButton" runat="server" Text="Insert" />
&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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-43

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-44

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-45

Results: After completing this exercise, you will have created a master page named Site.master, and
defined a ContentPlaceHolder control on the master page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-46

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-47

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>

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

Position: relative

Z-order: 1

Top: 62px

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-48

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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

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">
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-49

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-50

Introduction to Web Development with Microsoft Visual Studio 2010

<asp:TextBox ID="CustomerPhoneTextBox" runat="server"


MaxLength="30"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerEmailAddressLabel" runat="server" Text="Email
Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerEmailAddressTextBox" runat="server"
MaxLength="50"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerWebAddressLabel" runat="server" Text="Web
Address:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerWebAddressTextBox" runat="server"
MaxLength="80"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerCreditLimitLabel" runat="server" Text="Credit
Limit:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:TextBox ID="CustomerCreditLimitTextBox" runat="server"
MaxLength="10"></asp:TextBox>
</div>
</div>
<div class="customerTableRow">
<div class="customerTableLeftCol">
<asp:Label ID="CustomerNewsSubscriberLabel" runat="server" Text="News
Subscriber:"></asp:Label>
</div>
<div class="customerTableRightCol">
<asp:CheckBox ID="CustomerNewsSubscriberCheckBox" runat="server" />
</div>
</div>
<div class="customerTableFooter">
<asp:Button ID="CustomerInsertButton" runat="server" Text="Insert"
OnClick="CustomerInsertButton_Click" />
&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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-51

instantiateCustomerObject();
// Populate the UI controls
populateUI();

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-52

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Implementing Master Pages and User Controls

5-53

Module Review and 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?

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

5-54

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-1

Module 6
Validating User Input
Contents:
Lesson 1: Overview of User Input Validation

6-3

Lesson 2: ASP.NET Validation Controls

6-8

Lesson 3: Validating Web Forms

6-28

Lab: Validating User Input

6-33

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-3

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-4

Introduction to Web Development with Microsoft Visual Studio 2010

What Is Input Validation?

Key Points
Input validation can help improve a users 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 customers perception of the overall quality of
the Web site.
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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-5

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 validby using the Page.Validate method.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-6

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
Frameworkbased 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.
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 clientside validation scripts.
In browser versions that support input validationsuch as Windows Internet Explorer 8client-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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-7

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-8

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.

Combine validation controls.

Add validation controls to a Web Form.

Position and configure validation controls on a Web Form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-9

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-10

Introduction to Web Development with Microsoft Visual Studio 2010

Validation control

Function

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-11

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.
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="*" />

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-12

Introduction to Web Development with Microsoft Visual Studio 2010

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

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 enteredfor example, age, height, salary,
or number of childrenmatches the expected range.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-13

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-14

Introduction to Web Development with Microsoft Visual Studio 2010

RegularExpressionValidator Control

Key Points
You can use the RegularExpressionValidator control to verify that a users input matches a predefined
patternsuch 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.

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

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

Character

Definition

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

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>
<script type="text/javascript">
//<![CDATA[

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-16

Introduction to Web Development with Microsoft Visual Studio 2010

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>

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

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

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

6-17

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-18

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-19

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>

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 clientside and server-side validation functions.
Question: When could you use the CustomValidator control?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-20

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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="*" />

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-21

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="*" />

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-22

Introduction to Web Development with Microsoft Visual Studio 2010

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.

3.

4.

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.

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.

Open the Order Web Form in Design view.

5.

On the Start menu of 10267A-GEN-DEV, click All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

In Solution Explorer, right-click Order.aspx, and then click View Designer.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6.

6-23

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.

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. Todays date should be set as the minimum value, and todays 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.

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();

7.

In the Order.aspx.vb or Order.aspx.cs window, click the Close button.

In the Microsoft Visual Studio message box, click Yes.

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>

8.

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.

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.

Add a ValidationSummary control named OrderValidationSummary, below the two Button


controls.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-24

Introduction to Web Development with Microsoft Visual Studio 2010

<asp:ValidationSummary ID="OrderValidationSummary"
runat="server"></asp:ValidationSummary>

9.

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.

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 todays 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 todays date, in the format m/d/yyyy, and then click the Save button.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-25

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-26

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>

ASP.NET input validation controls contain two error message propertiesan ErrorMessage property, and
a Text propertyboth 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>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-27

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-28

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-29

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-30

Introduction to Web Development with Microsoft Visual Studio 2010

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-31

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 resourceslike a databasewhen a
page is invalid.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-32

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-33

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 crosschecking of user inputs with the server. In addition, you will perform server-side validation to protect the
Web project against spoofing and malicious code.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-34

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-35

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.

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.

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>

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>

Add a RequiredFieldValidator control named CustomerWebAddressRequiredFieldValidator, for


the CustomerWebAddressTextBox control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-36

Introduction to Web Development with Microsoft Visual Studio 2010

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

Add a RegularExpressionValidator control named


CustomerWebAddressRegularExpressionValidator, for the CustomerWebAddressTextBox
control.
<asp:RegularExpressionValidator ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-37

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-38

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-39

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-40

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Adding Server-Side Validation


The main task for this exercise is to validate the Customer user control.

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-41

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

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-42

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.

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.

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>

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>

Add a RequiredFieldValidator control named CustomerWebAddressRequiredFieldValidator, for


the CustomerWebAddressTextBox control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-43

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

Add a RegularExpressionValidator control named


CustomerWebAddressRegularExpressionValidator, for the CustomerWebAddressTextBox
control.
<asp:RegularExpressionValidator ID="CustomerWebAddressRegularExpressionValidator"
ControlToValidate="CustomerWebAddressTextBox" runat="server"
ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator>

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-44

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-45

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-46

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-47

Exercise 3: Adding Server-Side Validation


The main task for this exercise is to validate the Customer user control.

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;

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-48

Introduction to Web Development with Microsoft Visual Studio 2010

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-49

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-50

Introduction to Web Development with Microsoft Visual Studio 2010

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Validating User Input

6-51

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

6-52

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lab: Troubleshooting Microsoft ASP.NET Web Applications

7-25

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-4

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-5

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

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
applications logic to locate the bug.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-6

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?

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 codeeither 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 actionsuch as user inputleads to an
unexpected error or result.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-7

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-8

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

Method

7-9

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-10

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-11

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-12

Introduction to Web Development with Microsoft Visual Studio 2010

WriteIf. Conditionally writes a text string to the trace listeners. There are four overloads of this
methodtwo 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...");

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-13

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-14

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 debuggingif you want to debug your Web applicationand 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.
[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>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-15

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.

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.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-16

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-17

Lesson 2

Tracing in ASP.NET

Tracing is the process of receiving informative messages about the execution of a Web application at
runtimethat 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.

Lesson Objectives
After completing this lesson, you will be able to:

Describe tracing.

Describe the TraceContext class.

Perform tracing in a Web application.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-18

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-19

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-20

Introduction to Web Development with Microsoft Visual Studio 2010

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

The following screen shot displays the trace information for a page in a Web application:

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-21

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-22

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-23

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

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-24

Introduction to Web Development with Microsoft Visual Studio 2010

Category

Description

Collection
Server Variables

List of all the server variables and their values.

You can view trace information at the bottom of each page.


The following screen shot displays the requests in the trace viewer:

Question: How will you view trace information?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-25

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-26

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-27

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.

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.

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.

Task 3: Add debug output statements to the user control

Open the Customer user control.

Import the System.Diagnostics namespace.


Imports System.Diagnostics

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-28

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-29

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-30

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

State: NY

Web Address: http://www.cohowinery.com

7-31

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-32

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.

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-33

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.

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.

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.

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;

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-34

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-35

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.

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.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-36

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-37

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-38

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.

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Troubleshooting Microsoft ASP.NET Web Applications

7-39

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

7-40

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?

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

Lesson 3: Managing Data

8-23

Lab: Managing Data in an ASP.NET 4.0 Web Application

8-36

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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.NETdata providers and DataSethelp 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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 layersa disconnected layer, and a connected layer.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-5

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

Type

8-7

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

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, forwardonly, 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
dataone 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-8

Introduction to Web Development with Microsoft Visual Studio 2010

Type name

Type description
object and command objects to perform its duties.

DbDataReader

Reads a forward-only, read-only stream of rows from a data source.

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-9

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.
The Entity Framework enables you to work with data in the form of domain-specific objects and
propertiessuch as customers and customer addresseswithout 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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-10

Introduction to Web Development with Microsoft Visual Studio 2010

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.
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 gapwhich is frequently called an impedance mismatchby 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.
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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-11

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-12

Introduction to Web Development with Microsoft Visual Studio 2010

Component

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-13

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-14

Introduction to Web Development with Microsoft Visual Studio 2010

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 Explorerwhich is part of the Visual Studio 2010 IDEallows 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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-15

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;

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 windowif it is not already openand select
and copy the text from the Connection String property. Finally, paste the copied text into your code.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-16

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 performanceor 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.
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();
...

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-17

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-18

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-19

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();

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
ordersDataAdapter.DeleteCommand
ordersDataAdapter.InsertCommand
ordersDataAdapter.UpdateCommand

=
=
=
=

selectCommand
deleteCommand
insertCommand
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
ordersDataAdapter.DeleteCommand
ordersDataAdapter.InsertCommand
ordersDataAdapter.UpdateCommand

=
=
=
=

selectCommand;
deleteCommand;
insertCommand;
updateCommand;

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-20

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-21

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.

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.
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
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-22

Introduction to Web Development with Microsoft Visual Studio 2010

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 objectfor example, for a DataAdapter objectwhile 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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-23

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-24

Introduction to Web Development with Microsoft Visual Studio 2010

Retrieving Simple Data

Key Points
When you need to retrieve a single valuesuch as a password or the number of rows from the
databaseyou 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

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)

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-25

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-26

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 statementfor example, an entire rowthen
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()

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-27

Retrieving Non-Simple Data

Key Points
If you need to retrieve non-simple datasuch as the content of an entire table or a subset of rows from a
tablethe 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 datawhich you add manuallyor you can import XML documents. You can also use the
DataSet class for storing a copy or cache of the dataor a subset thereofin a data source on a different
server.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-28

Introduction to Web Development with Microsoft Visual Studio 2010

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

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.
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#]
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-29

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;

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-30

Introduction to Web Development with Microsoft Visual Studio 2010

Manipulating Data

Key Points
If you need to manipulate the data in your databaseeither locally or directly on the serveryou 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.
[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;

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-31

// Insert new row locally


ordersDataSet.Tables["Orders"].Rows.Add(newOrderDataRow);

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();

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-32

Introduction to Web Development with Microsoft Visual Studio 2010

[Visual C#]
// Update data source
ordersDataAdapter.Update(ordersDataSet, "Orders");

Question: What is the main purpose of using the DataAdapter object?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-33

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.

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">
...
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-34

Introduction to Web Development with Microsoft Visual Studio 2010

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-35

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-36

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.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-37

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-38

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-39

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-40

Introduction to Web Development with Microsoft Visual Studio 2010

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.

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.

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.

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.

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.

Task 5: Add code to manually save a customer to a data source

Open the Customer user control in the Code view.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

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.

8-41

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

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("CustomerManagementConnectionString").Connectio
nString
' 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")
Dim insertAddressParameter As New SqlParameter("@Address", SqlDbType.NVarChar, 50,
"Address")

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-42

Introduction to Web Development with Microsoft Visual Studio 2010

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-43

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(newCustomerDataRow)
' 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.

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.

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

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-44

Introduction to Web Development with Microsoft Visual Studio 2010

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-45

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.

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.

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-46

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.

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.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-47

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.

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.

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.

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.

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.

Task 5: Add code to manually save a customer to a data source

Open the Customer user control in the Code view.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-48

Introduction to Web Development with Microsoft Visual Studio 2010

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;

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["CustomerManagementConnectionString"].Connectio
nString;
// 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;
// Declare and instantiate parameter objects
SqlParameter insertFirstNameParameter = new SqlParameter("@FirstName",
SqlDbType.NVarChar, 50, "FirstName");
SqlParameter insertLastNameParameter = new SqlParameter("@LastName",
SqlDbType.NVarChar, 30, "LastName");

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-49

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-50

Introduction to Web Development with Microsoft Visual Studio 2010

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(newCustomerDataRow);
// 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.

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.

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

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-51

Check that the new customer has been added in the data source by using the new Customers Web
Form.

Close Internet Explorer.

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-52

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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data in a Microsoft ASP.NET 4.0 Web Application

8-53

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?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

8-54

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?

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 serverwhere many connections are opened to the databaseit 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-1

Module 9
Managing Data Access Tasks by Using LINQ
Contents:
Lesson 1: Overview of LINQ

9-3

Lesson 2: Managing XML Data by Using LINQ to XML

9-16

Lesson 3: Managing SQL Data by Using LINQ to SQL and


LINQ to Entities

9-29

Lab: Managing Data Access Tasks by Using LINQ

9-41

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-2

Introduction to Web Development with Microsoft Visual Studio 2010

Module Overview

Although a large amount of data is stored in Microsoft SQL Server databases and is managed by using
Microsoft ADO.NET, XML has become a standard for storage, management, and transmission of data.
However, both SQL Server and XML data require different methods for managing the data. You can use
language-integrated query (LINQ) to query data by using strongly-typed queries and strongly-typed
results, which is a common factor across disparate data types such as Microsoft .NET object, relational
databases and XML. LINQ improves developer productivity through Microsoft IntelliSense and compiletime error checking.
This module explains what LINQ is, and how you can use LINQ to manage both XML data and SQL Server
data in a Microsoft ASP.NET Web application by using Web server controls, and some code.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-3

Lesson 1

Overview of LINQ

You may be an expert at handling one type of data accesssuch as an SQL Server database or XML
databut not both, because the manner in which you access and manage SQL Server data and XML data
differs. Before the introduction of LINQ, there was no single, unified way to access data in different data
sources, manage the data, or use a single application programming interface (API) for doing these tasks.
Using LINQ, you can write data management code that can be used across various data sources with
minor syntax changes.
This lesson explains what LINQ is, and how you can use LINQ to SQL to write SQL-type queries for
selecting, filtering, and grouping SQL Server data. This lesson also shows how LINQ to XML enables you to
write queries on an in-memory XML document to retrieve collections of elements and attributes, and how
to use LINQ to entities.

Lesson Objectives
After completing this lesson, you will be able to:

Describe LINQ.

Describe LINQ Query Operators.

Describe LINQ to XML.

Describe LINQ to SQL.

Describe LINQ to Entities.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-4

Introduction to Web Development with Microsoft Visual Studio 2010

What Is LINQ?

Key Points
LINQ provides a programming model that you can use to retrieve and manage data from a variety of
sources by using any Microsoft .NET Frameworkbased programming language such as Microsoft Visual
Basic, or Microsoft Visual C#.
LINQ bridges the gap between the objects in object-oriented programming (OOP) and the various data
used by OOP applications. Before the introduction of LINQ, data queries were expressed as a simple
string, resulting in type-checking at compile time. There was no IntelliSense support, which Microsoft
Visual Studio provides. In addition, each type of data source required a different query language.
With LINQ, a query is a first-class language construct in Visual Basic and Visual C#, just like classes,
methods, or events. You can write queries in a simplified manner against strongly-typed collections of
objects, by using programming language keywords and familiar operators. LINQ also provides a unified
syntax that you can use to query any data source that supports LINQ, including SQL Server databases,
XML documents, or ADO.NET datasets. You can also write queries against any collection of objects that
supports the IEnumerable interface, whether standard or generic.

Visual Studio Features and Tools for LINQ


LINQ is an integrated part of the Visual Basic and Visual C# programming languages.
Visual Studio 2010 provides various tools and features that support application development by using
LINQ, including:

LINQ-Aware Code Editors. LINQ-aware code editors for Visual Basic and Visual C# provide
IntelliSense and LINQ-specific formatting capabilities.

Visual Studio Debugger Support. The Visual Studio debugger supports the debugging of LINQ
query expressions.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-5

The following illustration shows a partially-completed LINQ query against a SQL Server database in Visual
Basic and Visual C#. Notice the full type-checking and IntelliSense support that Visual Studio 2010
provides.

The following code shows how to create a simple LINQ query to enumerate all the files in a subfolder of
the Web application root named Public.
[Visual Basic]
Dim files = From file In My.Computer.FileSystem.GetFiles(
Request.PhysicalApplicationPath & "\Public")
Select file
[Visual C#]
var files = from file in System.IO.Directory.GetFiles(
Request.PhysicalApplicationPath + "\\Public")
select file;

LINQ Implementations
Visual Studio 2010 includes LINQ provider assemblies that enable you to use LINQ with several different
types of data, including:

LINQ to DataSet. Enables you to query data cached in a DataSet object.

LINQ to Entities. Enables you to query data in relational databases by querying an Entity Data Model
(EDM).

LINQ to Objects. Enables you to query in-memory data such as arrays and lists.

LINQ to SQL. Enables you to query data in relational databases by querying a LINQ to SQL data
context.

LINQ to XML. Enables you to query data stored in XML documents.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-6

Introduction to Web Development with Microsoft Visual Studio 2010

LINQ Query Operators

Key Points
The standard query operators are the methods that form the LINQ pattern. They provide query
capabilities, including filtering, aggregation, and sorting. There are two sets of LINQ standard query
operators:

One set of query operators operate on objects of type IEnumerable(T). (VB: IEnumerable(Of T) or
C#: IEnumerable<T>)

One set of query operators operates on objects of type IQueryable(T). (VB: IQueryable(Of T) or C#:
IQueryable<T>

The methods that make up each set are static members of the Enumerable and Queryable classes,
respectively. They are defined as extension methods of the type on which they operate, which means they
can be called by using either static method syntax or instance method syntax.
The standard query operators differ in the timing of their execution, depending on whether they return a
single value, or a sequence of values. Those methods that return a single valuefor example, Average or
Sumrun immediately. Methods that return a sequence defer the query execution and return an
enumerable object.
Most of methods operate on sequences, where a sequence is an object whose type implements the
IEnumerable<T> or IQueryable<T> interface. The following code examples demonstrate how the
standard query operators can be used to obtain information about a sequence.
[Visual Basic]
Dim sentence As String = "the quick brown fox jumps over the lazy dog"
' Split into individual words to create a collection
Dim words As String() = sentence.Split(" "c)
Dim query = From word In words
Group word.ToUpper() By word.Length Into gr = Group
Order By Length
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-7

Select Length, GroupedWords = gr


' Using method-based query syntax
Dim query2 = words _
.GroupBy(Function(w) w.Length, Function(w) w.ToUpper()) _
.Select(Function(g) New With {.Length = g.Key, .GroupedWords = g}) _
.OrderBy(Function(o) o.Length)
For Each obj In query2
Response.Write(String.Format("Words of length {0}:<br />", obj.Length))
For Each word As String In obj.GroupedWords
Response.Write(word & "<br />")
Next
Next

[Visual C#]
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words to create a collection.
string[] words = sentence.Split(' ');
// Using query expression syntax
var query = from word in words
group word.ToUpper() by word.Length into gr
orderby gr.Key
select new { Length = gr.Key, Words = gr };
// Using method-based query syntax
var query2 = words.
GroupBy(w => w.Length, w => w.ToUpper()).
Select(g => new { Length = g.Key, Words = g }).
OrderBy(o => o.Length);
foreach (var obj in query)
{
Response.Write(string.Format("Words of length {0}:<br />", obj.Length));

foreach (string word in obj.Words)


Response.Write(word + "<br />");

The code produces the following output:


Words of length 3:
THE
FOX
THE
DOG
Words of length 4:
OVER
LAZY
Words of length 5:
QUICK

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-8

Introduction to Web Development with Microsoft Visual Studio 2010

BROWN
JUMPS

Common Query Operators


The following is a list of common query operators in Visual Basic and Visual C#.
Operator(s)

Visual Basic
operator

Visual C# operator

Description

Select

Select

select

Selects a sequence from the container.

From ... In

From ... In

from ... in

Extracts a subset (From/from) of data from a


container (In/in).

Join

From x In ..., y In ...


Where x.a = b.a
-orJoin ... [As ...] In ...
On ...

join ... in ... on ...


equals ...

Performs a join, based on the specified key.

Where

Where

where

Defines a restriction for the items to extract.

Order By

Order By
-orOrder By ...
Descending

orderby
-ororderby ...
descending

Sorts a subset in ascending or descending


order.

Group By

Group ... By ... Into ... group ... by


-orgroup ... by ... into

Groups a subset by specified value.

Question: What are the types of objects, on which the two sets of LINQ standard query operators
operate?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-9

What Is LINQ to XML?

Key Points
Because XML has been widely adopted as a method of storing, formatting, and transporting data, it is
important to understand how to work with data in the XML format.
LINQ to XML provides an in-memory XML programming interface that capitalizes on the .NET LINQ
Framework. LINQ to XML uses the .NET Framework language capabilities, and is comparable to an
updated, redesigned document object model (DOM) XML programming interface. The LINQ to XML
query expressions provide functionality that is similar to that of XML Path Language (XPath).
Note: XPath is a query language for navigating an XML document and selecting nodes from the
document. However, it can also be used to compute valuessuch as numbers or Boolean valuesfrom
the content of the XML document.
LINQ to XML is comparable to DOM in that it makes an XML document accessible in memory, but LINQ
to XML differs from DOM in that it provides a new object model that is easier to work with. LINQ to XML
takes advantage of language improvements in both Visual Basic and Visual C#, and is integrated with
LINQ. The latter enables you to run queries on the in-memory XML document to retrieve collections of
elements and attributes.
LINQ to XML makes XML easier to manage, because the query expression is similar to the SQL
programming syntax.
In the following LINQ to XML code examples, the query is run to obtain the Internet top-level domain
(TLD) value for every Country element in the Countries root element.
[Visual Basic]
Dim internetTLDs =
From country In countries.<Country>
Select country.Element("InternetTLD")

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-10

Introduction to Web Development with Microsoft Visual Studio 2010

[Visual C#]
var internetTLDs =
from country in countries.Elements("Country")
select (string)country.Element("InternetTLD");

If you need to create in-memory XMLsuch as an XML treeyou can use the following lines of code. The
XML tree can be created more or less as you would write it in an XML file, because of how the Visual Basic
Code Editor handles the XML.
[Visual Basic]
Dim countries = _
<Countries>
<Country>
<ID>62750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Uganda</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>256</DialingCountryCode>
<InternationalDialingCode>000</InternationalDialingCode>
<InternetTLD>UG</InternetTLD>
</Country>
<Country>
<ID>602cf8a8-b62f-de11-a6b1-0003ffa70544</ID>
<Name>Denmark</Name>
<PhoneNoFormat>## ## ## ##</PhoneNoFormat>
<DialingCountryCode>45</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>DK</InternetTLD>
</Country>
<Country>
<ID>63750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Great Britain</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>44</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>UK</InternetTLD>
</Country>
</Countries>

[Visual C#]
XElement countries = new XElement("Countries",
new XElement("Country",
new XElement("ID", "62750c5e-092c-de11-8c6e-0003ff4ed632"),
new XElement("Name", "Uganda"),
new XElement("PhoneNoFormat", ""),
new XElement("DialingCountryCode", "256"),
new XElement("InternationalDialingCode", "000"),
new XElement("InternetTLD", "UG")
),
new XElement("Country",
new XElement("ID", "602cf8a8-b62f-de11-a6b1-0003ffa70544"),
new XElement("Name", "Denmark"),
new XElement("PhoneNoFormat", "## ## ## ##"),
new XElement("DialingCountryCode", "45"),
new XElement("InternationalDialingCode", "00"),
new XElement("InternetTLD", "DK")
),
new XElement("Country",
new XElement("ID", "63750c5e-092c-de11-8c6e-0003ff4ed632"),
new XElement("Name", "Great Britain"),
new XElement("PhoneNoFormat", ""),

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

);

9-11

new XElement("DialingCountryCode", "44"),


new XElement("InternationalDialingCode", "00"),
new XElement("InternetTLD", "UK")

Question: What are the various uses of LINQ to XML?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-12

Introduction to Web Development with Microsoft Visual Studio 2010

What Is LINQ to SQL?

Key Points
Almost all applications today manipulate data, and most often, the data is stored in a relational database
such as a SQL Server database. The difference lies in how the data in programming languages and data in
relational databases is represented. A programming language accesses information in a database by using
objects through one or more APIs. These APIs require that you specify your queries as simple text strings.
Because queries are represented as text strings, they cannot be verified for errors such as syntax errors.
Also, IntelliSense does not work in the Visual Studio 2010 text editor.
This is the gap that LINQ to SQL bridges, because it provides a runtime infrastructure for managing
relational data as objects. The data model of a traditional relational database is mapped to an object
model that is expressed in the syntax of the programming language used. At runtime, LINQ to SQL
translates the LINQ queries in the object model into SQL, and sends them to the database for execution.
Upon return, the results are converted back to objects.
You can use the Object Relational Designer (O/R Designer) in Visual Studio 2010 to create a data context,
which is a mapping of the relational data to objects. You can create the data context by using the user
interface of the O/R Designer by dragging tables and other objects from a database in Server Explorer to
the O/R Designer.
After you have added the tables to the designer surface, you can view and set the properties of the
classes. The tables become classes, and you can manipulate the data in the tables.
When you build your project or solution, the sqlmetal.exe command-line tool automatically generates the
classes that give you access to the data by using strongly-typed objects in your code.
In the following code examples that use LINQ to SQL, the query is run to obtain all the customers in the
Customers table in a SQL Server database, and is mapped by using a DataContext object.
[Visual Basic]
' Declare and instantiate data context
Dim cmDataContext As New CustomerManagementDataContext()
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-13

' Create query for selecting all customers from Customers table
Dim query =
From customers In cmDataContext.Customers
' Output names of selected customers
For Each cust In query
Response.Write(cust.Name & "<br />")
Next
[Visual C#]
// Declare and instantiate data context
CustomerManagementDataContext cmDataContext =
new CustomerManagementDataContext();
// Create query for selecting all customers from Customers table
var query =
from customers in cmDataContext.Customers
select customers;
// Output names of selected customers
foreach (Customer cust in query)
Response.Write(cust.Name + "<br />");

The Sqlmetal.exe tool creates the CustomerManagementDataContext class, and you should treat it like
an ADO.NET connection. The CustomerManagementDataContext class needs to be properly disposed
by using the Dispose method, after you have used it. If you plan to use the data context throughout your
application, you can declare it globallyfor example, in the global application file, Global.asax.
Question: In which scenario will you use LINQ to SQL?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-14

Introduction to Web Development with Microsoft Visual Studio 2010

What Is LINQ to Entities?

Key Points
The Entity Framework enables developers to work with data in the form of domain-specific objects and
propertiessuch as customers and customer addresseswithout having to think about the underlying
database tables and columns where this data is stored. LINQ to Entities enables you to write queries
against the Entity Framework conceptual model using Visual Basic or Visual C#. Queries against the Entity
Framework are represented by command tree queries, which execute against the object context. LINQ to
Entities converts LINQ queries to command tree queries, executes the queries against the Entity
Framework, and returns objects that can be used by both the Entity Framework and LINQ.
Through the Object Services infrastructure of Entity Framework, ADO.NET exposes a common conceptual
view of dataincluding relational dataas objects in the .NET environment. LINQ to Entities queries use
the Object Services infrastructure. The ObjectContext class is the primary class for interacting with an
Entity Data Model (EDM). The developer can construct a generic ObjectQuery instance through the
ObjectContext class. The ObjectQuery generic class represents a query that returns an instance or
collection of typed entities. The returned entity objects are updatable, and are located in the object
context.
In the following code examples that use LINQ to Entities, the Select method is used to return a sequence
of product names from the AdventureWorks database.
[Visual Basic]
Using AWEntities As New AdventureWorksEntities
Dim productNames =
AWEntities.Products.Select(Function(p) p.Name())
Response.Write("Product Names:" & "<br />")
For Each productName In productNames
Response.Write(productName & "<br />")
Next
End Using

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-15

[Visual C#]
using (AdventureWorksEntities AWEntities = new AdventureWorksEntities())
{
var productNames =
AWEntities.Products.Select(p => p.Name);

Response.Write("Product Names:" + "<br />");


foreach (String productName in productNames)
{
Response.Write(productName + "<br />");
}

Question: In which scenario will you use LINQ to Entities?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-16

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson 2

Managing XML Data by Using LINQ to XML

XML has traditionally been a type of data storage that is hard to manage, whether using DOM, other
object models, XML tools, or utilities. With the advent of LINQ to XML, this has all changed. While the
notion of nodes, elements, or attributes still exist in LINQ to XML, it is easier than before to query,
manage, and update XML data. XML is a widely-accepted data formatting method that helps you manage
and transport data to a database. LINQ to XML is a programming interface that supports LINQ
expressions to read, write, and process XML data. With LINQ to XML, you can write queries on an inmemory XML document, and retrieve collections of elements and attributes. You can also manage XML
data by querying and modifying the XML content, and then saving the content to a file, or serializing it for
further processing.
This lesson explains what LINQ to XML is, how you can make XML data available for querying, and how
you can query and manage XML data by using LINQ to XML.

Lesson Objectives
After completing this lesson, you will be able to:

Query XML data by using LINQ to XML.

Work with XML data by using LINQ to XML.

Display LINQ to XML data in Web Forms.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-17

Querying XML Data by Using LINQ to XML

Key Points
When you have a string of XML, or a file with XML content, you may want to extract specific information.
The .NET Framework includes three models for processing XML data. You can:

Use the System.Xml.XmlDocument class, which implements the World Wide Web Consortium
(W3C) DOM Level 1 Core and the DOM Level 2 Core.

Use the System.Xml.XPathDocument class, which provides a fast, read-only in-memory


representation of an XML document by using the XPath data model.

Use LINQ to XML.

The System.Xml.XmlDocument class and the System.Xml.XPathDocument class use the notion of a
document as a container for XML. However, this is not the case with LINQ to XML, which works well at the
element level by using the XElement class. The System.Xml.XmlReader works well when reading XML in
a fast, non-cached, but forward-only manner. However, you cannot use the System.Xml.XmlReader
when you need to query for specific elements without looping through the entire content. Although it is
possible to query the content of an XPathDocument object by using XPath, you will find that using LINQ
is easier.
The performance of LINQ to XML is faster than the performance of the DOM classes in the System.XML
namespace, but the performance of the XmlReader class is faster than the performance of LINQ to XML.

Making XML Available for Querying


When you have to query XML, you need to first determine where the XML is storedin a text string, in a
file, or in any other manner.
Examine the following code example.
<Countries>
<Country>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-18

Introduction to Web Development with Microsoft Visual Studio 2010

<ID>602cf8a8-b62f-de11-a6b1-0003ffa70544</ID>
<Name>Denmark</Name>
<PhoneNoFormat>## ## ## ##</PhoneNoFormat>
<DialingCountryCode>45</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>DK</InternetTLD>
</Country>
<Country>
<ID>62750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Uganda</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>256</DialingCountryCode>
<InternationalDialingCode>000</InternationalDialingCode>
<InternetTLD>UG</InternetTLD>
</Country>
<Country>
<ID>63750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Great Britain</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>44</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>UK</InternetTLD>
</Country>
</Countries>

The sample XML can be queried, whether already stored in memory (such as in a string), in manually
created XML, or externally in a file, provided it is accessible. Typically, prior to LINQ to XML, reading from
a file was done by using a class derived from the abstract System.Xml.XmlReader class, and while it is
still possible to do so, it is easier to do it as demonstrated in the following code, where the Countries.xml
file contains the sample XML.
[Visual Basic]
Dim countries As XElement = XElement.Load(Server.MapPath("Countries.xml"))

[Visual C#]
XElement countries = XElement.Load(Server.MapPath("Countries.xml"));

The Load method of the XElement class is overloaded, and some of the overloads take a parameter of
type System.IO.TextReader or System.Xml.XmlReader, so that there is a link to use the classes from the
System.Xml namespace. If you want to read the XML stored in a string, you can use the Parse method of
the XElement class as follows.
[Visual Basic]
Dim xmlString As String = "<Countries><Country><ID>602cf8a8-b62f-de11-a6b10003ffa70544</ID><Name>Denmark</Name>...</Country></Countries>"
Dim countries As XElement = XElement.Parse(xmlString)
[Visual C#]
string xmlString = "<Countries><Country><ID>602cf8a8-b62f-de11-a6b10003ffa70544</ID><Name>Denmark</Name>...</Country></Countries>";
XElement countries = XElement.Parse(xmlString);

Both the examples result in an outer XElement object that contains the inner XElement objects, as the
indentation of the sample XML indicates.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-19

Querying XML
You can query the XML in the countries XElement object as indicated in the following code examples.
[Visual Basic]
' Extract all elements where PhoneNoFormat has been specified
Dim countriesWithPhNoFormat As IEnumerable(Of XElement) =
From c In countries
Where Not IsNothing(c.Element("PhoneNoFormat")) AndAlso
CType(c.Element("PhoneNoFormat").Value, String) <> ""
Select c
[Visual C#]
// Extract all elements where PhoneNoFormat has been specified
var countriesWithPhNoFormat = (from c in countries.Elements()
where c.Element("PhoneNoFormat") != null &&
(string)c.Element("PhoneNoFormat").Value != ""
select c);

In the sample code, notice how the countriesWithPhNoFormat variable has been specifically declared;
this makes the code more readable. You can also extract the elements by omitting the type in Visual Basic,
or by using the var keyword in Visual C#, as demonstrated in the following code examples.
[Visual Basic]
' Extract all elements where PhoneNoFormat has been specified
Dim countriesWithPhNoFormat =
From c In countries.Elements
...
Select c
[Visual C#]
// Extract all elements where PhoneNoFormat has been specified
var countriesWithPhNoFormat = (from c in countries.Elements() ...
select c);

The LINQ to XML query specifies the following:

Select the countries XElement object.

Select descendant elements of the root node, which is the Countries node or element.

Select only the descendant elements of the Country node with the name PhoneNoFormat, and with a
non-blank value.

The query uses the Element property of a parent XElement to specify the descendant, but it is also
possible to use the Elements or Descendants property, in which case more than a single element can be
returned. You can use the Descendants property if you want to query the child elements, and the child
elements of these child elements, and so on, as indicated in the following code examples.
[Visual Basic]
Dim countriesWithPhNoFormat =
From c In countries.Elements
Where Not IsNothing(c.Descendants("PhoneNoFormat")) AndAlso
CType(c.Descendants("PhoneNoFormat").First.Value, String) <> ""
Select c

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-20

Introduction to Web Development with Microsoft Visual Studio 2010

[Visual C#]
var countriesWithPhNoFormat = from c in countries.Elements()
where c.Descendants("PhoneNoFormat") != null &&
(string)c.Descendants("PhoneNoFormat").First().Value != ""
select c;

Notice how the First extension method returns the first occurrence of the returned elements. In this case,
there will always be only one element. In the sample XML, elements have been used throughout, but in
many cases attributes are used instead of child elements, or a combination of attributes and child
attributes are used.
The following code is the same data as in the first XML sample, but with the exclusive use of attributes for
the Country element, instead of child elements.
<Countries>
<Country ID="38f5ad4b-092c-de11-8c6e-0003ff4ed632" Name="Denmark" PhoneNoFormat="##
## ## ##" DialingCountryCode="45" InternationalDialingCode="00 " InternetTLD="DK" />
<Country ID="62750c5e-092c-de11-8c6e-0003ff4ed632" Name="Uganda" PhoneNoFormat=""
DialingCountryCode="256" InternationalDialingCode="000 " InternetTLD="UG" />
<Country ID="63750c5e-092c-de11-8c6e-0003ff4ed632" Name="Great Britain"
PhoneNoFormat="" DialingCountryCode="44" InternationalDialingCode="00 " InternetTLD="UK"
/>
</Countries>

To get the same result by querying the sample XML, you need to query the Attribute element as
indicated in the following code examples.
[Visual Basic]
Dim countriesWithPhNoFormat = _
From c In countries.Elements _
Where Not IsNothing(c.Attribute("PhoneNoFormat")) AndAlso _
CType(c.Attribute("PhoneNoFormat").Value, String) <> "" _
Select c
[Visual C#]
var countriesWithPhNoFormat = from c in countries.Elements()
where c.Attribute("PhoneNoFormat") != null &&
(string) c.Attribute("PhoneNoFormat").Value != ""
select c;

The Attribute property returns an object of type XAttribute. Similar to the Elements property, the
Attributes property returns more than one attribute.
Question: What is the purpose of using the XElement class?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-21

Working with XML Data by Using LINQ to XML

Key Points
When you store XML in a durable statesuch as in a file with XML contentit may not suffice to extract
information; you may also need to update the XML content.
If you read an XML document by using the XmlReader class, you can similarly use the XmlWriter class to
write it to an XML document, but it is easier to read and write by using the various methods of the
XElement class.
The following code examples show how to select the countries that have the phone number format
specified.
[Visual Basic]
' Extract all elements where PhoneNoFormat has been specified
Dim countriesWithPhNoFormat As New XElement("Countries",
From c In countries.Elements
Where Not IsNothing(c.Element("PhoneNoFormat")) AndAlso
CType(c.Element("PhoneNoFormat").Value, String) <> ""
Select New XElement("Country",
New XElement(c.Element("ID")),
New XElement(c.Element("Name")),
New XElement(c.Element("PhoneNoFormat")),
New XElement(c.Element("DialingCountryCode")),
New XElement(c.Element("InternationalDialingCode")),
New XElement(c.Element("InternetTLD"))
))
' Save to file
countriesWithPhNoFormat.Save(Server.MapPath("CountriesWithPhNoFormat.xml"))
[Visual C#]
// Extract all elements where PhoneNoFormat has been specified
XElement countriesWithPhNoFormat = new XElement("Countries",

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-22

Introduction to Web Development with Microsoft Visual Studio 2010

from c in countries.Elements()
where c.Element("PhoneNoFormat") != null &&
(string) c.Element("PhoneNoFormat").Value != ""
select new XElement("Country",
new XElement(c.Element("ID")),
new XElement(c.Element("Name")),
new XElement(c.Element("PhoneNoFormat")),
new XElement(c.Element("DialingCountryCode")),
new XElement(c.Element("InternationalDialingCode")),
new XElement(c.Element("InternetTLD"))
));
// Save to file
countriesWithPhNoFormat.Save(Server.MapPath("CountriesWithPhNoFormat.xml"));

Both the XElement and XDocument classes have a Load and a Save method, but the query used in the
XElement object returns an IEnumerable(XElement) class, and not an XElement class like the Load
method does. Therefore, by specifically stating that the countriesWithPhNoFormat variable is of the
type XElement, and assigning a new outer XElement or root to Countries, you can use the same query.
However, you also need to create each individual Country element, copying across the values from the
matching elements from the query source, countries. Finally, you can save the extracted methods by
using the Save method.
Instead of extracting elements from one XElement, you can also modify, delete, or insert elements while
looping the original XElement. The sample content used for the code example is as follows.
<Countries>
<Country>
<ID>602cf8a8-b62f-de11-a6b1-0003ffa70544</ID>
<Name>Denmark</Name>
<PhoneNoFormat>## ## ## ##</PhoneNoFormat>
<DialingCountryCode>45</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>DK</InternetTLD>
</Country>
<Country>
<ID>62750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Uganda</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>256</DialingCountryCode>
<InternationalDialingCode>000</InternationalDialingCode>
<InternetTLD>UG</InternetTLD>
</Country>
<Country>
<ID>63750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Great Britain</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>44</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>UK</InternetTLD>
</Country>
<Country>
<ID>66750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>USA</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>1</DialingCountryCode>
<InternationalDialingCode>011</InternationalDialingCode>
<InternetTLD>US</InternetTLD>
</Country>
</Countries>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-23

The following code examples show how you can add, modify, or delete an element.
[Visual Basic]
' Add new element
countries.Add(New XElement("Country", _
New XElement("ID", "3032b345-092c-de11-8c6e-0003ff4ed632"), _
New XElement("Name", "Afghanistan"), _
New XElement("PhoneNoFormat", ""), _
New XElement("DialingCountryCode", "93"), _
New XElement("InternationalDialingCode", "00"), _
New XElement("InternetTLD", "AF")))
' Modify element
'
Loop through all countries
For Each country As XElement In countries.Elements
' Is this an element to modify?
If country.Element("Name") = "USA" Then
' Set the phone no. format
country.SetElementValue("PhoneNoFormat", "(###) ###-####")
End If
Next
' Delete element
'
Loop through all countries
For Each country As XElement In countries.Elements
' Is this an element to modify?
If country.Element("ID") = "62750c5e-092c-de11-8c6e-0003ff4ed632" Then
' Remove element
country.Remove()
End If
Next

[Visual C#]
// Add new element
countries.Add(new XElement("Country",
new XElement("ID", "3032b345-092c-de11-8c6e-0003ff4ed632"),
new XElement("Name", "Afghanistan"),
new XElement("PhoneNoFormat", ""),
new XElement("DialingCountryCode", "93"),
new XElement("InternationalDialingCode", "00"),
new XElement("InternetTLD", "AF")));
// Modify element
//
Loop through all countries
foreach (XElement country in countries.Elements())
{
// Is this an element to modify?
if (country.Element("Name").Value == "USA")
{
// Set the phone no. format
country.SetElementValue("PhoneNoFormat", "(###) ###-####");
}
}
// Delete element
//
Loop through all countries
foreach (XElement country in countries.Elements())
{
// Is this an element to modify?
if (country.Element("ID").Value == "62750c5e-092c-de11-8c6e-0003ff4ed632")
// Remove element
country.Remove();

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-24

Introduction to Web Development with Microsoft Visual Studio 2010

The Add method is straightforward, and so is the Remove method, because they are really standard .NET
Framework collection methods. The looping is also standard .NET code, but the SetElementValue
method is slightly different, in that passing a name that does not exist as a child element creates a child
element for you. If you call the SetElementValue method passing the name of an existing child element,
this method modifies the value of the child element to the value that you specify. If you pass null for
value, this method removes the child element.
The following is the resulting XML.
<Countries>
<Country>
<ID>602cf8a8-b62f-de11-a6b1-0003ffa70544</ID>
<Name>Denmark</Name>
<PhoneNoFormat>## ## ## ##</PhoneNoFormat>
<DialingCountryCode>45</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>DK</InternetTLD>
</Country>
<Country>
<ID>63750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Great Britain</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>44</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>UK</InternetTLD>
</Country>
<Country>
<ID>66750c5e-092c-de11-8c6e-0003ff4ed632</ID>
<Name>USA</Name>
<PhoneNoFormat>(###) ###-####</PhoneNoFormat>
<DialingCountryCode>1</DialingCountryCode>
<InternationalDialingCode>011</InternationalDialingCode>
<InternetTLD>US</InternetTLD>
</Country>
<Country>
<ID>3032b345-092c-de11-8c6e-0003ff4ed632</ID>
<Name>Afghanistan</Name>
<PhoneNoFormat></PhoneNoFormat>
<DialingCountryCode>93</DialingCountryCode>
<InternationalDialingCode>00</InternationalDialingCode>
<InternetTLD>AF</InternetTLD>
</Country>
</Countries>

The country, Afghanistan, has been added; the country, Uganda, has been removed; and the phone
number format for the United States has been modified.
Question: How will you use LINQ queries to process an XML tree?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-25

Displaying LINQ to XML Data

Key Points
When you need to display LINQ to XML data in your Web Forms, you have some options to choose from:

You can do it manually by including the creation of the XML tree or loading it from a file, or load the
XML into one or more Web server controls.

You can directly bind the XML data to an XmlDataSource Web server control, and then bind the
XmlDataSource control to one or more Web server controls.

A simple but very effective approach is to use the XmlDataSource that is bound to a GridView control.
If you have some Country-related data stored in a file, you can use the XElement.Load method to load
the XML data into memory, as follows.
[Visual Basic]
Dim countries As XElement = XElement.Load(Server.MapPath("Countries.xml"))
[Visual C#]
XElement countries = XElement.Load(Server.MapPath("Countries.xml"));

Alternatively, if the XML data exists in a string, the representation might look like the following code.
[Visual Basic]
Dim xmlString As String = "<Countries><Country ID='38f5ad4b-092c-de11-8c6e-0003ff4ed632'
Name='Denmark' PhoneNoFormat='## ## ## ##' DialingCountryCode='45'
InternationalDialingCode='00 ' InternetTLD='DK'></Country>" &
"<Country ID='62750c5e-092c-de11-8c6e-0003ff4ed632' Name='Uganda' PhoneNoFormat=''
DialingCountryCode='256' InternationalDialingCode='000 ' InternetTLD='UG'></Country>" &
"<Country ID='63750c5e-092c-de11-8c6e-0003ff4ed632' Name='Great Britain'
PhoneNoFormat='' DialingCountryCode='44' InternationalDialingCode='00 '
InternetTLD='UK'></Country>" &

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-26

Introduction to Web Development with Microsoft Visual Studio 2010

"<Country ID='66750c5e-092c-de11-8c6e-0003ff4ed632' Name='USA' PhoneNoFormat='(###)


###-####' DialingCountryCode='1' InternationalDialingCode='011 '
InternetTLD='US'></Country></Countries>"
[Visual C#]
string xmlString = "<Countries><Country ID='38f5ad4b-092c-de11-8c6e-0003ff4ed632'
Name='Denmark' PhoneNoFormat='## ## ## ##' DialingCountryCode='45'
InternationalDialingCode='00 ' InternetTLD='DK'></Country>" +
"<Country ID='62750c5e-092c-de11-8c6e-0003ff4ed632' Name='Uganda' PhoneNoFormat=''
DialingCountryCode='256' InternationalDialingCode='000 ' InternetTLD='UG'></Country>" +
"<Country ID='63750c5e-092c-de11-8c6e-0003ff4ed632' Name='Great Britain'
PhoneNoFormat='' DialingCountryCode='44' InternationalDialingCode='00 '
InternetTLD='UK'></Country>" +
"<Country ID='66750c5e-092c-de11-8c6e-0003ff4ed632' Name='USA' PhoneNoFormat='(###)
###-####' DialingCountryCode='1' InternationalDialingCode='011 '
InternetTLD='US'></Country></Countries>";

You then need to add the XML to the XmlDataSource Web server control, and it can be done whether
you have the XML data in a file or in a string, as indicated in the following code.
[Visual Basic]
' Set xml string data source
CountriesXmlDataSource.Data = xmlString
' Set xml file data source
CountriesXmlDataSource.DataFile = Server.MapPath("Countries.xml")
[Visual C#]
// Set xml string data source
CountriesXmlDataSource.Data = xmlString;
// Set xml file data source
CountriesXmlDataSource.DataFile = Server.MapPath("Countries.xml");

The DataFile property can also be set declaratively, as indicated in the following code.
<asp:XmlDataSource ID="CountriesXmlDataSource" runat="server" DataFile="~/Countries.xml"
/>

After setting either of the XML data properties of the XmlDataSource control, you should load and
validate the XML, which can be done as indicated in the following code.
[Visual Basic]
' Trigger Xml validation
CountriesXmlDataSource.GetXmlDocument()
[Visual C#]
// Trigger Xml validation
CountriesXmlDataSource.GetXmlDocument();

At this stage, the XML is validated, and a problem could arise if the XML data has more than one root
node.
If you want to filter the elements and retrieve all of the countries with the phone number format specified,
you can use the following code examples.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-27

[Visual Basic]
' Make XML data queryable
Dim countries As XElement = XElement.Parse(xmlString)
' Extract all countries with phone no. format specified
Dim countriesWithPhNoFormat As IEnumerable(Of XElement) = _
From c In countries.Elements("Country") _
Where Not IsNothing(c.Attribute("PhoneNoFormat")) AndAlso _
CType(c.Attribute("PhoneNoFormat").Value, String) <> "" _
Select c
[Visual C#]
// Make XML data queryable
XElement countries = XElement.Parse(xmlString);
// Extract all countries with phone no. format specified
IEnumerable<XElement> countriesWithPhNoFormat = (from c in countries.Elements("Country")
where c.Attribute("PhoneNoFormat") != null &&
(string)c.Attribute("PhoneNoFormat").Value != ""
select c);

Notice that to perform the query, you can parse the XML into an XElement object by using the Parse
method. An object of the type XElement can be used directly by the Data property of the
XmlDataSource, if you use the ToString method as in the following code.
[Visual Basic]
' Set xml string data source
CountriesXmlDataSource.Data = countries.ToString()
[Visual C#]
// Set xml string data source
CountriesXmlDataSource.Data = countries.ToString();

However, if you want to show the filtered countries, you have the countriesWithPhNoFormat variable,
which is of type IEnumerable(XElement). This must be converted so that it appears as a string to the
Data property of the XmlDataSource control, as in the following code.
[Visual Basic]
' Set xml string data source
CountriesXmlDataSource.Data = "<Countries>" & String.Join("",
countriesWithPhNoFormat.Select(Function(x) x.ToString()).ToArray()) & "</Countries>"
[Visual C#]
// Set xml string data source
LoadCountriesXmlDataSource.Data = "<Countries>" + string.Join("",
countriesWithPhNoFormat.Select(x => x.ToString()).ToArray()) + "</Countries>";

You can use the String.Join method to extract each object in the IEnumerable variable and join them
into an array of strings by using a Lambda function. However, it is important to notice the addition of the
root element <Countries>, which was stripped away when the query was performed. The
XmlDataSource control will throw an exception when you call the GetXmlDocument method, if you do
not add the root element. The name of the root element is irrelevant for this purpose.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-28

Introduction to Web Development with Microsoft Visual Studio 2010

Now, because the XmlDataSource has been prepared for use by a databound control, you can set the
DataSourceID property of the GridView control to the name of the XmlDataSource control, and
subsequently perform the data binding, as in the following code.
[Visual Basic]
' Bind to XmldataSource
XmlFileGridView.DataSourceID = "CountriesXmlDataSource"
' Perform databinding
XmlFileGridView.DataBind()
[Visual C#]
// Bind to XmldataSource
XmlFileGridView.DataSourceID = "CountriesXmlDataSource";
// Perform databinding
XmlFileGridView.DataBind();

Question: What are the advantages of using LINQ to XML?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-29

Lesson 3

Managing SQL Data by Using LINQ to SQL and LINQ


to Entities

Data in a relational database is usually referred to as SQL data, because of the syntax that is used for
accessing and querying the data. SQL data is the preferred method for storing most data. The SQL
language comes in a number of dialects, including Transact-SQL (T-SQL), which is provided by Microsoft.
All the languages differ with how you implement the database server. Although there are many
languages, after you learn one of the SQL languages, you can easily learn another SQL-based language or
dialect. With LINQ to SQL and LINQ to Entities, you can use a standardized, single SQL dialect, even if the
databases you access are from different organizations, such as Microsoft, IBM, or Oracle.
In this lesson, you will get to know what LINQ to SQL and LINQ to Entities are, how to make the SQL data
available for querying, and how you can query and manage the SQL data.

Lesson Objectives
After completing this lesson, you will be able to:

Query SQL data by using LINQ.

Work with SQL data by using LINQ.

Display SQL data in Web Forms by using LINQ.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-30

Introduction to Web Development with Microsoft Visual Studio 2010

Querying SQL Data by Using LINQ

Key Points
When you have data in a relational database, the data is most often extracted in smaller pieces for
displaying or managing specific information. You need to know how to query the data, and how to make
the data accessible for querying.

DataContext and ObjectContext Object


By using ADO.NET, you can connect to a relational database, and retrieve or update data. Using LINQ to
SQL, you can transport data by using the System.Data.Linq.DataContext class between the client and
the server. By using LINQ to Entities, you can query and work with entity data as objects by using the
System.Data.Objects.ObjectContext class.

Making SQL Data Available For Querying


When you want to query the SQL data, you need to first create a connection to the database, possibly by
using Server Explorer. Once you have a connection to access the tables, views, stored procedures, or
functions in a database, you can map these database objects to objects by using the O/R Designer in LINQ
to SQL, or the ADO.NET Entity Data Model Designer, also known as the Entity Designer, (LINQ to Entities).
You need to add a LINQ to SQL Classes or ADO.NET Entity Data Model project item to your Web
project by using the Add New Item dialog box.
Tip: When naming your LINQ to SQL Classes project item, the corresponding DataContext class that is
created is named by using the name that you give the LINQ to SQL Classes project item, and is suffixed
with the word DataContext. This means that if you name the LINQ to SQL Classes project item Orders, the
DataContext class will be named OrdersDataContext. You need to remember that the naming should
be based on the naming conventions that you use.
After you have added the LINQ to SQL Classes item (.dbml file) or ADO.NET Entity Data Model (.edmx file)
to your project, the O/R Designer or Entity Designer displays.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-31

The Object Relational Designer design surface has two panes:

Entities pane. The entities pane is the main design surface on the left that displays the entity classes,
associations, and inheritance hierarchies.

Methods pane. The methods pane is the design surface on the right that displays the DataContext
methods that are mapped to stored procedures and functions.

Note: The Object Relational Designer maps the relational data contained in a database to
objects. This process is known as Object Relational Mapping. Object Relational Mapping is about
making relational data entitiessuch as tablesavailable as objects in memory.
Note: You can manually create classes, associations, or inheritance in the entities pane, or you can drag
tables or views from Server Explorer. Associations are automatically added to the entities pane between
two entities, if they are associated or related in the database.
Note: Currently, the Object Relational Designer supports only SQL Server 2000, SQL Server 2005, SQL
Server 2008, and SQL Server Express databases. LINQ to SQL supports other databases, but then the
DataContext class must be created manually.
The Entity Designer consists of the following components:

A visual design surface for editing the conceptual model. You can create, modify, or delete entities
and associations.

A Mapping Details window for viewing and editing mappings. You can map entity types or
associations to database tables, columns, and stored procedures.

A Model Browser window that provides tree views of the conceptual model and the storage model.

Toolbox controls for creating entities, associations, and inheritance relationships.

Note: To work with entities in the Entity Designer and the associated .edmx file, you can use the Entity
Data Model Wizard, Update Model Wizard, and Create Database Wizard. This means that you can
generate a data model from an existing database, create a data model from scratch or update an existing
data model, and generate a database from the data model.
When you save the .dbml or .edmx file, the Code Generation Tool also known as SqlMetal.exe (LINQ to
SQL) or EntityModelCodeGenerator (LINQ to Entities) is automatically run to create or re-create the
DataContext or ObjectContext class. The actual entity classeswhich are referenced from the
DataContext or ObjectContext classare exposed through public read-only properties.
It is the generated code that makes it possible to query the database objects in your LINQ to SQL or LINQ
to Entities queries.
Note: The connection string used for connecting to the database is automatically saved to the web.config
file in the connectionStrings element. For a LINQ to SQL Classes project item, the name of the add
element is by default the name of the database, suffixed with ConnectionString. For an ADO.NET Entity
Data Model project item, the name of the add element is by default the name of the ObjectContext
created.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-32

Introduction to Web Development with Microsoft Visual Studio 2010

The following code examples show how to query the entities in the Customers database table by using
LINQ to SQL.
[Visual Basic]
' Initialize data context from web.config
Dim cmDataContext As New CustomerManagementDataContext(
ConfigurationManager.ConnectionStrings("customerManagementConnectionString").ConnectionS
tring)
' Return all customers with a credit limit smaller than 1,000
Dim query = From c In cmDataContext.Customers
Where c.CreditLimit < 1000
Select c
' Iterate through the customers
...
' Dispose of data context
cmDataContext.Dispose()
[Visual C#]
// Initialize data context from web.config
CustomerManagementDataContext cmDataContext = new CustomerManagementDataContext(
ConfigurationManager.ConnectionStrings["customerManagementConnectionString"].ConnectionS
tring);
// Return all customers with a credit limit smaller than 1,000
var query = from c in cmDataContext.Customers
where c.CreditLimit < 1000
select c;
// Iterate through the customers
...
// Dispose of data context
cmDataContext.Dispose();

Ensure that the DataContext or ObjectContext object is appropriately disposed of, as it is usually done
with unmanaged resources. LINQ to SQL and LINQ to Entities both use deferred execution by default,
which means that a LINQ to SQL or LINQ to Entities statement is not run against the database until you
start iterating through the results. This means that you should not dispose of DataContext or
ObjectContext object until the results have been accessed.
The following code examples show how to query the entities in the Customers database table, by using
LINQ to Entities.
[Visual Basic]
' Initialize object context from web.config
Dim cmObjectContext As New CustomerManagementObjectContext(
ConfigurationManager.ConnectionStrings("customerManagementConnectionString").ConnectionS
tring)
' Return all customers with a credit limit smaller than 1,000
Dim query = From c In cmObjectContext.Customers
Where c.CreditLimit < 1000
Select c
' Iterate through the customers

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-33

...
' Dispose of object context
cmObjectContext.Dispose()
[Visual C#]
// Initialize object context from web.config
CustomerManagementObjectContext cmObjectContext = new CustomerManagementObjectContext(
ConfigurationManager.ConnectionStrings["customerManagementConnectionString"].ConnectionS
tring);
// Return all customers with a credit limit smaller than 1,000
var query = from c in cmObjectContext.Customers
where c.CreditLimit < 1000
select c;
// Iterate through the customers
...
// Dispose of data context
cmObjectContext.Dispose();

Question: What is the purpose of using LINQ to SQL?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-34

Introduction to Web Development with Microsoft Visual Studio 2010

Working with SQL Data by Using LINQ

Key Points
When you use SQL data, you might not only want to extract information, you might want to also perform
updates to the database. Similar to the retrieval of entities, you can perform updates by using the
DataContext or ObjectContext object.
For example, you can perform updates such as adding a new country to the countries collection,
modifying the name of a country, or deleting a country by using the DataContext object. The following
code examples show how you can add, modify, or delete a country entity by using LINQ to SQL.
[Visual Basic]
' Create a new Country object
Dim countryObject As New Country With
{
.ID = New Guid("3032b345-092c-de11-8c6e-0003ff4ed632"),
.Name = "Afghanistan",
.DialingCountryCode = "93",
.InternationalDialingCode = "00",
.InternetTLD = "AF"
}
' Add new country to the Countries collection
cmDataContext.Countries.InsertOnSubmit(countryObject)
' Return country to modify
Dim modifyQuery =
From c In cmDataContext.Countries
Where c.Name = "USA"
Select c
' Modify country
For Each c As Country In modifyQuery
c.PhoneNoFormat = "(###) ###-####"
Next
' Return country to delete
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-35

Dim deleteQuery =
From c In cmDataContext.Countries
Where c.ID = New Guid("62750c5e-092c-de11-8c6e-0003ff4ed632")
Select c
' Delete country
cmObjectContext.Countries.DeleteOnSubmit(deleteQuery.First)
' Submit changes to database
Try
cmDataContext.SubmitChanges()
Catch ex As Exception
' Handle exception
...
End Try

[Visual C#]
// Create a new Country object
Country countryObject = new Country
{
ID = new Guid("3032b345-092c-de11-8c6e-0003ff4ed632"),
Name = "Afghanistan",
DialingCountryCode = "93",
InternationalDialingCode = "00",
InternetTLD = "AF"
};
// Add new country to the Countries collection
cmDataContext.Countries.InsertOnSubmit(countryObject);
// Return country to modify
var modifyQuery =
from c in cmDataContext.Countries
where c.Name == "USA"
select c;
// Modify country
foreach (Country c in modifyQuery)
c.PhoneNoFormat = "(###) ###-####";
// Return country to delete
var deleteQuery =
from c in cmDataContext.Countries
where c.ID == new Guid("62750c5e-092c-de11-8c6e-0003ff4ed632")
select c;
// Delete country
cmObjectContext.Countries.DeleteOnSubmit(deleteQuery.First);
// Submit changes to database
try
{
cmDataContext.SubmitChanges();
}
catch (Exception)
{
// Handle exception
...
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-36

Introduction to Web Development with Microsoft Visual Studio 2010

In the example, a new country object is created locally, and then added to the Countries collection of the
DataContext class by using the InsertOnSubmit method. For both the modify and delete operations,
new LINQ queries are run to return exactly the row that you want to modify or delete. When modifying, it
is only necessary to update the specific entity with the correct column values, because the entity will be
marked as modified in the DataContext class. The DeleteOnSubmit method is used to mark the country
for deletion. All the changes to the entities are only performed locally; the changes are submitted to the
database only when the SubmitChanges method is called.
The country, Afghanistan, has been added; the country, Uganda, has been removed; and the phone
number format for the United States has been modified.
The following code examples show how you can add, modify, or delete a country entity by using LINQ to
Entities.
[Visual Basic]
' Create a new Country object
Dim countryObject As New Country With
{
.ID = New Guid("3032b345-092c-de11-8c6e-0003ff4ed632"),
.Name = "Afghanistan",
.DialingCountryCode = "93",
.InternationalDialingCode = "00",
.InternetTLD = "AF"
}
' Add new country to the Countries collection
cmObjectContext.Countries.AddObject(countryObject)
' Return country to modify
Dim modifyQuery =
From c In cmObjectContext.Countries
Where c.Name = "USA"
Select c
' Modify country
For Each c As Country In modifyQuery
c.PhoneNoFormat = "(###) ###-####"
Next
' Return country to delete
Dim deleteQuery =
From c In cmObjectContext.Countries
Where c.ID = New Guid("62750c5e-092c-de11-8c6e-0003ff4ed632")
Select c
' Delete country
cmObjectContext.Countries.DeleteObject(deleteQuery.First)
' Submit changes to database
Try
cmObjectContext.SaveChanges()
Catch ex As Exception
' Handle exception
...
End Try

[Visual C#]
// Create a new Country object
Country countryObject = new Country
{
ID = new Guid("3032b345-092c-de11-8c6e-0003ff4ed632"),
Name = "Afghanistan",

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

};

9-37

DialingCountryCode = "93",
InternationalDialingCode = "00",
InternetTLD = "AF"

// Add new country to the Countries collection


cmObjectContext.Countries.AddObject(countryObject);
// Return country to modify
var modifyQuery =
from c in cmObjectContext.Countries
where c.Name == "USA"
select c;
// Modify country
foreach (Country c in modifyQuery)
c.PhoneNoFormat = "(###) ###-####";
// Return country to delete
var deleteQuery =
from c in cmObjectContext.Countries
where c.ID == new Guid("62750c5e-092c-de11-8c6e-0003ff4ed632")
select c;
// Delete country
cmObjectContext.Countries.DeleteObject(deleteQuery.First);
// Submit changes to database
try
{
cmObjectContext.SaveChanges();
}
catch (Exception)
{
// Handle exception
...
}

In the example, a new country object is created locally and then added to the Countries collection of the
ObjectContext class by using the AddObject method. For both the modify and delete operations, new
LINQ queries are run to return exactly the row that you want to modify or delete. When modifying, it is
only necessary to update the specific entity with the correct column values, because the entity will be
marked as modified in the ObjectContext class. The DeleteObject method is used to mark the country
for deletion. All the changes to the entities are only performed locally; the changes are submitted to the
database only when the SaveChanges method is called.
Question: Which methods will submit and save changes made to the local LINQ to SQL or LINQ to
Entities context, to the database?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-38

Introduction to Web Development with Microsoft Visual Studio 2010

Displaying SQL Data by Using LINQ

Key Points
When you need to display your SQL data in your Web Forms by using LINQ, you can:

Do it all manually.

Directly bind the SQL data to a LinqDataSource or EntityDataSource Web server control, and then
bind the LinqDataSource or EntityDataSource control to one or more Web server controls used for
displaying the data.

The LinqDataSource and EntityDataSource control are very similar to the SqlDataSource control, but
there are differences:

LinqDataSource uses a DataContext object for accessing the database.

EntityDataSource uses an ObjectContext object for accessing the database.

LinqDataSource and EntityDataSource SQL statements can use LINQ queries.

Therefore, if you want to use the LinqDataSource control, you need to add a LINQ to SQL classes project
item, populate it with entities, and then generate the DataContext class. If you want to use the
EntityDataSource control, you need to add an ADO.NET Entity Data Model project item, populate it
with entities, and then generate the ObjectContext class.
The code-generated DataContext or ObjectContext class, is automatically instantiated when it is bound
to a LinqDataSource or EntityDataSource control, and if the data source control is bound to a dataaware Web server control such as the GridView or ListView controls.
If using LINQ to SQL, you need to link the generated DataContext to the LinqDataSource Web server
control, as follows.
[Visual Basic]
' Set data context
CountriesLinqDataSource.ContextTypeName = "CustomerManagementDataContext"
' Set table
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-39

CountriesLinqDataSource.TableName = "Countries"
[Visual C#]
// Set data context
CountriesLinqDataSource.ContextTypeName = "CustomerManagementDataContext";
// Set table
CountriesLinqDataSource.TableName = "Countries";

Notice that at a minimum, you need to set the ContextTypeName and TableName properties, but these
can also be set declaratively, as follows.
<asp:LinqDataSource ID="CountriesLinqDataSource" runat="server"
ContextTypeName="CustomerManagementDataContext" TableName="Countries" />

If using LINQ to Entities, you need to link the generated ObjectContext to the EntityDataSource Web
server control, as follows.
[Visual Basic]
' Set object context
CountriesEntityDataSource.ContextTypeName = "CustomerManagementObjectContext"
' Set entity set
CountriesEntityDataSource.EntitySetName = "Countries"
[Visual C#]
// Set object context
CountriesEntityDataSource.ContextTypeName = "CustomerManagementObjectContext";
// Set entity set
CountriesEntityDataSource.EntitySetName = "Countries";

Notice that at a minimum, you need to set the ContextTypeName and EntitySetName properties, but
these can also be set declaratively, as follows.
<asp:EntityDataSource ID="CountriesEntityDataSource" runat="server"
ContextTypeName="CustomerManagementObjectContext" EntitySetName="Countries" />

At this stage, you can display all the rows from the specified table by using an instance of the specified
DataContext or ObjectContext class. However, that would not make them different from the
SqlDataSource control. It is the Where property and the associated parameters that really make the
LinqDataSource and EntityDataSource controls helpful, because they can be set to values retrieved from
any of the followinga control parameter, a cookie parameter, a form parameter, a profile parameter, a
query string parameter, a session parameter, or a literal value. This means that you can filter data
automatically, based on the value that you set in any of the followinga control property, a cookie
property, a form parameter such as the value of a TextBox control, an ASP.NET Profile parameter, a query
string value, a session value, or a literal value.
You can configure the Where property manually, but setting the parameters can be done more easily by
using the Configure Where Expression dialog box. This dialog box is accessible from the Properties
window by clicking the ellipsis (...) button in the Where field. However, it is easier to use the Configure
Data Source dialog box, which is accessible from Design view of the Web Form on which the
LinqDataSource or EntityDataSource control has been placed.
This following code shows how the generated markup for a LinqDataSource control can look.
<asp:LinqDataSource ID="CountriesLinqDataSource" runat="server"

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-40

Introduction to Web Development with Microsoft Visual Studio 2010

ContextTypeName="CustomerManagementDataContext" TableName="Countries"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"
Where="Name == @Name">
<WhereParameters>
<asp:Parameter DefaultValue="B" Name="Name" Type="String" />
</WhereParameters>
</asp:LinqDataSource>

Notice that the comparison operator is the one used when programming in Visual C#, and that goes for
all the operators, even if you are programming in Visual Basic.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-41

Lab: Managing Data Access Tasks by Using LINQ

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 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 load data from an XML file, and save the data to a database by using LINQ to Entities.
In addition, you will filter and display the data by using LINQ to XML.

Objectives
After completing this lab, you will be able to:

Load data from an XML file.

Display data by using LINQ to XML.

Save data to a database by using LINQ to Entities.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-42

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 has a Web site to manage its customer information. You are responsible for managing the
customer database. Updates to the country data in the database are being delivered in XML files on a
monthly basis, and you need to create a Web Form for importing the XML file into the
CustomerManagement SQL Server database. You also need to filter the XML data for the countries with a
specified phone number from the database. Use LINQ to XML for importing and filtering the XML data,
and LINQ to Entities for inserting the new data into the database.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-43

Section 1: Visual Basic


Exercise 1: Loading Data by Using the XmlDataSource Control
The main tasks in this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Create the ImportCountries Web Form.

3.

Add an XmlDataSource control to the Web Form.

4.

Configure the XmlDataSource control.

5.

Add a GridView control to the Web Form.

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\M9\VB folder.

Task 2: Create the ImportCountries Web Form

Add a new Web Form named ImportCountries, that is based on the Site.master master page.

Open the ImportCountries Web Form in the Design view.

Task 3: Add an XmlDataSource control to the Web Form

Add an existing XML file, D:\Labfiles\Starter\M9\Countries.xml, to the Web site.

Add an XmlDataSource control to the Content control of the ImportCountries Web Form.

Rename the XmlDataSource control you just added to CountriesXmlDataSource.

Save the ImportCountries Web Form.

Task 4: Configure the XmlDataSource control

Open the Configure Data Source control by using the Show Smart Tag option.

Use the Countries.xml data file in the XmlDataSource control.

Save the ImportCountries Web Form.

Task 5: Add a GridView control to the Web Form

Add a GridView control to the Content control of the ImportCountries Web Form.

Rename the GridView control as CountriesGridView.

Set the width of the GridView control to 100%.

Bind the CountriesGridView control to the CountriesXmlDataSource control by using the Smart
Tag.

Save the ImportCountries Web Form.

Build the Web Form and fix any errors.

View the ImportCountries Web Form in the browser.

Close the Windows Internet Explorer browser.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-44

Introduction to Web Development with Microsoft Visual Studio 2010

Results: After completing this exercise, you will have created a Web Form, added a GridView and an
XmlDataSource control to the Web Form, configured the XmlDataSource control for managing
data, and bound the GridView control to the XmlDataSource control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-45

Exercise 2: Displaying Data by Using LINQ to XML


The main tasks in this exercise are as follows:
1.

Add a Button control to the Web Form.

2.

Update sitemap to enable country import.

3.

Load the XML data file manually.

4.

Show the filtered countries by using the GridView control.

Task 1: Add a Button control to the Web Form

Open the ImportCountries Web Form in the Source view.

Add a div element with a class attribute value of importCountriesHeader to the Content control,
above the GridView control.

Add a Button control to the div element.

Change the value for the ID attribute from Button1 to FilterButton.

Change the Text property of the Button control from Button to Filter Countries.
Text="Filter Countries"

Open the ImportCountries Web Form in Design view, and select the FilterButton control.

Add the default code for the Click event of the FilterButton control.

Save the ImportCountries code file.

View the ImportCountries.aspx in Source view.

Add a div element with a class attribute value of importResult to the Content control, between the
GridView control and the div element with a class attribute value of importCountriesHeader.
<div class="importResult">
</div>

Add a Label control to the div element.

Change the value for the ID attribute from Label1 to ImportResultLabel.


ID="ImportResultLabel"

Remove the Text attribute and value.


Text="Label"

Disable view state for the Label control.


EnableViewState="false"

Format and save the ImportCountries Web Form.

Task 2: Update sitemap to enable country import

Open the web.sitemap file.

Append new siteMapNode element to the Countries siteMapNode.


<siteMapNode title="Import" description="Import countries"
url="~/ImportCountries.aspx" />

Save and close the web.sitemap file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-46

Introduction to Web Development with Microsoft Visual Studio 2010

Task 3: Load the XML data file manually

Create a private method named loadCountries, to load the XML data to the ImportCountries class.

Note: The loadCountries method returns an XElement, and takes a string parameter named fileName.
Private Function loadCountries(ByVal fileName As String) As XElement
End Function

Import the System.Xml.Linq namespace.


Imports System.Xml.Linq

Add the code to the loadCountries method to load the content of the file by using the
XElement.Load method, and then return to the caller of the method.
return XElement.Load(Server.MapPath(fileName))

In the Click event handler for the FilterButton control, call the loadCountries method, passing
Countries.xml for the filename, and saving the returned value in an XElement variable named
countries.
Dim countries As XElement = loadCountries("Countries.xml")

Create a shared private member variable of type IEnumerable(XElement) named


countriesWithPhNoFormat, for holding the filtered countries. Initialize to Nothing, in the
ImportCountries class.
Private Shared countriesWithPhNoFormat As IEnumerable(Of XElement) = Nothing

Create a new private method named filterCountries, for filtering the XML data in the
ImportCountries class.

Note: The filterCountries method returns an IEnumerable(XElement), and takes an XElement


parameter named countries.
Private Function filterCountries(ByVal countries As XElement) As IEnumerable(Of
XElement)
End Function

Add a LINQ query to the filterCountries method that searches the child elements of the root node in
the passed countries variable, and returns the result to the caller of the method.
Return _
From c In countries.Elements()
Select c

Add filtering to the LINQ query, selecting the Country elements for which a value for the
PhoneNoFormat attribute has been specified.
Where Not String.IsNullOrEmpty(c.Attribute("PhoneNoFormat"))

Call the filterCountries method, pass the local countries variable, and then save the returned value in
the private member variable named countriesWithPhNoFormat, in the Click event handler of the
FilterButton control.
countriesWithPhNoFormat = filterCountries(countries)

Save the ImportCountries code file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-47

Task 4: Show the filtered countries by using the GridView control

Create a private method named buildXmlString for building an XML string from the filtered XML
data in the ImportCountries class.

Note: The buildXmlString method returns a string and takes an IEnumerable(XElement) parameter
named countriesWithPhNoFormat.
Private Function buildXmlString(ByVal countriesWithPhNoFormat As IEnumerable(Of
XElement)) As String
End Function

Return the value of the passed countriesWithPhNoFormat, wrapped in a root node named
Countries, to the buildXmlString method.
Return "<Countries>" & countriesWithPhNoFormat & "</Countries>"

Call the IEnumerable(XElement).Select method on the countriesWithPhNoFormat variable to


convert each country into a string.
countriesWithPhNoFormat.Select()

Convert all the values in the countriesWithPhNoFormat variable to strings by using the ToString
method in an anonymous Lambda function, placed in the call to the Select method.
countriesWithPhNoFormat.Select(Function(x) x.ToString())

Convert the current output from the Select method to an array by using the ToArray method.
countriesWithPhNoFormat.Select(Function(x) x.ToString()).ToArray()

Join the current output from the ToArray method by using the String.Join method, specifying an
empty string separator.
String.Join("", countriesWithPhNoFormat.Select(Function(x) x.ToString()).ToArray())

Assign the return value of the buildXmlString method to the Data property of the
CountriesXmlDataSource control, passing the countriesWithPhNoFormat private member variable
to the buildXmlString method.
CountriesXmlDataSource.Data = buildXmlString(countriesWithPhNoFormat)

Reset the DataFile property of the CountriesXmlDataSource control, ensuring that the Data
property is used when rendering.
CountriesXmlDataSource.DataFile = ""

Build the ImportCountries Web Form, and fix any errors.

View the ImportCountries Web Form in the browser.

Filter the countries from the ImportCountries Web Form.

Close the Internet Explorer browser.


Results: After completing this exercise, you will have loaded the content of the XML file manually,
added a Button control to the Web Form, added code to the Click event for filtering the loaded
countries, and displayed the filtered XML data in a GridView control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-48

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Saving Data by Using LINQ to Entities


The main tasks for this exercise are as follows:
1.

Add a Button control to the Web Form.

2.

Add an ADO.NET Entity Data Model project item to the Web site project.

3.

Create an ObjectContext object.

4.

Insert the filtered XML data in the local ObjectContext data.

5.

Submit the local ObjectContext data to the database.

Task 1: Add a Button control to the Web Form

Open the ImportCountries Web Form in Source view.

Add a Button control next to the FilterButton control.

Change the value for the ID attribute from Button1 to SaveButton.


ID="SaveButton"

Change the value for the Text property from Button to Save Countries.
Text="Save Countries"

Open the ImportCountries Web Form in Design view, and double-click the SaveButton control.

Save the ImportCountries code file.

Task 2: Add an ADO.NET Entity Data Model project item to the Web site project

Add an ADO.NET Entity Data Model project item named CustomerManagement.edmx.

In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from
database, and then click Next.

On the Choose Your Data Connection page, on the Which data connection should your
application use to connect to the database? list, click CustomerManagementConnectionString
(Settings), in the box below the Save entity connection settings in Web.config as check box, type
Entities, and then click Next.

On the Choose Your Database Objects page, on the Which database objects do you want to
include in your model? list, expand Tables, click Countries (dbo), click Customers (dbo), click
Pluralize or singularize generated object names , and then click Finish.

Save the ADO.NET Entity Data Model item.

Close the ADO.NET Entity Data Model item.

Task 3: Create an ObjectContext object

Create a private method named saveCountries in the ImportCountries class, for saving the filtered
XML data.

Note: The saveCountries method does not return a value, but it takes an IEnumerable(XElement)
parameter named countriesWithPhNoFormat.
Private Sub saveCountries(ByVal countriesWithPhNoFormat As IEnumerable(Of XElement))
End Sub

Add code to create and instantiate an ObjectContext of type


CustomerManagementModel.Entities, named cmObjectContext, retrieving the

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-49

CustomerManagementEntities connection string from the web.config file by using the


System.Web.Configuration.WebConfigurationManager class.
Dim cmObjectContext As New CustomerManagementModel.Entities(
System.Web.Configuration.WebConfigurationManager.
ConnectionStrings("Entities").ConnectionString)

Task 4: Insert the filtered XML data in the local ObjectContext data

Add code to loop through the Country elements in the passed countriesWithPhNoFormat variable,
by using a For Each construct.
' Loop through the filtered countries
For Each country As XElement In countriesWithPhNoFormat
Next

Add code to insert each country in the Countries collection of the cmObjectContext object by using
the AddObject method, and by passing the values from the filtered XML.
' Loop through the filtered countries
For Each country As XElement In countriesWithPhNoFormat
' Add the new country to the Countries collection
cmObjectContext.Countries.AddObject(New CustomerManagementModel.Country With
{
.ID = New Guid(country.Attribute("ID").Value),
.Name = country.Attribute("Name").Value,
.PhoneNoFormat = country.Attribute("PhoneNoFormat").Value,
.DialingCountryCode = country.Attribute("DialingCountryCode").Value,
.InternationalDialingCode =
country.Attribute("InternationalDialingCode").Value,
.InternetTLD = country.Attribute("InternetTLD").Value
})
Next

Task 5: Submit the local ObjectContext data to the database

Add a Try Catch Finally construct for saving the local modifications to database. The Catch code
must catch all exceptions.
' Save to database
Try
Catch ex As Exception
Finally
End Try

Add a call to submit the local modifications to the database by using the SaveChanges method of
the ObjectContext object in the Try part.
' Save to database
Try
cmObjectContext.SaveChanges()
Catch ex As Exception
Finally
End Try

Display successful import result message by setting the Text property of the ImportResultLabel
control to Rows successfully exported to SQL Server table in the Try part.
' Display success message
ImportResultLabel.Text = "Rows successfully exported to SQL Server table."

Add code to display a custom error message by setting the Text property of the ImportResultLabel
control to An error occurred exporting to SQL Server.<br/> in the Catch part. Append the value
of the Message property of the caught Exception, and two additional line breaks <br/><br/>. The

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-50

Introduction to Web Development with Microsoft Visual Studio 2010

text color must be set to red, by setting the ForeColor property of the Label control to the value
System.Drawing.Color.Red.
Catch ex as Exception
' Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>" &
ex.Message & "<br/><br/>"
ImportResultLabel.ForeColor = System.Drawing.Color.Red

Add a more specific Catch statement to the Try Catch Finally construct for catching exceptions that
are thrown when errors occur during the actual update, by catching exceptions of type
System.Data.UpdateException. The Catch code must be added before the existing catch.
' Save to database
Try
cmObjectContext.SaveChanges()
' Display success message
ImportResultLabel.Text = "Rows successfully exported to SQL Server table."
Catch ex As System.Data.UpdateException
Catch ex As Exception
' Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>" &
ex.Message & "<br/><br/>"
ImportResultLabel.ForeColor = System.Drawing.Color.Red
Finally
End Try

Add code to display a custom error message by setting the Text property of the ImportResultLabel
control to An error occurred exporting to SQL Server.<br/>One or more of the rows already
exist in the table.<br/><br/> in the new Catch. The text color must be set to red by setting the
ForeColor property of the Label control to System.Drawing.Color.Red.
Catch ex As System.Data.UpdateException
' Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>One or
more of the rows already exist in the table.<br/><br/>"
ImportResultLabel.ForeColor = System.Drawing.Color.Red

Add code to dispose the ObjectContext object in the Finally part.


Finally
cmObjectContext.Dispose()

Call the saveCountries method by passing the static countriesWithPhNoFormat private member
variable from the Click event handler of the SaveButton control.
saveCountries(countriesWithPhNoFormat)

Build the ImportCountries Web Form, and fix any errors.

View the ImportCountries Web Form in the Solution Explorer browser.

Note: Notice that the CountriesGridView control displays the content of the XML data file.

Filter the countries from the ImportCountries Web Form.

Save the imported countries in the database.

Note: If you try to save the countries that already exist in the SQL database, you will receive an error
message.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-51

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 a Button control to the Web Form,
added an ADO.NET Entity Data Model project item, created an ObjectContext object, and saved the
imported countries to the database.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-52

Introduction to Web Development with Microsoft Visual Studio 2010

Section 2: Visual C#
Exercise 1: Loading Data by Using the XmlDataSource Control
The main tasks in this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Create the ImportCountries Web Form.

3.

Add an XmlDataSource control to the Web Form.

4.

Configure the XmlDataSource control.

5.

Add a GridView control to the Web Form.

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\M9\CS folder.

Task 2: Create the ImportCountries Web Form

Add a new Web Form named ImportCountries, that is based on the Site.master master page.

Open the ImportCountries Web Form in the Design view.

Task 3: Add an XmlDataSource control to the Web Form

Add an existing XML file, D:\Labfiles\Starter\M9\Countries.xml, to the Web Site.

Add an XmlDataSource control to the Content control of the ImportCountries Web Form.

Rename the XmlDataSource control that you just added to CountriesXmlDataSource.

Save the ImportCountries Web Form.

Task 4: Configure the XmlDataSource control

Open the Configure Data Source control by using the Show Smart Tag option.

Use the Countries.xml data file in the XmlDataSource control.

Save the ImportCountries Web Form.

Task 5: Add a GridView control to the Web Form

Add a GridView control to the Content control of the ImportCountries Web Form.

Rename the GridView control as CountriesGridView.

Set the width of the GridView control to 100%.

Bind the CountriesGridView control to the CountriesXmlDataSource control by using the Smart
Tag.

Save the ImportCountries Web Form.

Build the Web Form and fix any errors.

View the ImportCountries Web Form in the browser.

Close Internet Explorer.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-53

Results: After completing this exercise, you will have created a Web Form, added a GridView and an
XmlDataSource control to the Web Form, configured the XmlDataSource control for managing
data, and bound the GridView control to the XmlDataSource control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-54

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 2: Displaying Data by Using LINQ to XML


The main tasks in this exercise are as follows:
1.

Add a Button control to the Web Form.

2.

Update sitemap to enable country import.

3.

Load the XML data file manually.

4.

Show the filtered countries by using the GridView control.

Task 1: Add a Button control to the Web Form

Open the ImportCountries Web Form in the Source view.

Add a div element with a class attribute value of importCountriesHeader to the Content control,
above the GridView control.

Add a Button control to the div element.

Change the value for the ID attribute from Button1 to FilterButton.

Change the Text property of the Button control from Button to Filter Countries.
Text="Filter Countries"

Open the ImportCountries Web Form in Design view, and then select the FilterButton control.

Add the default code for the Click event of the FilterButton control.

Save the ImportCountries code file.

View the ImportCountries.aspx in Source view.

Add a div element with a class attribute value of importResult to the Content control, between the
GridView control and the div element with a class attribute value of importCountriesHeader.
<div class="importResult">
</div>

Add a Label control to the div element.

Change the value for the ID attribute from Label1 to ImportResultLabel.


ID="ImportResultLabel"

Remove the Text attribute and value.


Text="Label"

Disable view state for the Label control.


EnableViewState="false"

Format and save the ImportCountries Web Form.

Task 2: Update sitemap to enable country import

Open the web.sitemap file.

Append new siteMapNode element to the Countries siteMapNode.


<siteMapNode title="Import" description="Import countries"
url="~/ImportCountries.aspx" />

Save and close the web.sitemap file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-55

Task 3: Load the XML data file manually

Create a private method named loadCountries, to load the XML data to the ImportCountries class.

Note: The loadCountries method returns an XElement, and takes a string parameter named fileName.
private XElement loadCountries(string fileName)
{
}

Import the System.Xml.Linq namespace.


using System.Xml.Linq;

Add the code to the loadCountries method to load the content of the file by using the
XElement.Load method, and then return to the caller of the method.
return XElement.Load(Server.MapPath(fileName));

In the Click event handler for the FilterButton control, call the loadCountries method, passing
Countries.xml for the filename, and saving the returned value in an XElement variable named
countries.
XElement countries = loadCountries("Countries.xml");

Create a static private member variable of type IEnumerable(XElement) named


countriesWithPhNoFormat, for holding the filtered countries. Initialize to null, in the
ImportCountries class.
static private IEnumerable<XElement> countriesWithPhNoFormat = null;

Create a new private method named filterCountries, for filtering the XML data in the
ImportCountries class.

Note: The filterCountries method returns an IEnumerable(XElement), and takes an XElement


parameter named countries.
private IEnumerable<XElement> filterCountries(XElement countries)
{
}

Add a LINQ query to the filterCountries method that searches the child elements of the root node in
the passed countries variable, and returns the result to the caller of the method.
return
from c in countries.Elements()
select c;

Add filtering to the LINQ query, selecting the Country elements for which a value for the
PhoneNoFormat attribute has been specified.
where c.Attribute("PhoneNoFormat") != null &&
(string) c.Attribute("PhoneNoFormat").Value != ""

Call the filterCountries method, pass the local countries variable, and then save the returned value in
the private member variable named countriesWithPhNoFormat, in the Click event handler of the
FilterButton control.
countriesWithPhNoFormat = filterCountries(countries);

Save the ImportCountries code file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-56

Introduction to Web Development with Microsoft Visual Studio 2010

Task 4: Show the filtered countries by using the GridView control

Create a private method named buildXmlString for building an XML string from the filtered XML
data in the ImportCountries class.

Note: The buildXmlString method returns a string and takes an IEnumerable(XElement) parameter
named countriesWithPhNoFormat.
private string buildXmlString(IEnumerable<XElement> countriesWithPhNoFormat)
{
}

Return the value of the passed countriesWithPhNoFormat, wrapped in a root node named
Countries, to the buildXmlString method.
return "<Countries>" + countriesWithPhNoFormat + "</Countries>";

Call the IEnumerable(XElement).Select method on the countriesWithPhNoFormat variable to


convert each country into a string.
countriesWithPhNoFormat.Select()

Convert all the values in the countriesWithPhNoFormat variable to strings by using the ToString
method in an anonymous Lambda function, placed in the call to the Select method.
countriesWithPhNoFormat.Select(x => x.ToString())

Convert the current output from the Select method to an array by using the ToArray method.
countriesWithPhNoFormat.Select(x => x.ToString()).ToArray()

Join the current output from the ToArray method by using the String.Join method, specifying an
empty string separator.
string.Join("", countriesWithPhNoFormat.Select(x => x.ToString()).ToArray())

Assign the return value of the buildXmlString method to the Data property of the
CountriesXmlDataSource control, passing the countriesWithPhNoFormat private member variable
to the buildXmlString method.
CountriesXmlDataSource.Data = buildXmlString(countriesWithPhNoFormat);

Reset the DataFile property of the CountriesXmlDataSource control, ensuring that the Data
property is used when rendering.
CountriesXmlDataSource.DataFile = "";

Build the ImportCountries Web Form, and fix any errors.

View the ImportCountries Web Form in the browser.

Filter the countries from the ImportCountries Web Form.

Close Internet Explorer.


Results: After completing this exercise, you will have loaded the content of the XML file manually,
added a Button control to the Web Form, added code to the Click event for filtering the loaded
countries, and displayed the filtered XML data in a GridView control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-57

Exercise 3: Saving Data by Using LINQ to Entities


The main tasks for this exercise are as follows:
1.

Add a Button control to the Web Form.

2.

Add an ADO.NET Entity Data Model project item to the Web site project.

3.

Create an ObjectContext object.

4.

Insert the filtered XML data in the local ObjectContext data.

5.

Submit the local ObjectContext data to the database.

Task 1: Add a Button control to the Web Form

Open the ImportCountries Web Form in the Source view.

Add a Button control next to the FilterButton control.

Change the value for the ID attribute from Button1 to SaveButton.


ID="SaveButton"

Change the value for the Text property from Button to Save Countries.
Text="Save Countries"

Open the ImportCountries Web Form in Design view, and double-click the SaveButton control.

Save the ImportCountries code file.

Task 2: Add an ADO.NET Entity Data Model project item to the Web site project

Add an ADO.NET Entity Data Model project item named CustomerManagement.edmx.

In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from
database, and then click Next.

On the Choose Your Data Connection page, on the Which data connection should your
application use to connect to the database? list, click CustomerManagementConnectionString
(Settings), in the box below the Save entity connection settings in Web.config as check box, type
Entities, and then click Next.

On the Choose Your Database Objects page, on the Which database objects do you want to
include in your model? list, expand Tables, click Countries (dbo), click Customers (dbo), click
Pluralize or singularize generated object names, and then click Finish.

Save the ADO.NET Entity Data Model item.

Close the ADO.NET Entity Data Model item.

Task 3: Create an ObjectContext object

Create a private method named saveCountries in the ImportCountries class, for saving the filtered
XML data.

Note: The saveCountries method does not return a value, but it takes an IEnumerable(XElement)
parameter named countriesWithPhNoFormat.
private void saveCountries(IEnumerable<XElement> countriesWithPhNoFormat)
{
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-58

Introduction to Web Development with Microsoft Visual Studio 2010

Add code to create and instantiate an ObjectContext of type


CustomerManagementModel.Entities named cmObjectContext, retrieving the
CustomerManagementEntities connection string from the web.config file by using the
System.Web.Configuration.WebConfigurationManager class.
CustomerManagementModel.Entities cmObjectContext =
new CustomerManagementModel.Entities(
System.Web.Configuration.WebConfigurationManager.
ConnectionStrings["Entities"].ConnectionString);

Task 4: Insert the filtered XML data in the local ObjectContext data

Add code to loop through the Country elements in the passed countriesWithPhNoFormat variable,
by using a For Each construct.
// Loop through the filtered countries
foreach (XElement country in countriesWithPhNoFormat)
{
}

Add code to insert each country in the Countries collection of the cmObjectContext object by using
the AddObject method, and by passing the values from the filtered XML.
// Add the new country to the Countries collection
cmObjectContext.Countries.AddObject(new CustomerManagementModel.Country
{
ID = new Guid(country.Attribute("ID").Value),
Name = country.Attribute("Name").Value,
PhoneNoFormat = country.Attribute("PhoneNoFormat").Value,
DialingCountryCode = country.Attribute("DialingCountryCode").Value,
InternationalDialingCode = country.Attribute("InternationalDialingCode").Value,
InternetTLD = country.Attribute("InternetTLD").Value
});

Task 5: Submit the local ObjectContext data to the database

Add a try catch finally construct for saving the local modifications to database. The catch code must
catch all exceptions.
// Save to database
try
{
}
catch (Exception ex)
{
}
finally
{
}

Add a call to submit the local modifications to the database by using the SaveChanges method of
the ObjectContext object in the try part.
// Save to database
try
{
cmObjectContext.SaveChanges();
}
catch (Exception ex)
{
}
finally
{
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-59

Display successful import result message, by setting the Text property of the ImportResultLabel
control to Rows successfully exported to SQL Server table in the try part.
// Display success message
ImportResultLabel.Text = "Rows successfully exported to SQL Server table.";

Add code to display a custom error message by setting the Text property of the ImportResultLabel
control to An error occurred exporting to SQL Server.<br/> in the Catch part. Append the value
of the Message property of the caught Exception, and two additional line breaks <br/><br/>. The
text color must be set to red, by setting the ForeColor property of the Label control to the value
System.Drawing.Color.Red.
catch (Exception ex)
{
// Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>" +
ex.Message + "<br/><br/>";
ImportResultLabel.ForeColor = System.Drawing.Color.Red;
}

Add a more specific catch to the try catch finally construct for catching exceptions that are thrown
when errors occur during the actual update, by catching exceptions of type
System.Data.UpdateException. The catch code must be added before the existing catch.
// Save to database
try
{
cmObjectContext.SaveChanges();
// Display success message
ImportResultLabel.Text = "Rows successfully exported to SQL Server table.";

}
catch (System.Data.UpdateException)
{
}
catch (Exception ex)
{
// Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>" +
ex.Message + "<br/><br/>";
ImportResultLabel.ForeColor = System.Drawing.Color.Red;
}
finally
{
}

Add code to display a custom error message by setting the Text property of the ImportResultLabel
control to An error occurred exporting to SQL Server.<br/>One or more of the rows already
exist in the table.<br/><br/> in the new catch. The text color must be set to red, by setting the
ForeColor property of the Label control to the value System.Drawing.Color.Red.
catch (System.Data.UpdateException)
{
// Display error
ImportResultLabel.Text = "An error occurred exporting to SQL Server.<br/>One or
more of the rows already exist in the table.<br/><br/>";
ImportResultLabel.ForeColor = System.Drawing.Color.Red;
}

Add code to dispose the ObjectContext object in the finally part.


finally
{
cmObjectContext.Dispose();
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-60

Introduction to Web Development with Microsoft Visual Studio 2010

Call the saveCountries method by passing the static countriesWithPhNoFormat private member
variable from the Click event handler of the SaveButton control.
saveCountries(countriesWithPhNoFormat);

Build the ImportCountries Web Form, and fix any errors.

View the ImportCountries Web Form in the Solution Explorer browser.

Note: Notice that the CountriesGridView control displays the content of the XML data file.

Filter the countries from the ImportCountries Web Form.

Save the imported countries in the database.

Note: If you try to save the countries that already exist in the SQL database, you will receive an error
message.
Results: After completing this exercise, you will have added a Button control to the Web Form,
added an ADO.NET Entity Data Model project item, created an ObjectContext object, and saved the
imported countries to the database.

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.

Note: The answers to the exercises are on the Course Companion CD.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data Access Tasks by Using LINQ

9-61

Lab Review

Review Questions and Answers


1.

What types of data can you query by using LINQ?

2.

Why do you use stored procedures instead of accessing the database directly?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

9-62

Introduction to Web Development with Microsoft Visual Studio 2010

Module Review and Takeaways

Review Questions and Answers


1.

What are the tools and features provided by Visual Studio 2010 to support application development
using LINQ?

2.

What are the three models provided by the .NET Framework for processing XML data?

3.

What are the panes available in Object Relational Designer design surface?

Real-World Issues and Scenarios


1.

You need to display data from an XML file that is queried by using LINQ to XML. What is the easiest
way to display the data returned from the query?
You can use the XmlDataSource control.

2.

Your Web application has been deployed to a production server, but one of the tables in the SQL
Server database has a new column added. You need to update the DataContext so that that new
column can be returned in the LINQ to SQL queries when all the columns are returned. How will you
implement this without using Visual Studio 2010?
You should use the SqlMetal.exe command-line tool.

Best Practices
Mention some best practices in the context of your own business situations.

DataContext and ObjectContext objects should always be disposed of.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-1

Module 10
Managing Data by Using Microsoft ASP.NET Dynamic Data
Contents:
Lesson 1: Overview of ASP.NET Dynamic Data

10-3

Lesson 2: Applying ASP.NET Dynamic Data

10-24

Lesson 3: Customizing ASP.NET Dynamic Data Applications

10-34

Lab: Managing Data by Using ASP.NET Dynamic Data

10-46

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-2

Introduction to Web Development with Microsoft Visual Studio 2010

Module Overview

Using Rapid Application Development (RAD), you can create prototypes of your application. You can drag
controls to the design surface, and then build and run the application. By creating and sharing prototypes
of an application with a customerwhether internal or externalyou can get immediate feedback from
the customer. However, there may be a few issues with using RAD. The quality of the generated code may
not be consistent, and the code may not be easy to maintain. There may also be security issues because of
manual coding, such as ensuring correct input validation. The security risk is particularly applicable to
data-driven Web development, when the Web application not only displays the data in the database, but
also manages it.
Microsoft ASP.NET Dynamic Data resolves these issues in RAD development. ASP.NET Dynamic Data is a
framework that enables you to quickly build a functional data-driven application based on a languageintegrated query (LINQ) to SQL, or Entity Framework, data model.
ASP.NET Dynamic Data is used to create data-driven applications. Data-driven applications use,
manipulate, and analyze data to perform tasks. Currently, data-driven applications use routing for
displaying data from a data source. ASP.NET Dynamic Data can also be used for creating Web sites that
display and manage data that is automatically read and written to the data source, with little or no
coding.
This module explains ASP.NET Dynamic Data, and how you can use it with LINQ to SQL to manage your
data from a Web user interface (UI), with very little coding.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-3

Lesson 1

Overview of ASP.NET Dynamic Data

ASP.NET Dynamic Data provides a framework that enables you to quickly build a functional data-driven
application, based on either a LINQ to SQL data model, or the Entity Framework data model. ASP.NET
Dynamic Data improves usability and data-driven RAD by using existing ASP.NET data controls. RAD is
made easy because of the rich ASP.NET Dynamic Data scaffolding framework. A scaffolding framework
provides a functional Web application for viewing and editing data. If you add a LINQ to SQL or Entity
Framework data model to a project, you can register it with Dynamic Data, and have a fully functional
Web site for managing your data. If supported by a data source, you can perform Create, Read, Update,
and Delete (CRUD) operations. The Web site includes the filtering of data by both foreign keys and
Boolean fields. Also, you can add smart validation based on database constraints for nullable fields, data
types, and field lengths, by using Web server validation controls.
In this lesson, you will learn about the ASP.NET Dynamic Data framework, including the project
infrastructure, the scaffolding, the field and page templates, and the routing.

Lesson Objectives
After completing this lesson, you will be able to:

Describe ASP.NET Dynamic Data.

Describe the Dynamic Data project infrastructure.

Explain how to implement ASP.NET Dynamic Data scaffolding.

Describe ASP.NET Dynamic Data templates.

Describe ASP.NET Dynamic Data routing.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-4

Introduction to Web Development with Microsoft Visual Studio 2010

What Is ASP.NET Dynamic Data?

Key Points
The ASP.NET Dynamic Data framework helps you create data-driven ASP.NET Web applications. The
Dynamic Data framework automatically discovers the data-model metadata at run time, and uses the
metadata to derive the UI behavior. The scaffolding framework provides a functional Web site to manage
data. You can customize the scaffolding framework to override the default behavior. You can also
integrate the scaffolding elements with your existing ASP.NET Web Forms and applications.

Data Model
The data model represents information in a database, and depicts how the database objects are related.
Dynamic Data supports both the LINQ to SQL data model, and the Microsoft ADO.NET Entity Framework
data model.
If you register the data models with Dynamic Data, the data model can perform automatic validation of
data fields. You can also control the appearance and behavior of data at the data layer level by annotating
or applying attributes to the data model. For example, you can annotate that a table should be part of the
Web application, and a field should be shown when the data in the containing table is shown. You can
also add a display name attribute for a field that it is different from the actual field name, and add a field
description attribute that is used by Dynamic Data to add a tool tip when you mouse over the control that
is used to display the field and value.
You can include multiple instances of data models in a Web application, but the models that are used in
Dynamic Data must be of the same type. ASP.NET Dynamic Data is model-oriented, because the Dynamic
Data infrastructure is based on the data model. You can use the Dynamic Data infrastructure to control
the request routing, control the look and feel of the user interface, and manage the data source.

Scaffolding
Scaffolding enhances the existing ASP.NET page framework by dynamically displaying pages that are
based on the data model. Scaffolding provides the following capabilities:

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-5

Allows you to create a data-driven Web application with little or no code.

Provides built-in data validation based on the database schema, which is part of the data model.

Creates automatic filters for each foreign key or Boolean field, which are derived from the database
schema.

Templates
ASP.NET Dynamic Data is based on a number of generic templates that you can use to display various
data. These include page templates, and field templates. The templates are disk-based filessuch as Web
Form and User Control templatesthat are used at run time by Dynamic Data for generating the
rendered pages, and controlling the pages that contain data from the data source.

Page Templates. You can use page templates to provide a default view of data entities. These
templates are ASP.NET Web Forms that are configured to display data from any entity in the data
model. They are generic, because the Web Forms are not specific to a single database entitysuch as
a table. Dynamic Data provides page templates for different views of data, including:

List view, which lists the table rows and is the default view.

Details view, which displays the details for a single row.

Edit view, which allows you to edit rows.

List Details view, which displays parent and child entities as a master and details view.

Insert view, which allows you to insert a row.

You can modify the routing for your Web application to use any page template as the default
template, or to use different page templates for different purposes. You can modify the existing page
templates, and create custom page templates.

Field Templates. Dynamic data uses field templates to render the UI for managing the data in the
individual data fields. Dynamic Data determines the appropriate field template from the data field
types in the data model schema. Dynamic Data includes separate field templates for displaying and
editing data fields.
You can customize the built-in field templates, or create new ones to specify how individual data
fields are rendered. You can override the use of the default field templates by creating your own
custom field templates, and then annotate the data model to use those field templates. This is
performed by applying the UIHint attribute to the field that uses the field template in the data
model.

Data Controls
Dynamic Data enhances existing data controls to include dynamic behavior. ASP.NET 4.0 provides several
complex, template-based data-bound controls, including the GridView, DetailsView, ListView, and
FormView Web server controls. Dynamic Data enhances these existing data controls to include dynamic
behavior.

The GridView and DetailsView controls display data dynamically by using predefined Dynamic Data
templates. You can customize these templates and use specific controls for rendering the UI for
managing the data fields. This enables you to make changes in one location t affect the appearance
and behavior of the data controls across the Web application. The DynamicField class is used by the
GridView and DetailsView controls to display a field value.

The ListView and FormView controls are similar to the GridView and DetailsView controls, but
implement the behavior by using a DynamicControl control in their templates. Unlike the GridView
and DetailsView controls, you must manually specify the data entity field that the ListView and
FormView controls need to manage. Dynamic Data automatically builds the UI for these controls

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-6

Introduction to Web Development with Microsoft Visual Studio 2010

based on the specified templates. DynamicControl controls do not automatically render the UI for
any field; you must bind the controls to a specific data field.
At run time, Dynamic Data examines the data model metadata and provides automatic validation
based on the metadata. For example, if a column in the database is marked as not nullable, a
RequiredFieldValidator control is automatically rendered for that column. You can also apply
custom metadata to further customize how data fields are rendered and validated.
Question: What are the some of the capabilities provided by ASP.NET Dynamic Data?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-7

Dynamic Data Project Infrastructure

Key Points
The infrastructure of an ASP.NET Dynamic Data Web site project or ASP.NET Dynamic Data Web
application project is slightly different from a standard ASP.NET Web site project or ASP.NET Web
application project. In that the ASP.NET Dynamic Data projects, there are a number of extra folders and
files that are created by default.
You can create an ASP.NET Dynamic Data Web site or ASP.NET Dynamic Data Web application in
Microsoft Visual Studio 2010 by using either the ASP.NET Dynamic Data Web Site template, or the
ASP.NET Dynamic Data Web Application template. These templates generate the user controls, page
templates, and ASP.NET Web files that Dynamic Data uses to create the UI for working with the data.

DataContext or ObjectContext Class


An ASP.NET Dynamic Data Web applicationwhether created by using the ASP.NET Dynamic Data Web
Site template or the ASP.NET Dynamic Data Web Application templaterequires a
System.Web.DynamicData.MetaModel object and a registered DataContext or ObjectContext class.
The context can either be a LINQ to SQL class or an ADO.NET Entity Framework class. The DataContext
or ObjectContext class should be in the App_Code folder at the root of the application.

Folders and Files


The following table lists the folders and files that are created at the root level, in a Dynamic Data Web site
or Dynamic Data Web application.
Folder or file

Description

DynamicData

This subfolder contains folders for the user controls and Web Forms that
display data. The user controls are the field templates, and the Web Forms are
the page templates.

Global.asax

The Global Application file (Global.asax) can also be part of a standard

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-8

Introduction to Web Development with Microsoft Visual Studio 2010

Folder or file

Description
ASP.NET Web site. In a Dynamic Web site, the file registers an instance of the
MetaModel class, to add routes to the
System.Web.Routing.RouteCollection object, and to register the
DataContext or ObjectContext class with the MetaModel class.

Scripts

This subfolder contains the JavaScript files that are required for the use of
Asynchronous JavaScript and XML (Ajax) or jQuery.

Site.master

Site.master is the master page for the Dynamic Data Web site, and it is used
by all Dynamic Data page templates. The Site.master master page is similar to
a standard master page, but it does contain a
System.Web.UI.ScriptManager control, with an EnablePartialRendering
property that is set to false. The ScriptManager class manages the ASP.NET
Ajax script libraries and script files, partial-page rendering, and client proxy
class generation for Web application services.

web.config

This is the Web site configuration file, which is common for all ASP.NET Web
sites and Web applications.

Global Application File


In a Dynamic Data Web site, the Global.asax file contains a handler for the Application_Start event that is
raised when the Web application starts. In the handler, the RegisterRoutes method is called. By default,
the RegisterRoutes method contains a MetaModel instance, and a commented-out call to the
RegisterContext method. To enable Dynamic Data operations, you must enable the RegisterContext
method, and pass to it a valid data context, such as a DataContext instance or an ADO.NET Entity
Framework context.
By default, the Global.asax file in a Dynamic Data Web site calls the Add(Type) method to add routing for
each action, and for the List.aspx, Details.aspx, Edit.aspx, and Insert.aspx pages.

DynamicData Subfolder Structure


The following table describes the subfolders in the DynamicData subfolder.
File or folder

Description

Content

This folder contains the Images folder, which contains the graphics files used as
icons for the GridViewPager user control. The Content subfolder also contains
the GridViewPager.ascx user control, which is used to enhance paging when
there is more than one page of data for an entity.

CustomPages

This folder is a container folder for your custom page templates, which are used
to override the built-in or modified page templates in the PageTemplates
subfolder. For example, if the data context contains a table named Products, you
can create a DynamicData\CustomPages\Products folder, and then add .aspx
pages to the new folder, which is used to display the Products data. You can
copy the pages from the DynamicData\PageTemplates folder into the new
DynamicData\CustomPages\Products folder, and then modify the templates.

EntityTemplates

This folder contains the default entity templates, which are used to build the UI
for displaying tables.

FieldTemplates

This folder contains the Dynamic Data user controls that map to data types
from the data model, including the Boolean.ascx, Boolean_Edit.ascx,
Children.ascx, DateTime.ascx, DateTime_Edit.ascx, Decimal_Edit.ascx,

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

File or folder

10-9

Description
ForeignKey.ascx, ForeignKey_Edit.ascx, Integer_Edit.ascx,
MultilineText_Edit.ascx, Text.ascx, and Text_Edit.ascx user controls.

Filters

This folder contains the user control filter templates that are used to create
the UI for table row filtering, including the Boolean.ascx, Enumeration.ascx,
and ForeignKey.ascx user controls.

PageTemplates

This folder is a container folder for the built-in page templatesthe


Details.aspx, Edit.aspx, Insert.aspx, List.aspx, and ListDetails.aspx Web
Formswhich produce the UI that is used for managing the data.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-10

Introduction to Web Development with Microsoft Visual Studio 2010

ASP.NET Dynamic Data Scaffolding

Key Points
Scaffolding makes it possible to dynamically create pages at run time that are based on the data model
without needing a physical page, by extending the existing ASP.NET page framework.
To enable the managing of the data in an entity in the data model, scaffolding must be enabled for all
entities, or for a particular entity. Note that if you enable scaffolding for all entities, any usermalicious or
notmay be able to work out the schema of the database. However, if you are creating a simple data
management application, this might be the best choice because it will save you development time.
You can also enable scaffolding on the registration of the data or object context in the global application
file. This registration is made by using the RegisterContext method, which takes a
System.Web.DynamicData.ContextConfiguration object parameter.
You are required to register the data context that will use Dynamic Data features, even if you are not
going to use the scaffolding mechanism. This registration is made in the Global.asax file by using the
RegisterContext method. The RegisterContext method accepts a ContextConfiguration object as a
parameter. To enable the scaffolding mechanism while registering the data or object context, set the
ScaffoldAllTables property of the ContextConfiguration object to true. This will enable the scaffolding
mechanism for the whole data model.
[Visual Basic]
DefaultModel.RegisterContext(GetType(MyObjectContext),
New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(MyObjectContext),
new ContextConfiguration() { ScaffoldAllTables = true });

The risk in doing this is that while you know the tables that are exposed at this point in time, you might
add more entities to the DataContext or ObjectContext class at a later stage, and these entities will also
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-11

be exposed by the scaffolding. However, even if you choose to use this approach, you can specifically hide
entities from the scaffolding mechanism by using the ScaffoldTableAttribute attribute. You can use the
ScaffoldTableAttribute attribute to set the ScaffoldAllTables property to False/false when registering
with the data model. You can also use the ScaffoldTableAttribute attribute to enable or disable the
scaffolding mechanism for a given entity, by applying the attribute to a partial class with the same name
as the entity in the data model. In the following code examples, the partial class is manually created, with
the scaffolding enabled for the Orders entity.
[Visual Basic]
Imports Microsoft.VisualBasic
Imports System.ComponentModel.DataAnnotations
<ScaffoldTable(True)>
Partial Public Class Order
...
End Class

[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
[ScaffoldTable(true)]
public partial class Order
{
...
}

Notice that the class is named Order, in singular, and not Orders in plural when you use LINQ to SQL or
the ADO.NET Entity Data Model to name the classes. Because the Order class is a partial class, you must
use the same name that the data model uses.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-12

Introduction to Web Development with Microsoft Visual Studio 2010

Demonstration: How to Implement ASP.NET Dynamic Data Scaffolding

Key Points
In this demonstration, you will learn how to implement ASP.NET Dynamic Data scaffolding.

Demonstration Steps
To implement ASP.NET Dynamic Data scaffolding, you need to:
1.

Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.

2.

Open Visual Studio 2010.

3.

4.

5.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Open an existing Web site from either D:\Demofiles\M10\VB\Scaffolding or


D:\Demofiles\M10\CS\Scaffolding.

On the File menu of the Start Page - Microsoft Visual Studio window, click Open Web Site.

In the Open Web Site dialog box, in the Folder box, type either
D:\Demofiles\M10\VB\Scaffolding or D:\Demofiles\M10\CS\Scaffolding, and then click
Open.

Build and run the Web site.

On the Build menu of the Scaffolding - Microsoft Visual Studio window, click Build Web Site.

In the Save File As dialog box, click Cancel.

On the Debug menu of the Scaffolding - Microsoft Visual Studio window, click Start Without
Debugging.

Close the Windows Internet Explorer browser.

In the There are no accessible tables. Make sure that at least one data model is registered in
Global. - Windows Internet Explorer window, click the Close button.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

6.

Open Global.asax.

7.

10-13

In Solution Explorer, right-click Global.asax, and then click Open.

Uncomment the following lines of code at the top of the Shared or static RegisterRoutes method,
and modify the uncommented line of code to register the
AdventureWorksLT2008_DataModel.AdventureWorksLT2008_
DataEntities ObjectContext with the model.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorksLT20
08_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables = False})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksLT200
8_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = false
});

In the Global.asax code window, change the following code,


[Visual Basic]
' DefaultModel.RegisterContext(GetType(YourDataContextType), New
ContextConfiguration() With {.ScaffoldAllTables = False})
[Visual C#]
//DefaultModel.RegisterContext(typeof(YourDataContextType), new
ContextConfiguration() { ScaffoldAllTables = false });

to:
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorks
LT2008_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables =
False})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksL
T2008_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = false
});

8.

Build and run the Web site.

On the Build menu of the Scaffolding - Microsoft Visual Studio window, click Rebuild Web Site.

In the Save File As dialog box, click Cancel.

On the Debug menu, click Start Without Debugging.

Note: Explain that the reason the exception is thrown, is that the tables that scaffolding should use have
not been specified, even if you have registered the data context.
9.

Close Internet Explorer.

In the There are no accessible tables. Make sure that at least one data model is registered in
Global. - Windows Internet Explorer window, click the Close button.

10. Modify the uncommented line of code to scaffold all tables.


[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorksLT20
08_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables = True})
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-14

Introduction to Web Development with Microsoft Visual Studio 2010

[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksLT200
8_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = true
});

In the Global.asax code window, change the following code,


[Visual Basic]
' DefaultModel.RegisterContext(GetType(YourDataContextType), New
ContextConfiguration() With {.ScaffoldAllTables = False})
[Visual C#]
//DefaultModel.RegisterContext(typeof(YourDataContextType), new
ContextConfiguration() { ScaffoldAllTables = false });

to:
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorks
LT2008_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksL
T2008_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = true
});

11. Build and run the Web site.

On the Build menu of the Scaffolding - Microsoft Visual Studio window, click Rebuild Web Site.

In the Save File As dialog box, click Cancel.

On the Debug menu, click Start Without Debugging.

12. View the Customers table, and then return to the home page.

In the Dynamic Data Site - Windows Internet Explorer window, under My tables, click
Customers.

In the Customers - Windows Internet Explorer window, under DYNAMIC DATA SITE, click Back
to home page.

13. View the Products table, and then return to the home page.

In the Dynamic Data Site - Windows Internet Explorer window, under My tables, click Products.

In the Products - Windows Internet Explorer window, under DYNAMIC DATA SITE, click Back to
home page.

Note: Notice that now all the tables in the data context are now shown on the Web Site home page.
14. Close Internet Explorer.

In the Dynamic Data Site - Windows Internet Explorer window, click the Close button.

15. Modify the uncommented line of code to not scaffold all tables.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorksLT20
08_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables = False})

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-15

[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksLT200
8_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = false
});

In the Global.asax code window, change the following code,


[Visual Basic]
' DefaultModel.RegisterContext(GetType(YourDataContextType), New
ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
//DefaultModel.RegisterContext(typeof(YourDataContextType), new
ContextConfiguration() { ScaffoldAllTables = true });

to:
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorks
LT2008_DataEntities), New ContextConfiguration() With {.ScaffoldAllTables =
False})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksL
T2008_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = false
});

16. Close the Global.asax file.

In the Global.asax code window, click the Close button.

In the Microsoft Visual Studio message box, click Yes.

17. Add a new class file named Customer to the App_Code folder.

In Solution Explorer, right-click App_Code, and then click Add New Item.

In the middle pane of the Add New Item - D:\Demofiles\M10\VB


\Scaffolding\ or Add New Item - D:\Demofiles\M10\CS\Scaffolding\ dialog box, click Class,
in the Name box, type Customer, and then click Add.

18. Import the System.ComponentModel.DataAnnotations namespace in the Customer class file.


[Visual Basic]
Imports System.ComponentModel.DataAnnotations
[Visual C#]
using System.ComponentModel.DataAnnotations;

In either the App_Code/Customer.vb or App_Code/Customer.cs code window, type the following


code.
[Visual Basic]
Imports System.ComponentModel.DataAnnotations
[Visual C#]
using System.ComponentModel.DataAnnotations;

19. Wrap the Customer class in the AdventureWorksLT2008_DataModel namespace.


[Visual Basic]

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-16

Introduction to Web Development with Microsoft Visual Studio 2010

Namespace AdventureWorksLT2008_DataModel
Public Class Customer
...
End Class
End Namespace
[Visual C#]
namespace AdventureWorksLT2008_DataModel
{
/// <summary>
/// Summary description for Customer
/// </summary>
public class Customer
{
...
}
}

In the App_Code/Customer.vb or App_Code/Customer.cs code window, add a namespace


directive at the beginning and end of the Customer class.
[Visual Basic]
Namespace AdventureWorksLT2008_DataModel
Public Class Customer
...
End Class
End Namespace
[Visual C#]
namespace AdventureWorksLT2008_DataModel
{
/// <summary>
/// Summary description for Customer
/// </summary>
public class Customer
{
...
}
}

20. Apply the Partial or partial keyword to the Customer class.


[Visual Basic]
Partial Public Class Customer
[Visual C#]
public partial class Customer

In the App_Code/Customer.vb or App_Code/Customer.cs code window, apply the Partial or


partial keyword to the Customer class.
[Visual Basic]
Partial Public Class Customer
[Visual C#]
public partial class Customer

21. Remove the default constructor from the Customer class.

In the App_Code/Customer.cs code window, remove the following code.


[Visual C#]
public Customer()
(
//
// TODO: Add Constructor logic here

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-17

//

Note: You only need to remove the default constructor from the Customer class if you are working in
Visual C#.
22. Apply the ScaffoldTable attribute to the Customer class with a value of True/true.

In the App_Code/Customer.vb or App_Code/Customer.cs code window, type the following code


before the Customer class declaration.
[Visual Basic]
<ScaffoldTable(True)>
[Visual C#]
[ScaffoldTable(true)]

23. Build and run the Web site.

On the Build menu of the Scaffolding - Microsoft Visual Studio window, click Rebuild Web Site.

In the Save File As dialog box, click Cancel.

On the Debug menu, click Start Without Debugging.

Note: Explain that now only the Customers table is exposed, because of the scaffolding attribute in the
Customer class.
24. View the Customers table, and then return to the home page.

In the Dynamic Data Site - Windows Internet Explorer window, under My tables, click
Customers.

Note: Notice that all table columns are shown by default.

In the Customers - Windows Internet Explorer window, under DYNAMIC DATA SITE, click Back
to home page.

25. Close all open windows.

In the Dynamic Data Site - Windows Internet Explorer window, click the Close button.

In the Scaffolding - Microsoft Visual Studio window, click the Close button.

Note: If the Microsoft Visual Studio message box displays, click No.
Question: What is the use of ScaffoldTable attribute?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-18

Introduction to Web Development with Microsoft Visual Studio 2010

ASP.NET Dynamic Data Templates

Key Points
ASP.NET Dynamic Data uses generic templates for generating the UI for managing the data at runtime.
The templates consist of page templates and field templates. The templates are used by the Dynamic Data
runtime for creating the pages and user controls that display and manage the data in the data source.
These templates contain data-bound controls, and have various default property settings that are used to
automatically bind the templates to the data source.

Page Templates
You can use the built-in page templates to serve fully functional pages. Page templates include all
database operationssuch as view, insert, edit, and deleteand sorting and paging functions for list
views. In addition, the pages provide built-in data validation that is based on the database schema, and
sorting filters for each foreign key or Boolean field. These templates are generic, because the Web Forms
are not specific to a single database entity, such as a table.
Dynamic Data uses a different page template for each operation, except for the delete operation, which
displays as a link in both List and Details pages. This is because there is no need for a separate page
template for the delete operation, as it only requires a confirmation dialog box. The following are the
built-in page templates.
Template

Description

List view or List.aspx

This page templatewhich is the default template for the view


operationdisplays a list of rows from a database entity in a
GridView control. The DropDownList controls filter the data for
each foreign key or Boolean column, and for sorting and paging
capabilities.

Details view or Details.aspx

This page templatewhich is the default template for the select


operationdisplays a detailed view of a single item in the entity, in

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

Template

10-19

Description
a FormView control.

Edit view or Edit.aspx

This page template, which is the default template for the edit
operation, displays an interface for editing a single item in the
entity in a FormView control.

List Details view or ListDetails.aspx

This page template is a combination of the Insert, List, and Details


templates. It displays a list of rows from a database entity in a
GridView control. It also provides DropDownList controls for
filtering the data for each foreign key or Boolean column, and for
sorting and paging capabilities. A FormView control views a
selected item, and inserts a new item in the entity.

Insert view or Insert.aspx

This page templatewhich is the default template for the insert


operationdisplays an interface for inserting a single item into a
database entity in a FormView control.

Field Templates
You can use a field template for rendering the UI that manages the data in the individual data fields.
Dynamic Data determines the appropriate field template from the data field types in the data model
schema. There are several field templates for managing different data fields. The field templates are
implemented as Web user controls with an .ascx extension.
Dynamic Data reads the database schema to get information about the data types and foreign keys, and
the ASP.NET data controls supplied by Dynamic Data are aware of the database schema. This makes it
easy for you to access and manipulate data. To replace the default rendering of the GridView and
FormView controls, you should manually provide the code for the rendering on each page. Field
templates provide a simpler way to globally change the default rendering of the GridView and
FormView controls.
Dynamic Data uses default field templates to create default rendering for displaying and editing data. The
following are the default field templates that are added to a Dynamic Data Web site.
Template

Description

Boolean.ascx

This field template displays a field of a Boolean data type. It is rendered as a


CheckBox control.

Boolean_Edit.ascx

Use this field template to edit a field of a Boolean data type. It is rendered
as a CheckBox control.

Children.ascx

Use this field template to display a field that has a one-to-many relationship,
and redirect the user to the relationship page. It is rendered as a HyperLink
control.

Children_Insert.ascx

This field template prevents navigation to a page that displays child items
while a parent item is being created.

DateTime.ascx

Use this field template to display DateTime data type as literal text.

DateTime_Edit.ascx

Use this field template to edit DateTime data in a TextBox control.


However, if the field in the entity disallows null values, or if the field is
required, this template also renders a RequiredFieldValidator control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-20

Introduction to Web Development with Microsoft Visual Studio 2010

Template

Description

Decimal_Edit.ascx

Use this field template to edit decimal values in a TextBox control. The
template also renders a CompareValidator control that verifies conversion
to the Decimal data type. If the field in the entity disallows null values, or
if the field is required, this template also renders a RequiredFieldValidator
control. If the field has a range attribute, the template also renders a
RangeValidator control.

EmailAddress.ascx

Use this field template to display an email address that is rendered as a


hyperlink.

Enumeration.ascx

Use this field template to display enumeration values using a Literal control.

Enumeration_Edit.ascx

This field template allows users to select from a list of enumeration values by
using a DropDownList control.

ForeignKey.ascx

Use this field template to display a field that has a many-to-one relationship,
and to redirect the user to the relationship page. The field template renders
as a HyperLink control.

ForeignKey_Edit.ascx

Use this field template to edit a field that has a many-to-one relationship,
and to render a DropDownList control that enables users to select foreign
keys that are exposed by the data model.

Integer_Edit.ascx

Use this field template to edit integer values in a TextBox control. The
template also renders a CompareValidator control that verifies conversion
to an integer. If the field in the entity disallows null values, or if the field is
required, this template also renders a RequiredFieldValidator control. If the
field has a range attribute, the template also renders a RangeValidator
control.

ManyToMany.ascx

Use this field template to display and edit many-to-many data fields (ADO
Entity Data Models only).

ManyToMany_Edit.ascx

Use this field template to edit database fields that have a many-to-many
relation with another table.

MultilineText_Edit.ascx

Use this template to edit database fields that are marked as text blockssuch
as TEXT, NTEXT, VARCHAR(MAX), NVARCHAR(MAX) data types in
Microsoft SQL Serverin a TextBox control, if the TextMode property is
set to MultiLine. If the field in the entity disallows null values, or if the field is
required, this template also renders a RequiredFieldValidator control. If a
RegularExpression attribute is added to the data model, the template also
renders a RegularExpressionValidator control.

Text.ascx

Use this field template to display fields of type String, Decimal, Double, and
integer types as literal text.

Text_Edit.ascx

Use this field template to edit text values in a TextBox control, if the
TextMode property is set to SingleLine. If the field in the entity disallows
null values, or if the field is required, this template also renders a
RequiredFieldValidator control. If the field in the database has a length
associated with it, the MaxLength property of the TextBox control is set
accordingly.

Url.ascx

Use this field template to display a URL that is rendered as a hyperlink.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-21

ASP.NET Dynamic Data Routing

Key Points
Dynamic Data uses ASP.NET routing to match and handle URL requests. The routes are defined in the
global application file.
Scaffolding infers the view and the entity that a user wants to view, from the URL requested. The benefit
of using the routing mechanism is that the URL requested does not have to match the physical path in the
application, but it can allow both physical files and dynamically-generated pages.
You can modify the URL routing to use any page template as the default page for a specific operation, or
to use different page templates for different purposes.
You can customize the routes to specify different page templates. You can also customize them to display
different URLs, remove the file extension (aspx), or pass parameters by using routes, instead of query
string values.
The following codewhich is part of the default Global.asax filespecifies the default route to use, where
a template is specified for each action on any table in the data model.
[Visual Basic]
routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With {
.Constraints = New RouteValueDictionary(New With {.Action =
"List|Details|Edit|Insert"}),
.Model = DefaultModel})
[Visual C#]
routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert" }),
Model = DefaultModel
});

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-22

Introduction to Web Development with Microsoft Visual Studio 2010

The following code exampleswhich are part of the default Global.asax file that is commented out by
defaultspecifies the routes to use only one page template for all operations.
[Visual Basic]
routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With {
.Action = PageAction.List,
.ViewName = "ListDetails",
.Model = DefaultModel})
routes.Add(New DynamicDataRoute("{table}/ListDetails.aspx") With {
.Action = PageAction.Details,
.ViewName = "ListDetails",
.Model = DefaultModel})
[Visual C#]
routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") {
Action = PageAction.List,
ViewName = "ListDetails",
Model = DefaultModel
});
routes.Add(new DynamicDataRoute("{table}/ListDetails.aspx") {
Action = PageAction.Details,
ViewName = "ListDetails",
Model = DefaultModel
});

The first route enables all actions in the page for a given table by using the ListDetails page template. The
second route enables a page to navigate to the details of a recordsuch as navigating to a relationship
table when you have a foreign key field.
The routes are analyzed in the order they appear in the code. You need to first define the specific routes,
and then define the generic ones, just as you declare the exception type order when you wrap code in a
Try/try statement.
You can specify specific routes for specific tables, by specifying a page template that is different from the
one used by the rest of the tables. The following examples show how to specify a different page template
for the Customers table of the CustomerManagement database, and then define a generic page template
for the other tables of the database.
[Visual Basic]
routes.Add(New DynamicDataRoute("Customers/{action}.aspx") With {
.ViewName = "ListDetails",
.Table = "Customers",
.Model = model})
routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With {
.Constraints = New RouteValueDictionary(
New With {.Action = "List|Details|Edit|Insert"}),
.Model = model})
[Visual C#]
routes.Add(new DynamicDataRoute("Customers/{action}.aspx")
{
ViewName = "ListDetails",
Table = "Customers",
Model = model
});

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-23

routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
{
Constraints = new RouteValueDictionary(
new { action = "List|Details|Edit|Insert" }),
Model = model
});

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-24

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson 2

Applying ASP.NET Dynamic Data

You can use the ASP.NET Dynamic Data framework in a Web site in various ways. You can create a new
Web site based on the ASP.NET Dynamic Data Web Site template in Visual Studio, or you can add
Dynamic Data features to an existing Web site. However, the possibilities do not stop there, because you
can customize or create new page templates and field templates to suit your needs.
In this lesson, you will learn about applying the ASP.NET Dynamic Data Framework to a new Web site and
to an existing Web site. You will also learn how to customize a field template, and how to add dynamic
behavior to a data-bound control.

Lesson Objectives
After completing this lesson, you will be able to:

Explain how to create an ASP.NET Dynamic Data Web site.

Add ASP.NET Dynamic Data to an existing Web site.

Add dynamic behavior to ASP.NET data-bound controls.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-25

Demonstration: How to Create an ASP.NET Dynamic Data Web Site

Key Points
Dynamic Data enables you to create a data-driven Web site with minimal or no code. An important
feature of Dynamic Data is the scaffolding mechanism. When you enable the scaffolding mechanism in a
Dynamic Data Web site, ASP.NET analyzes your data model and dynamically generates Web pages for
each table. These auto-generated Web pages provide display, insert, delete, and edit capabilities for each
table. Because Dynamic Data allows you to create a data-driven Web site with minimal or no code, it can
be used whenever you need to manage data from a database, by using a Web-based UI.
1.

2.

3.

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.

In the User Account Control dialog box, in the text box, type Pa$$w0rd, and then click Yes.

Create a Web site by using the New Web Site dialog box.

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, click ASP.NET Dynamic Data Entities Web Site.

In the Web location list, click File System, and in the text box,
type either D:\Demofiles\M10\VB\DDWebSite or D:\Demofiles\M10\CS\DDWebSite, and
then click OK.

Add an existing SQL Server 2008 Express Edition database to the Web site.

In Solution Explorer, right-click App_Data, and then click Add Existing Item.

In the middle pane of the Add Existing Item D:\Demofiles\M10


\VB\DDWebSite\ or Add Existing Item D:\Demofiles\M10\CS
\DDWebSite\ dialog box, in the File name box, type
D:\Demofiles\M10\AdventureWorksLT2008_Data.mdf, and then click Add.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-26

Introduction to Web Development with Microsoft Visual Studio 2010

4.

Add an ADO.NET Entity Data Model named AdventureWorks.edmx to the Web site.

In Solution Explorer, right-click D:\...\DDWebSite\, and then click Add New Item.

In the middle pane of the Add New Item D:\Demofiles\M10


\VB\DDWebSite\ or Add New Item D:\Demofiles\M10\CS
\DDWebSite\dialog box, in the middle pane, click ADO.NET Entity Data Model.

In the Name box, type AdventureWorks.edmx, and then click Add.

In the Microsoft Visual Studio message box, click Yes.

Note: Point out that in a Web site, code files that are not directly related to a Web Form or user control
must be placed in the App_Code folder.

In the Entity data Model Wizard, click Generate from database, and then click Next.

In the Entity data Model Wizard, on the Choose Your Data Connection page, in the Which
data connection should your application use to connect to the database? list, click
AdventureWorksLT2008_Data.mdf, and then click Next.

In the Entity data Model Wizard, on the Choose Your Database Objects page, in the Which
database objects do you want to include in your model? pane, expand Tables, select Tables,
remove the selection from BuildVersion, click Pluralize or singularize generated object
names, and then click Finish.

Note: Point out that each table is represented as an entity that is named as the corresponding database
table, but in singular.
5.

6.

Save and close AdventureWorks.edmx.

On the File menu of Visual Studio 2010, click Save App_Code


/AdventureWorks.edmx.

In the App_Code/AdventureWorks.edmx window, click the Close button.

Open the Global.asax file, and add context registration to the RegisterRoutes procedure.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorksLT20
08_DataEntities),
New ContextConfiguration() With {.ScaffoldAllTables = True})
[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksLT200
8_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = true
});

In Solution Explorer, right-click Global.asax, and then click Open.

In the Global.asax window, add the following code at the top of to the RegisterRoutes
procedure.
[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008_DataModel.AdventureWorks
LT2008_DataEntities),
New ContextConfiguration() With {.ScaffoldAllTables = True})

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-27

[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008_DataModel.AdventureWorksL
T2008_DataEntities), new ContextConfiguration()
{
ScaffoldAllTables = true
});

Note: Point out that this will register the Entity Data model object context for use by the Dynamic Data
field, and enable the automatic scaffolding of the data model.
7.

8.

Save and close the Global.asax file.

On the File menu of Visual Studio 2010, click Save Global.asax.

In the Global.asax window, click the Close button.

Build and run the Web site.

On the Debug menu of Visual Studio 2010, click Start Without Debugging.

Note: The page that displays in the browser displays a list of the tables that you added to the data model.
9.

Test the Web site for the Dynamic Data functionality, and view some of the pages by using the pager
control.

In the Dynamic Data Site Windows Internet Explorer window, click Customers.

Note: The page displays the List view that contains the data from the Customers table.

In the Page box, type 20, and then press ENTER.

In the Customers - Windows Internet Explorer window, click Delete for a specific customer.

In the Message from webpage message box, click Cancel.

In the Customers - Windows Internet Explorer window, to the left of a customer, click Details.

Note: The page displays the Details view, which contains the data for the row selected from the
Customers table.

In the Customers - Windows Internet Explorer window, click Show all items.

In the Customers - Windows Internet Explorer window, click FirstName.

In the Customers - Windows Internet Explorer window, in the second row from the top, under
CustomerAddresses, click View CustomerAddresses.

Note: The page displays the List view, which contains the customer address data.

In the Customer list, click All.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click
Insert new item to create a new customer.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-28

Introduction to Web Development with Microsoft Visual Studio 2010

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click
Insert, view the smart validation that has been added to the required fields, and then click
Cancel.

Note: The page displays the List view, which contains the data from the CustomerAddresses table. This is
the default view, and the one you are returned to, after cancelling.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click Edit
to modify a customer address.

Note: The page displays the Edit view, which contains the data for the CustomerAddresses tables selected
row.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the page, click
Cancel to cancel the edit operation.

In the CustomerAddresses - Windows Internet Explorer window, click the Close button.

In the DDWebSite - Microsoft Visual Studio window, click the Close button.

Question: What is the use of the AdventureWorks.edmx file?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-29

Adding ASP.NET Dynamic Data to an Existing Web Site

Key Points
When you create new Web sites and Web applications based on the corresponding Visual Studio 2010
templates, you might also want to add Dynamic Data to an existing Web site. To do this, create a sample
Dynamic Data Web site, then, copy the markup and code from the sample Web site to your existing Web
site.

Add Dynamic Data Default Files and Folders


You can use the default Dynamic Data templates and images, and then copy these to an existing Dynamic
Data Web site. To add Dynamic Data default files and folders, you need to perform the following steps:
1.

Add the DynamicData folder and default Dynamic Data content to the Web site by copying the
DynamicData folder from the root folder of the sample Web site, to the root folder of the new Web
site.

2.

In Solution Explorer, refresh the Web site content to ensure the addition of the DynamicData folder.

Add a Master Page


Because the Dynamic Data page templates are content pages, you need to add a master page or modify
an existing master page. To add a master page, you need to perform the following steps:
1.

Add a new master page, if necessary.

2.

The Dynamic Data page templates refer to the Site.master master template. You must rename your
master page by using this name, or you must modify each page template in the
DynamicData\PageTemplates folder, so that they refer to the correct master page.

Add a ScriptManager Control to the Master Page


The Dynamic Data page templates uses Ajax controls, including the UpdatePanel control. Therefore, you
must add a ScriptManager control to the master page, or modify the existing master page, if necessary.
Complete the following steps to add a ScriptManager control to the master page:

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-30

Introduction to Web Development with Microsoft Visual Studio 2010

1.

Open the master page.

2.

If necessary, add a ScriptManager control by dragging it from the Toolbox, or by inserting the
following markup.
<asp:ScriptManager ID="ScriptManager1" runat="server" />

The name of the ScriptManager control should be set to ScriptManager1, because there is a
ScriptManagerProxy control in each of the page templates that refers to this control. Alternatively,
you can modify each of the templates to refer to the name that you provide for the
ScriptManagerProxy control.
3.

Save and close the master page.

Add a Data Model


The Dynamic Data feature is based on data, and currently Visual Studio 2010 supports both the LINQ to
SQL data model, and the Entity Framework data model. To use the LINQ to SQL data model, you must
add a new LINQ to SQL Classes project item.
1.

Add a new LINQ to SQL Classes project item.

2.

Drag tables from a data connection in Server Explorer, to the Entities pane of the Object Relational
Designer.

3.

Save and close the .dbml file.

Add a Global Application Class File


Dynamic Data must register the default routes for the various views, and register the data model with the
MetaModel at application startup. You need to add a new Global Application class or modify an existing
Global Application Class. Complete the following steps to add or modify a Global Application Class.
1.

Add a Global Application Class project item, if necessary.

2.

Import the System.Web.DynamicData namespace in the Global.asax file.

3.

In the Global.asax file, create a public Shared/static procedure named Register, which takes a single
parameter named routes, of type RouteCollection, by adding the following code to the Global.asax
file.
[Visual Basic]
Public Shared Sub Register(ByVal routes As RouteCollection)
End Sub
[Visual C#]
public static void Register(RouteCollection routes)
{
}

4.

In the Global.asax file, in the Application_Start method, call the new Register procedure by passing
RouteTable.Routes as the only parameter.
[Visual Basic]
Register(RouteTable.Routes)
[Visual C#]
Register(RouteTable.Routes);

5.

In the Global.asax file, at the top of the script block, create and initialize a private, shared/static
instance of the System.Web.DynamicData.MetaModel class.
[Visual Basic]
Private Shared s_defaultModel As New MetaModel

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-31

[Visual C#]
private static MetaModel s_defaultModel = new MetaModel();

6.

In the Global.asax file, add a property named DefaultModel, for accessing the private shared/static
instance of the System.Web.DynamicData.MetaModel class.
[Visual Basic]
Public Shared ReadOnly Property DefaultModel() As MetaModel
Get
Return s_defaultModel
End Get
End Property
[Visual C#]
public static MetaModel DefaultModel {
get {
return s_defaultModel;
}
}

7.

In the Register procedure, register the DataContext or ObjectContext class with scaffolding
disabled for all tables, by using the RegisterContext method of the MetaModel class.
[Visual Basic]
DefaultModel.RegisterContext(GetType(MyContext),
new ContextConfiguration() With
{.ScaffoldAllTables = False})
[Visual C#]
DefaultModel.RegisterContext(typeof(MyContext),
new ContextConfiguration()
{
ScaffoldAllTables = false
});

8.

Add an Import directive to the Global Application Class. Add the Import directive after the
Application directive, with the Namespace attribute set to System.Web.Routing.

9.

In the Register procedure, add a generic route of type DynamicDataRoute for the List, Details,
Edit, and Insert actions in that order. Have the route redirect to the page template of the same
name, prefixed in the URL with the table name. Add the route by using the Add method of the
passed routes parameter, by appending the following code to the Register procedure.
[Visual Basic]
routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With { _
.Constraints = New RouteValueDictionary( _
New With {.Action = "List|Details|Edit|Insert"}), _
.Model = DefaultModel})
[Visual C#]
routes.Add(new DynamicDataRoute("{table}/{action}.aspx")
{
Constraints = new RouteValueDictionary(
new
{
action = "List|Details|Edit|Insert"
}),
Model = DefaultModel
});
}

10. Save and close the Global Application Class.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-32

Introduction to Web Development with Microsoft Visual Studio 2010

Adding Dynamic Behavior to ASP.NET Data-Bound Controls

Key Points
ASP.NET Dynamic Data contains some classes that you can use to add dynamic behavior to the ASP.NET
4.0 data-bound controls. These classes, which include DynamicDataManager, DynamicControl, and
DynamicField, are grouped in the System.Web.DynamicData namespace.
You can add ASP.NET Dynamic Data functionality to a FormView or a GridView control by using the
DynamicField field in the designer. A DynamicDataManager control must be present on the Web Form
or user control to add DynamicField objects to the data-bound control by using the designer.

To add DynamicField objects to a data-bound control


To add DynamicField objects to a data-bound controlsuch as the FormView or GridView controlby
using the Web Form designer, you need to perform the following steps.
1.

Open the Web Form in the Design view.

2.

In the Toolbox, expand the Dynamic Data group, and drag a DynamicDataManager control to the
top of the Web Form.

3.

Right-click the data-bound control, and then click Show Smart Tag.

4.

In the Smart Tag panel, click Edit Columns.

5.

In the Fields dialog box, clear the Auto-generate fields check box.

6.

In the Available fields list, click DynamicField, and then click Add.

7.

In the Field properties list, set the DataField property to the name of the data column to which you
want to bind the dynamic field.

Note: You need to repeat steps 6 and 7 for each data field that you want to display.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-33

You can also use the DynamicControl control in a TemplateField field of a FormView or a GridView
control by following the same procedure that you use to create ASP.NET Dynamic Data in template-based
data-bound controls.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-34

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson 3

Customizing ASP.NET Dynamic Data Applications

While the ASP.NET Dynamic Data framework provides several built-in page templates and field templates,
you might want to customize the views, the field controls, or the scaffolding. For example, you may want
to create field templates that render a UI for displaying and editing telephone numbers or e-mail
addresses into a certain format.
In this lesson, you will learn how to customize or create new page templates, customize or create new
field templates, and customize the scaffolding and routing of an ASP.NET Dynamic Data Web site.

Lesson Objectives
After completing this lesson, you will be able to:

Create a Dynamic Data page template.

Explain how to create a Dynamic Data field template.

Customize Dynamic Data scaffolding.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-35

Creating a Dynamic Data Page Template

Key Points
Dynamic Data enables you to customize the templates by customizing the built-in page templates, and by
customizing the layout for a particular table. The Dynamic Data page templates in the
DynamicData\PageTemplates folder are generic, and are used for all entities in your data model, unless
you create a custom page template, or customize the scaffolding.
If you want to customize one or more of the page templates for all entities in your data model, you can
modify the page templates in the DynamicData
\PageTemplates folder. The page templates are content pages, and designers or developers may need to
customize them. The changes that you make in this location affect the appearance and behavior of the
generated pages that are using the scaffolding mechanism across the Web application. You can also
choose to add new page templates in this folder, and then modify the scaffolding to use the new
template for one or more actions. However, if you want to create a specific view for a single entity in your
data model, you can use a custom page template. To customize the layout for an individual entity by
using a custom page template, you need to perform the following steps:
1.

Open your ASP.NET Dynamic Data Web site in Visual Studio 2010.

2.

In Solution Explorer, expand the DynamicData folder, and create a subfolder in the CustomPages
folder.

3.

Name the new folder the same as the entity in your data context, but use a plural ending as the
folder name for the Order entityfor example, Orders.

4.

Create a new content page from scratch, or simply copy an existing page template from the
DynamicData\PageTemplates folder to the new subfolder.

5.

Customize the page template as you see fit, and save your changes.

6.

Test your application and the new page template by performing the action registered with the view
or page template.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-36

Introduction to Web Development with Microsoft Visual Studio 2010

Note: If the subfolder name for a custom page template does not match an entity name plus the plural
ending, Dynamic Data cannot locate the page templates, and will use the generic one in the
DynamicData\PageTemplates folder instead.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-37

Demonstration: How to Create a Dynamic Data Field Template

Key Points
In this demonstration, you will learn how to create a Dynamic Data field template.

Demonstration Steps
To create field templates to render the UI for displaying and editing DateTime data fields, you need to
perform the following steps:
1.

Open Visual Studio 2010.

2.

3.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Open the Scaffolding folder from either D:\Demofiles\M10\VB or D:\Demofiles\M10\CS.

On the File menu of Visual Studio 2010, click Open Web Site.

In the Open Web Site dialog box, in the Folder name, type either
D:\Demofiles\M10\VB\Scaffolding or D:\Demofiles\M10\CS\Scaffolding, and then click
Open.

Add a new Dynamic Data field named DateCalendar.ascx to the DynamicData\FieldTemplates


folder.

In Solution Explorer, expand DynamicData, right-click FieldTemplates, and then click Add New
Item.

In the left pane of the Add New Item D:\Demofiles\M10


\VB\Scaffolding\ or Add New Item D:\Demofiles\M10\CS
\Scaffolding\ dialog box, click either Visual Basic or Visual C#.

In the middle pane, click Dynamic Data Field, in the Name box, type DateCalendar.ascx, and
then click Add.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-38

Introduction to Web Development with Microsoft Visual Studio 2010

Note: The code must be placed in a code-behind file.


Note: Notice that the two dynamic data field templates named DateCalendar.ascx and
DateCalendar_Edit.ascx are created. The DateCalendar.ascx user control renders the UI for displaying the
DateTime data fields, while the DateCalendar_Edit.ascx user control renders the UI for editing the
DateTime data fields.
4.

In the DateCalendar.ascx user control, remove the Text attribute of the Literal control with the
value FieldValueString.

5.

6.

In the DynamicData/FieldTemplates/DateCalendar.ascx window, delete the Text attribute value


FieldValueString.

Save and close the DateCalendar.ascx user control file.

In the Scaffolding Microsoft Visual Studio window, on the File menu, click Save
DynamicData/FieldTemplates/DateCalendar.ascx.

In the DynamicData/FieldTemplates/DateCalendar.ascx window, click the Close button.

Open either the DateCalendar.ascx.vb or DateCalendar.ascx.cs code-behind file.

7.

In Solution Explorer, expand DateCalendar.ascx, right-click either DateCalendar.ascx.vb or


DateCalendar.ascx.cs, and then click Open.

Use the following code to override the user control OnDataBinding method to format the display of
the DateTime value by excluding the time.

Note: The value of the field is available in the FieldValue property.


[Visual Basic]
Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs)
MyBase.OnDataBinding(e)
Dim shortDate As String = String.Empty
If FieldValue IsNot Nothing Then
Dim dt As DateTime = Format(CType(FieldValue, DateTime), "d")
shortDate = dt.ToShortDateString()
End If
Literal1.Text = shortDate
End Sub
[Visual C#]
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
string shortDate = string.Empty;
if (FieldValue != null)
{
DateTime dt = (DateTime) FieldValue;
shortDate = dt.ToShortDateString();
}
}

Literal1.Text = shortDate;

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-39

In either the DateCalendar.ascx.vb or DateCalendar.ascx.cs window, add the following code in the
DynamicData_FieldTemplates_DateCalendar class.
[Visual Basic]
Protected Overloads Overrides Sub OnDataBinding(ByVal e As EventArgs)
MyBase.OnDataBinding(e)
Dim shortDate As String = String.Empty
If FieldValue IsNot Nothing Then
Dim dt As DateTime = Format(CType(FieldValue, DateTime), "d")
shortDate = dt.ToShortDateString()
End If
Literal1.Text = shortDate
End Sub
[Visual C#]
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
string shortDate = string.Empty;
if (FieldValue != null)
{
DateTime dt = (DateTime) FieldValue;
shortDate = dt.ToShortDateString();
}
}

8.

9.

Literal1.Text = shortDate;

Save and close the DateCalendar.ascx.vb or DateCalendar.ascx.cs code-behind file.

In the Scaffolding Microsoft Visual Studio window, on the File menu, click either Save
DynamicData/FieldTemplates/DateCalendar.ascx.vb or Save
DynamicData/FieldTemplates/DateCalendar.ascx.cs.

In the DynamicData/FieldTemplates/DateCalendar.ascx.vb or
DynamicData/FieldTemplates/DateCalendar.ascx.cs window, click the Close button.

Open the DateCalendar_Edit.ascx user control, and ensure that the AutoEventWireup is set to true.

In Solution Explorer, right-click DateCalendar_Edit.ascx, and then click Open.

In the DynamicData/Field...Calendar_Edit.ascx window, in the Control directive, ensure that the


AutoEventWireup attribute is set to true, by placing the cursor inside the Control directive, and
viewing the Properties Window in Visual Studio 2010.

10. Replace the FieldValueEditString expression of the Text attribute with the custom GetDateString
method.

In the DynamicData/Field...Calendar_Edit.ascx window, change the FieldValueEditString value of


the Text attribute in the Textbox control, with the value GetDateString.
<asp:TextBox ID="TextBox1" runat="server" Text='<%# GetDateString() %>' >
</asp:TextBox>

11. Append the following markup to the DateCalendar_Edit.ascx user control, to define the Calendar
control that renders the UI to enable another way of editing dates.
[Visual Basic]
<asp:Calendar ID="Calendar1" runat="server"
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-40

Introduction to Web Development with Microsoft Visual Studio 2010

VisibleDate='<%# If(FieldValue, DateTime.Now) %>'


SelectedDate='<%# If(FieldValue, DateTime.Now) %>'
OnSelectionChanged="Calendar1_SelectionChanged" />
[Visual C#]
<asp:Calendar ID="Calendar1" runat="server"
VisibleDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
SelectedDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
OnSelectionChanged="Calendar1_SelectionChanged" />

In the DynamicData/Field...Calendar_Edit.ascx window, append the following markup.


[Visual Basic]
<asp:Calendar ID="Calendar1" runat="server"
VisibleDate='<%# If(FieldValue, DateTime.Now) %>'
SelectedDate='<%# If(FieldValue, DateTime.Now) %>'
OnSelectionChanged="Calendar1_SelectionChanged" />
[Visual C#]
<asp:Calendar ID="Calendar1" runat="server"
VisibleDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
SelectedDate='<%# (FieldValue != null) ? FieldValue : DateTime.Now %>'
OnSelectionChanged="Calendar1_SelectionChanged" />

12. Save and close DateCalendar_Edit.ascx user control.

In the Scaffolding Microsoft Visual Studio window, on the File menu, click Save
DynamicData/FieldTemplates/DateCalendar_Edit.ascx.

In the DynamicData/FieldTemplates/DateCalendar_Edit.ascx window, click the Close button.

13. Open either the DateCalendar_Edit.ascx.vb or DateCalendar_Edit.ascx.cs code-behind file. Add a


GetDateString method. In the method, process the user's input as it is entered, by using the TextBox
control. The method formats the date by using a short date format that excludes the time by using
the following code.
[Visual Basic]
Protected Function GetDateString() As String
If FieldValue <> Nothing Then
Dim dt As DateTime = Format(CType(FieldValue, DateTime), "d")
Else

Return dt.ToShortDateString()

Return String.Empty
End If
End Function
[Visual C#]
protected string GetDateString()
{
if (FieldValue != null)
{
DateTime dt = (DateTime)FieldValue;
}
else
}

return dt.ToShortDateString();
return string.Empty;

In either the DynamicData/Field...Calendar_Edit.ascx.vb or


DynamicData/Field...Calendar_Edit.ascx.cs window, append the following code in the
DynamicData_FieldTemplates_DateCalendar class.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-41

[Visual Basic]
Protected Function GetDateString() As String
If FieldValue <> Nothing Then
Dim dt As DateTime = Format(CType(FieldValue, DateTime), "d")
Else

Return dt.ToShortDateString()

Return String.Empty
End If
End Function
[Visual C#]
protected string GetDateString()
{
if (FieldValue != null)
{
DateTime dt = (DateTime)FieldValue;
}
else
}

return dt.ToShortDateString();
return string.Empty;

14. Add a handler for the SelectionChanged event of the Calendar control. In the handler, set the Text
property of the TextBox control to a formatted version of the selected date from the calendar.
Note: This displays the current selection of the user in the text box by using the following code:
[Visual Basic]
Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
' Display value using the short date format.
TextBox1.Text = Calendar1.SelectedDate.ToString("d")
End Sub
[Visual C#]
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
// Display value using the short date format.
TextBox1.Text = Calendar1.SelectedDate.ToString("d");
}

In either the DynamicData/Field...Calendar_Edit.ascx.vb or


DynamicData/Field...Calendar_Edit.ascx.cs window, append the following code in the
DynamicData_FieldTemplates_DateCalendar class.
[Visual Basic]
Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As
EventArgs)
' Display value using the short date format.
TextBox1.Text = Calendar1.SelectedDate.ToString("d")
End Sub
[Visual C#]
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
// Display value using the short date format.
TextBox1.Text = Calendar1.SelectedDate.ToString("d");
}

15. Save and close the DateCalendar_Edit.ascx.vb or DateCalendar_Edit.ascx.cs code-behind file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-42

Introduction to Web Development with Microsoft Visual Studio 2010

In the Scaffolding Microsoft Visual Studio window, on the File menu, click either
Save DynamicData/FieldTemplates/DateCalendar_Edit.ascx.vb or
Save DynamicData/FieldTemplates/DateCalendar_Edit.ascx.cs.

In the Scaffolding Microsoft Visual Studio window, on the File menu, click the Close button.

You have now created the field templates that render the UI for displaying and editing DateTime data
field types. The field templates instruct Dynamic Data to apply the appropriate formatting and validation.
If validation fails, the field templates generate appropriate error messages.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-43

Customizing Dynamic Data Scaffolding

Key Points
Dynamic Data scaffolding increases the power and functionality of the existing ASP.NET page framework
by dynamically displaying pages that are based on the data model, but without the need for a physical
page. This is because Dynamic Data uses URL routing to match and handle requests. The scaffolding
mechanism infers the view and the table that a user wants to view from the URL requested. The benefit of
using the routing mechanism is that the URL requested does not have to match the physical path in the
application.
By default, the scaffolding mechanism is turned off, but you can use the following methods to enable the
scaffolding:

Enabling as part of the data context registration

By using the ScaffoldTableAttribute attribute

By using the ScaffoldColumnAttribute attribute

You must register the data context that will use the Dynamic Data features, even if you do not plan to use
the scaffolding mechanism. This registration is made in the Global.asax file by using the RegisterContext
method, which accepts a ContextConfiguration object as a parameter. To enable the scaffolding
mechanism while registering the data context, you need to set the ScaffoldAllTables property of the
ContextConfiguration object to true. This will enable the scaffolding mechanism for the whole data
model. In other words, it will expose all the tables in the data model for display, edit, insert, and delete
capabilities. If you want to hide some tables from the scaffolding mechanism, you can use the
ScaffoldTableAttribute attribute.
The following code examples show how you can enable the scaffolding mechanism for all the tables in the
data model, while registering the MyContext data context.
[Visual Basic]
DefaultModel.RegisterContext(GetType(MyContext), _

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-44

Introduction to Web Development with Microsoft Visual Studio 2010

New ContextConfiguration() With {.ScaffoldAllTables = True})


[Visual C#]
DefaultModel.RegisterContext(typeof(MyContext),
new ContextConfiguration() { ScaffoldAllTables = true });

If you want more control on the tables that are exposed, you can use the ScaffoldTableAttribute
attribute to enable or disable the scaffolding mechanism for a given table. Instead of exposing the entire
data model and hiding the tables that do not have to be exposed, you can expose only the tables that are
required by the application. To apply the ScaffoldTableAttribute attribute, you must create a partial
class that has the same name of the entity class in the data model, and then apply the attribute to the
partial class. The following code examples show how you can enable the scaffolding mechanism for an
individual table.
[Visual Basic]
Imports System.ComponentModel.DataAnnotations
<ScaffoldTable(True)>
Partial Public Class Order
End Class
[Visual C#]
using System.ComponentModel.DataAnnotations;
[ScaffoldTable(true)]
public partial class Order
{
}

If you want more control on the data fields that are exposed, you can use the ScaffoldColumnAttribute
attribute to enable or disable the scaffolding mechanism for a given data field.
The following are some of the rules that apply to the column or field scaffolding:

By default, not all data fields are displayed by Dynamic Data.

If a UIHintAttribute attribute is applied to a data field, the data field displays. This rule overrides any
other rules that follow.

If a data field is a foreign-key field, the data field does not display. This occurs because Dynamic Data
handles foreign key fields in a different manner, and will not display the foreign key field value.

If the data field is automatically generated in the database, the data field does not display, because
this type of field may not contain relevant information. Ensure that you apply the UIHintAttribute
attribute to the data field, if the data field must be displayed.

If the value of the IsCustomProperty property is set to true, the data field does not display.

To apply the ScaffoldColumnAttribute attribute, you must create an associated metadata class where
you can apply the ScaffoldColumnAttribute attribute to the data field. You must also create a partial
class that has the same name of the entity class in the data model. Then, you must associate these two
classes by applying the MetadataTypeAttribute attribute to the partial class.
The following code examples show how to hide specific data fields, ID and Addresses, from the scaffolding
mechanism.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-45

[Visual Basic]
Imports System.ComponentModel.DataAnnotations
<MetadataType(GetType(CustomerMetadata))>
Partial Public Class Customer
End Class
Public Class CustomerMetadata
<ScaffoldColumn(False)>
Public ID As Object
<ScaffoldColumn(False)>
Public Address As Object
End Class
[Visual C#]
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
}
public class CustomerMetadata
{
[ScaffoldColumn(false)]
public object ID;

[ScaffoldColumn(false)]
public object Address;

Customizing the Routes


Dynamic Data uses ASP.NET routing to match and handle URL requests. The routes are defined in the
Global.asax file. By default, Dynamic Data uses a different page template for each operation, such as
display, select, edit, or insert.
You can customize the routes to display different URLs, but you can also use them to specify different
page templates, remove the file extension from the URL, or even pass parameters by using routes, instead
of query string values.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-46

Introduction to Web Development with Microsoft Visual Studio 2010

Lab: Managing Data by Using ASP.NET Dynamic Data

Note: You can perform tasks in this lab by using either 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 add Dynamic Data to an existing Web site, and then register LINQ to Entities by using
Dynamic Data. In addition, you will add metadata to the data model, and test the Dynamic Data
functionality in the Web site.

Objectives
After completing this lab, you will be able to:

Add dynamic data to an existing Web site.

Register Entity Framework with Dynamic Data.

Test the Dynamic Data functionality.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-47

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.
The sales team of the organization wants to use the ASP.NET application to display and modify data
contained in the CustomerManagement database. In addition, the sales team wants to add new records in
the database by using Web Forms. To facilitate this, you need to add dynamic data to the Web site, and
register the existing LINQ to Entities ObjectContext by using dynamic data.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-48

Introduction to Web Development with Microsoft Visual Studio 2010

Section 1: Visual Basic


Exercise 1: Adding Dynamic Data to an Existing Web Site
The main tasks for this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Create a sample dynamic data Web site.

3.

Add the dynamic data default files and folders.

4.

Add the ScriptManager control to the master page.

5.

Update dynamic data page templates to use an existing master page.

6.

Copy dynamic data styles.

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\M10\VB folder.

Task 2: Create a sample dynamic data Web site

Open a second instance of Visual Studio 2010.

Create a new ASP.NET Dynamic Data Web site in the D:\Labfiles\Starter\M10\VB\SampleDDWebSite


folder.

Close the second instance of Visual Studio 2010.

Task 3: Add the dynamic data default files and folders

Add the DynamicData folder and default dynamic data content from the SampleDDWebSite Web
site to the CustomerManagement Web site by copying the DynamicData folder from the path,
D:\Labfiles\Starter\M10
\VB\SampleDDWebSite\DynamicData.

In Solution Explorer, refresh the Web site content to ensure the addition of the DynamicData folder.

Task 4: Add the ScriptManager control to the master page

Open the Site.master master page in Source view.

Add a ScriptManager control before the div element with a value of content for the class attribute
by adding an asp:ScriptManager element with an ID attribute value of MainScriptManager.

Save the Site.master master page.

Close the Site.master master page.

Task 5: Update dynamic data page templates to use an existing master page

Open the Find and Replace dialog box.

Replace the ContentPlaceHolder1 name that is referenced in the Dynamic Data Page Templates,
with the name of the ContentPlaceHolder control that is used in the existing master page,
MainContentPlaceHolder.

In all of the opened and modified Dynamic Data page templatesDetails.aspx, Edit.aspx,
Insert.aspx, List.aspx, and ListDetails.aspxremove the Content control with an ID attribute value
of headContent.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-49

Save and close all modified files.

Task 6: Copy dynamic data styles

Copy the content of the D:\Labfiles\Starter\M10\VB


\SampleDDWebSite\Site.css stylesheet.

Add the copied content to the existing Styles\Site.css stylesheet.

Save and close the Site.css file.

Results: After completing this exercise, you will have added dynamic data to an existing Web site.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-50

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 2: Registering Entity Framework with Dynamic Data


The main tasks for this exercise are as follows:
1.

Add a Global Application Class file.

2.

Import the required namespaces.

3.

Get Entity Model namespace.

4.

Register the ObjectContext with the metadata model.

5.

Add a generic route to the routing table.

Task 1: Add a Global Application Class file

Add Global Application Class project item to the CustomerManagement Web site.

Task 2: Import the required namespaces

Add an Import directive to the Global Application Class with the Namespace attribute set to
System.Web.Routing.
<%@ Import Namespace="System.Web.Routing" %>

Task 3: Get Entity Model namespace

Open the CustomerManagement Entity Model CustomerManagement.edmx that is located in the


App_Code folder, in the ADO.NET Entity Data Model Designer (Entity Designer).

Notice the namespace that is used for the code that is generated for the entity model.

Close the CustomerManagement Entity Model.

Task 4: Register the ObjectContext with the metadata model

Create a public Shared procedure named Register, which takes a single parameter named routes, of
type RouteCollection.

Note: The Register procedure does not return a value.


Public Shared Sub Register(ByVal routes As RouteCollection)
End Sub

In the Global.asax file, in the Application_Start method, call the Register procedure by passing
RouteTable.Routes as the only parameter.
Register(RouteTable.Routes)

Add and initialize a new private shared variable of type MetaModel, named defaultModel. Initialize
by using the default and parameterless constructor.
Private Shared defaultModel As New MetaModel()

Add a new public shared property of type MetaModel, named DefaultMetaModel. Make the
property read-only and have it return the private and shared variable, defaultModel.
Public Shared ReadOnly Property DefaultMetaModel As MetaModel
Get
Return defaultModel
End Get
End Property

Register the CustomerManagementModel.Entities ObjectContext in the Register procedure with


scaffolding enabled for all tables by using the RegisterContext method of the MetaModel class.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-51

DefaultMetaModel.RegisterContext(GetType(CustomerManagementModel.Entities), New
ContextConfiguration() With
})

.ScaffoldAllTables = True

Task 5: Add a generic route to the routing table

In the Register procedure, add a generic route of type DynamicDataRoute for the List, Details,
Edit, and Insert actions, in that order. Use the DefaultMetaModel as the meta model to redirect to
the page template of the same name, which is prefixed in the URL with the table name. Add the route
by using the Add method of the passed routes parameter.
routes.Add(New DynamicDataRoute("{table}/{action}.aspx") With {
.Constraints = New RouteValueDictionary(New With {.Action =
"List|Details|Edit|Insert"}),
.Model = DefaultMetaModel
})

Save the Global Application Class project item.

Close the Global Application Class project item.

Results: After completing this exercise, you will have registered Entity Framework with Dynamic Data.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-52

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Map, Clean, and Test the Solution


The main tasks for this exercise are as follows:
1.

Map navigation to Dynamic Data page templates.

2.

Remove superfluous solution and project items.

3.

Test the Dynamic Data functionality.

Task 1: Map navigation to Dynamic Data page templates

Open the web.sitemap file.

Map the New menu command in the Customers menu to the Insert page template, by modifying
the url attribute for the New siteMapNode within the Customers siteMapNode, to a value of
~/Customers/Insert.aspx.
<siteMapNode title="New" description="Create New Customer"
url="~/Customers/Insert.aspx" />

Map the All menu command in the Customers menu to the List page template, by modifying the url
attribute for the All siteMapNode within the Customers siteMapNode, to a value of
~/Customers/List.aspx.
<siteMapNode title="All" description="View All Customers" url="~/Customers/List.aspx"
/>

Add a New menu command to the Countries menu to make it use the Insert page template, by
adding a new siteMapNode within the Countries siteMapNode.
<siteMapNode title="New" description="Create New Country"
url="~/Countries/Insert.aspx" />

Add an All menu command to the Countries menu to make it use the List page template, by adding
a new siteMapNode within the Countries siteMapNode.
<siteMapNode title="All" description="View All Countries" url="~/Countries/List.aspx"
/>

Save and close the web.sitemap file.

Task 2: Remove superfluous solution and project items

Remove the CustomerManagementEntities project from the CustomerManagement solution.

Delete the Customers Web Form in the CustomerManagement Web site.

Delete the InsertCustomer Web Form in the CustomerManagement Web site.

Delete the Customer user control in the CustomerManagement Web site.

Task 3: Test the Dynamic Data functionality

Run the CustomerManagement application.

Show all customers, by clicking All, on the Customers menu.

Close all open windows.

Task 4: 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-53

Section 2: Visual C#
Exercise 1: Adding Dynamic Data to an Existing Web Site
The main tasks for this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Create a sample Dynamic Data Web site.

3.

Add the dynamic data default files and folders.

4.

Add the ScriptManager control to the master page.

5.

Update Dynamic Data page templates to use an existing master page.

6.

Copy dynamic data styles.

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\M10\CS folder.

Task 2: Create a sample Dynamic Data Web site

Open a second instance of Visual Studio 2010.

Create a new ASP.NET Dynamic Data Web site in the D:\Labfiles\Starter\M10\CS\SampleDDWebSite


folder.

Close the second instance of Visual Studio 2010.

Task 3: Add the dynamic data default files and folders

Add the DynamicData folder and default dynamic data content from the SampleDDWebSite Web
site to the CustomerManagement Web site by copying the DynamicData folder from the path,
D:\Labfiles\Starter\M10\CS\SampleDDWebSite\DynamicData.

In Solution Explorer, refresh the Web site content to ensure the addition of the DynamicData folder.

Task 4: Add the ScriptManager control to the master page

Open the Site.master master page in Source view.

Add a ScriptManager control before the div element with a value of content for the class attribute
by adding an asp:ScriptManager element with an ID attribute value of MainScriptManager.

Save the Site.master master page.

Close the Site.master master page.

Task 5: Update the Dynamic Data page templates to use an existing master page

Open the Find and Replace dialog box.

Replace the ContentPlaceHolder1 name that is referenced in the Dynamic Data Page Templates,
with the name of the ContentPlaceHolder control used in the existing master page,
MainContentPlaceHolder.

In all of the opened and modified Dynamic Data page templatesDetails.aspx, Edit.aspx,
Insert.aspx, List.aspx, and ListDetails.aspxremove the Content control with an ID attribute value
of headContent.

Save and close all modified files.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-54

Introduction to Web Development with Microsoft Visual Studio 2010

Task 6: Copy dynamic data styles

Copy the content of the D:\Labfiles\Starter\M10\CS


\SampleDDWebSite\Site.css stylesheet.

Add the copied content to the existing Styles\Site.css stylesheet.

Save and close the Site.css file.

Results: After completing this exercise, you will have added dynamic data to an existing Web site.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-55

Exercise 2: Registering Entity Framework with Dynamic Data


The main tasks for this exercise are as follows:
1.

Add a Global Application Class file.

2.

Import the required namespaces.

3.

Get Entity Model namespace.

4.

Register the ObjectContext with the metadata model.

5.

Add a generic route to the routing table.

Task 1: Add a Global Application Class file

Add Global Application Class project item to the CustomerManagement Web site.

Task 2: Import the required namespaces

Add an Import directive to the Global Application Class with the Namespace attribute set to
System.Web.Routing.
<%@ Import Namespace="System.Web.Routing" %>

Task 3: Get Entity Model namespace

Open the CustomerManagement Entity Model CustomerManagement.edmx that is located in the


App_Code folder, in the ADO.NET Entity Data Model Designer (Entity Designer).

Notice the namespace that is used for the code that is generated for the entity model.

Close the CustomerManagement Entity Model.

Task 4: Register the ObjectContext with the metadata model

Create a public static procedure named Register, which takes a single parameter named routes, of
type RouteCollection.

Note: The Register procedure does not return a value.


public static void Register(RouteCollection routes)
{
}

In the Global.asax file, in the Application_Start method, call the Register procedure by passing
RouteTable.Routes as the only parameter.
Register(RouteTable.Routes);

Add and initialize a new private static variable of type MetaModel, named defaultModel. Initialize
by using the default and parameterless constructor.
private static MetaModel defaultModel = new MetaModel();

Add a new public static property of type MetaModel, named DefaultMetaModel. Make the
property read-only, and have it return the private and static variable, defaultModel.
public static MetaModel DefaultMetaModel
{
get
{
return defaultModel;
}
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-56

Introduction to Web Development with Microsoft Visual Studio 2010

Register the CustomerManagementModel.Entities ObjectContext in the Register procedure with


scaffolding enabled for all tables by using the RegisterContext method of the MetaModel class.
DefaultMetaModel.RegisterContext(typeof(CustomerManagementModel.Entities), new
ContextConfiguration()
{
ScaffoldAllTables = true
});

Task 5: Add a generic route to the routing table

In the Register procedure, add a generic route of type DynamicDataRoute, for the List, Details,
Edit, and Insert actions, in that order. Use the DefaultMetaModel as the meta model to redirect to
the page template of the same name, which is prefixed in the URL with the table name. Add the route
by using the Add method of the passed routes parameter.
routes.Add(new DynamicDataRoute("{table}/{action}.aspx") {
Constraints = new RouteValueDictionary(new { action = "List|Details|Edit|Insert"
}),
Model = DefaultMetaModel
});

Save the Global Application Class project item.

Close the Global Application Class project item.

Results: After completing this exercise, you will have registered Entity Framework with Dynamic Data.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-57

Exercise 3: Map, Clean, and Test the Solution


The main tasks for this exercise are as follows:
1.

Map navigation to Dynamic Data page templates.

2.

Remove superfluous solution and project items.

3.

Test the Dynamic Data functionality.

Task 1: Map navigation to Dynamic Data page templates

Open the web.sitemap file.

Map the New menu command in the Customers menu to the Insert page template, by modifying
the url attribute for the New siteMapNode within the Customers siteMapNode, to a value of
~/Customers/Insert.aspx.
<siteMapNode title="New" description="Create New Customer"
url="~/Customers/Insert.aspx" />

Map the All menu command in the Customers menu to the List page template, by modifying the url
attribute for the All siteMapNode within the Customers siteMapNode, to a value of
~/Customers/List.aspx.
<siteMapNode title="All" description="View All Customers" url="~/Customers/List.aspx"
/>

Add a New menu command to the Countries menu to make it use the Insert page template, by
adding a new siteMapNode within the Countries siteMapNode.
<siteMapNode title="New" description="Create New Country"
url="~/Countries/Insert.aspx" />

Add an All menu command to the Countries menu to make it use the List page template, by adding
a new siteMapNode within the Countries siteMapNode.
<siteMapNode title="All" description="View All Countries" url="~/Countries/List.aspx"
/>

Save and close the web.sitemap file.

Task 2: Remove superfluous solution and project items

Remove the CustomerManagementEntities project from the CustomerManagement solution.

Delete the Customers Web Form in the CustomerManagement Web site.

Delete the InsertCustomer Web Form in the CustomerManagement Web site.

Delete the Customer user control in the CustomerManagement Web site.

Task 3: Test the Dynamic Data functionality

Run the CustomerManagement application.

In the Contoso Customer Management Windows Internet Explorer window, on the Customers
menu, click All.

Close all open windows.

Task 4: 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.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-58

Introduction to Web Development with Microsoft Visual Studio 2010

Lab Review

Review Questions and Answers


1.

In which file should you add the registration of the context?

2.

What is the use of the ScaffoldColumnAttribute attribute?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Managing Data by Using Microsoft ASP.NET Dynamic Data

10-59

Module Review and Takeaways

Review Questions and Answers


1.

What are the capabilities provided by Scaffolding?

2.

What are the features of Dynamic Data?

3.

List the built-in page templates.

Real-World Issues and Scenarios


1.

You need to modify the page template for displaying all rows in any registered database entity. What
is the easiest way to do this?
You should modify the List.aspx page template.

2.

You need to create a specific view for a single entity in your data model. How do you do this?
Create a subfolder in the DynamicData\CustomPages folder, and name the subfolder the same as
the entity in your data context, but use a plural ending. Create a new content page, and then add it
to the subfolder.

Best Practices

Do not modify the generated DataContext or ObjectContext classes. Instead, create partial classes
and place the custom code in partial classes. When the DataContext or ObjectContext classes are
regenerated, any changes are overridden.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

10-60

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-1

Module 11
Creating a Microsoft ASP.NET Ajax-enabled Web Forms
Application
Contents:
Lesson 1: Introduction to Ajax

11-3

Lesson 2: Creating an ASP.NET Ajax Application by Using the


Ajax Features for ASP.NET

11-9

Lesson 3: Extending an ASP.NET Web Forms Application by


Using the Ajax Control Toolkit

11-29

Lab: Creating a Microsoft ASP.NET Ajax-enabled


Web Forms Application

11-38

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-2

Introduction to Web Development with Microsoft Visual Studio 2010

Module Overview

Asynchronous JavaScript and XML (Ajax) is a set of technologies that you can use to make your Web
pages more responsive. Microsoft ASP.NET Ajax integrates Ajax featuressuch as partial-page updates,
asynchronous calls made to the Web server, and the use of user interface elementsinto ASP.NET Web
application development. You can use Ajax to create rich and responsive Web applications that provide a
good user experience.
This module provides an overview of Ajax, and explains how to create an ASP.NET Web application with
Ajax capabilities, by using Microsoft and ASP.NET Ajax. The module also introduces the Ajax Control
Toolkit, explains how to install the toolkit, and how to add controls from the toolkit to an ASP.NET Web
Forms application.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-3

Lesson 1

Introduction to Ajax

Using Ajax, Web applications can retrieve data from the server asynchronously in the background without
affecting the display and behavior of the existing page. You use Microsoft Ajax to either create entirely
client-based Ajax applications, or you can use the Ajax features of ASP.NET for implementing Ajax-related
functionality. Microsoft Ajax helps you create Web pages that allow partial-page updates to refresh only
the areas of a Web page that are updated. Partial page updates and asynchronous calls made to the Web
server not only provide a rich user experience that emulates a responsive user interface (UI), but also
reduces bandwidth usage and page load times.
In this lesson, you will get an overview of both Ajax and Microsoft Ajax, and ASP.NET Ajax technologies.
You will also examine the architecture of Microsoft Ajax.

Lesson Objectives
After completing this lesson, you will be able to:

Describe AJAX.

Describe ASP.NET Ajax.

Describe the architecture of ASP.NET Ajax.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-4

Introduction to Web Development with Microsoft Visual Studio 2010

What Is Asynchronous JavaScript and XML?

Key Points
Ajax is a group of technologies that are designed to increase the responsiveness of Web pages. Using
Ajax, you can refresh parts of a page instead of the whole Web page during data exchange with the Web
server. This increases the speed and interactivity of the page.
Ajax works across multiple platforms and browsers, and uses open standards, such as JavaScript. The
asynchronous nature of Ajax helps your application retrieve data from the server as a background task
that does not affect the current Web page display.
The types of information that can be updated by using Ajax in Web sites include sports score results,
counters, timers, clocks, share prices, and news. The information is typically updated at regular intervals,
which can be implemented by using a timer.

Ajax Technologies
Ajax is not a technology in itself, but a term that refers to the use of a group of technologies. Ajax uses a
combination of:

An XMLHttpRequest object, which you can use for data exchange between the browser and the
Web server asynchronously. This object enables browsers to request data without a page reload, and
it is one of the key features of Ajax.

HTML, XHTML, and cascading style sheets (CSS), which provide the markup and style information for
a Web page.

XML and other data transfer formats, such as JavaScript Object Notation (JSON), which you can use to
transfer data between a Web server and a client.

Document Object Model (DOM), which you use with a scripting language such as JavaScript to
provide client-side interaction with the data on a Web page.

Question: What are some of the benefits that Ajax provides?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-5

What Is ASP.NET Ajax?

Key Points
ASP.NET Ajax enables you to develop Web pages that integrate ASP.NET and Ajax technologies. You can
use ASP.NET Ajax to make your Web applications more efficient and responsive. ASP.NET Ajax is a
framework for building interactive and responsive Web applications that work across all popular browsers.
The ASP.NET Ajax framework includes:

Server-side ASP.NET Ajax. This is included in ASP.NET 4.0 for building Ajax-enabled ASP.NET Web
Forms and server controls. It includes the Ajax Server controls, which enables you to add Ajax
functionality to an ASP.NET Web Form.

Client-side ASP.NET Ajax. The Microsoft Ajax Library is a JavaScript library that provides the clientside features of the ASP.NET Ajax framework. The Microsoft Ajax Library is released separately from
the ASP.NET framework and Microsoft Visual Studio, but it integrates with Visual Studio 2010 and
ASP.NET 4.0.

Ajax Control Toolkit. The Ajax Control Toolkit provides a powerful software development kit (SDK)
that makes it easy to create and reuse custom controls and extenders. The Control Toolkit includes
samples and components that show you some of the experiences that you can create with ASP.NET
Ajax controls and extenders. The Ajax Control Toolkit is community-supported.

jQuery library. This is a JavaScript function library that focuses on DOM querying and manipulation.

Microsoft Ajax Content Delivery Network. The Microsoft Ajax Content Delivery Network (CDN)
enables you to easily add Microsoft Ajax Library and jQuery scripts to your Web applications. Using
Microsoft Ajax CDN, you can significantly improve the performance of your Ajax applications. The
contents of the Microsoft Ajax CDN are cached on servers located around the world.

ASP.NET Ajax helps developers choose the method of Ajax development. The development methods
include client-side programming, server-side programming, or a combination of both. ASP.NET Ajax is
integrated with Microsoft .NET Framework 4, and enables you to build Web applications that implement
Ajax features by using the design tools provided by Visual Studio 2010.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-6

Introduction to Web Development with Microsoft Visual Studio 2010

Key Features of ASP.NET Ajax


Ajax features in ASP.NET enable you to build rich Web applications that have many advantages over
server-based Web applications. Ajax-enabled applications offer:

Improved efficiency, because significant parts of Web page processing are performed in the browser.

Familiar UI elements such as progress indicators, tooltips, calendars, and pop-up windows.

Partial-page updates that refresh only the parts of the Web page that have changed.

Client integration with ASP.NET application services for security features such as forms authentication,
roles, and user profiles.

Auto-generated proxy classes that simplify the call to Web service methods from client script.

A framework that lets you customize server controls to include client capabilities.

Support for the most popular and generally used browsers, including Windows Internet Explorer,
Mozilla Firefox, and Apple Safari.

Data integration by using Web services.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-7

Architecture of ASP.NET Ajax

Key Points
ASP.NET Ajax consists of client-script libraries and server components.

Client Architecture
The client architecture of ASP.NET Ajax consists of the Microsoft Ajax Library. The client-script libraries
contain JavaScript files that provide features that enable you to develop consistent and modular
applications.
The ASP.NET Ajax client architecture includes the following layers:

Components. Components enable rich behaviors in the browser, by providing support for features
such as behaviors, controls, and non-visual components, without postbacks.

Browser compatibility. The browser compatibility layer provides support for multiple browsersfor
example, Internet Explorer, Mozilla Firefox, and Apple Safari.

Networking. The networking layer handles asynchronous requests, and provides communication
with Web and application services, and XML and JSON serialization.

Core services. The core services layer provides a JavaScript base class library, and object-oriented
extensions that enable you to make use of features such as classes, inheritance, serialization, and
event handling.

Debugging and Error Handling. Core services include the Sys.Debug class, which provides methods
for displaying objects in a readable form at the end of a Web page. The class also shows trace
messages, enables you to use assertions, and lets you break into the debugger.

Globalization. The Ajax server and client architecture in ASP.NET provides a model for localizing and
globalizing client script. This enables you to design applications that use a single code base to
provide UI for many languages and cultures.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-8

Introduction to Web Development with Microsoft Visual Studio 2010

Server Architecture
The server architecture of ASP.NET Ajax consists of ASP.NET server controls and components that you can
use to create the UI, and implement the functionality and flow of an application. ASP.NET Ajax includes
the following server components:

Script support. Ajax features in ASP.NET are implemented by using supporting scripts that are sent
from the server to the client. Depending on the Ajax features that you enable, different scripts are
sent to the browser. You can also create custom client script for your ASP.NET applications. ASP.NET
Ajax includes support for debug and release modes; this enables you to test for errors in your code,
and then create a release version of the code before you deploy your application. Script support for
Ajax in ASP.NET provides partial-page rendering, which updates regions of the page by using an
asynchronous postback.

Localization. The ASP.NET Ajax architecture builds on the foundation of the ASP.NET localization
model, and it provides additional support for localized .js files. ASP.NET can serve localized client
scripts and resources automatically, for specific languages and regions.

Web services. ASP.NET Ajax enables you to use client script to call ASP.NET Web services and
Windows Communication Foundation (WCF) Services.

Application services. ASP.NET Ajax enables you to use application servicessuch as Forms
authentication and profileswithout a page postback. Application services in ASP.NET are built-in
Web services.

Server controls. The Ajax Server controls consist of server and client code that integrate to produce
rich client behavior. The most commonly used of these controls are the ScriptManager,
UpdatePanel, UpdateProgress, and Timer controls.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-9

Lesson 2

Creating an ASP.NET Ajax Application by Using the


Ajax Features for ASP.NET

As a developer, you might spend most of your time on the server-side aspects of ASP.NET Ajax, because
ASP.NET Ajax focuses on the client-side technologies interacting with server-side technologies. The Ajax
Features for ASP.NET provide server-side controls and functionality that you can use to implement Ajax
features in your ASP.NET Web applications. The server-side framework not only manages client requests,
but also manages the interaction and exchange of JavaScript objects and the Microsoft .NET objects
between the client-side and server-side code. The Ajax Features for ASP.NET work over the core layer of
the ASP.NET 4.0 Framework, WCF, and ASP.NET-based Web services.
This lesson describes the Ajax Features for ASP.NET, and explains how to use several of the available
ASP.NET Ajax server controls.

Lesson Objectives
After completing this lesson, you will be able to:

Describe the Ajax Features for ASP.NET.

Describe the ASP.NET Ajax server controls and their uses.

Describe the uses of the ScriptManager control.

Explain how to add the ScriptManager control.

Describe the uses of the UpdatePanel control.

Explain how to add the UpdatePanel control.

Describe the UpdateProgress control.

Describe partial-page updates.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-10

Introduction to Web Development with Microsoft Visual Studio 2010

What Are the Ajax Features for ASP.NET?

Key Points
Ajax features for ASP.NET contain the core server-side components of ASP.NET Ajax. The Ajax Features
extend the server-side control framework of ASP.NET, and provide new controls that you can use to
implement Ajax features in your ASP.NET Web applications. These controls appear in a separate tab in the
Visual Studio Toolbox.

ASP.NET Ajax Server-Side Programming


Developers familiar with the ASP.NET server-side programming model can use the ASP.NET Ajax serverside controls UpdatePanel, UpdateProgress, and ScriptManager to implement Ajax functionality in an
ASP.NET Web Forms application without writing any JavaScript. For example, the UpdatePanel control
helps you update a portion of an ASP.NET Web Form without requiring you to reload the entire page. The
ScriptManager control helps you manage browser history in an Ajax application. You can do this by
updating the browser back button after an Ajax request.
The ASP.NET Ajax server-side controls are included as a standard part of the ASP.NET 4.0 framework.
These controls are available in Visual Studio 2010, or the Visual Web Developer toolbox.
In addition, the Ajax Control Toolkit provides many more controls that you can add to your toolbox and
include in your pages.
You can enhance the server-based features of ASP.NET by including client-script functionality in ASP.NET
Web Forms. You can use a client script to provide a rich and responsive user interface to users. You can
also use client script to make asynchronous calls to the Web server while a page is running in the browser.
Question: What are the ASP.NET Ajax server-side controls that help you add Ajax functionality to an
ASP.NET Web Forms application, without the need for any scripting?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-11

ASP.NET Ajax Server Controls

Key Points
Ajax features for ASP.NET provides server controls. The following list describes the most frequently used
ASP.NET Ajax server controls:

ScriptManager. The ScriptManager control is used to manage client script for Ajax-enabled
ASP.NET Web Forms. By default, the ScriptManager control registers the script for the Ajax Library
with the page. This enables a client script to use the type system extensions, and to support features
such as partial-page rendering and Web-service calls. You must add a ScriptManager control to a
Web page before you can use the UpdatePanel, UpdateProgress, and Timer controls. If you have a
ScriptManager control on a master page, you need a ScriptManagerProxy control on a content
page if you are using Ajax controls on the content page. In addition, the ScriptManager control
enables the Microsoft Ajax Library to be loaded from the Microsoft CDN.

UpdatePanel. The UpdatePanel controls help you build client-centric Web applications. With
UpdatePanel controls, you can refresh specific parts of the page instead of refreshing the entire page
with a postback. This is referred to as performing a partial-page update. An ASP.NET Web Form that
contains a ScriptManager control and one or more UpdatePanel controls can automatically
participate in partial-page updates, without custom client script. To use an UpdatePanel, you add an
instance of the control on a page, and then place other server controls inside the panel.

UpdateProgress. The UpdateProgress control provides status information about partial-page


updates in UpdatePanel controls. You can customize the default content and the layout of the
UpdateProgress control. The UpdateProgress control enables you to provide progress information
about partial-page updates. The UpdateProgress control can work with an entire page, or with just a
specific UpdatePanel control. When a partial-page update is fast, you can prevent flashing. To do
this, you can specify a delay before the UpdateProgress control displays. This way, you can control
how long after the update the content of the UpdateProgress control displays.

Timer. The ASP.NET Ajax Timer control performs postbacks at defined intervals. You can use the
Timer control in conjunction with an UpdatePanel to perform a partial-page update at a defined
interval. You can also use the Timer control to post the whole page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-12

Introduction to Web Development with Microsoft Visual Studio 2010

Question: What are some of the scenarios in which you can use the ScriptManager control, the Timer
control, the UpdateProgress control, and the UpdatePanel control?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-13

Uses of the ScriptManager Control

Key Points
When a page contains one or more UpdatePanel controls, the ScriptManager control is used to manage
partial-page rendering in the browser. The control interacts with the page life cycle to update the parts of
the page that are inside the UpdatePanel controls.
The EnablePartialRendering property of the ScriptManager control determines whether a page
participates in partial-page updates. By default, the EnablePartialRendering property is true. Therefore,
by default, partial-page rendering is enabled when you add a ScriptManager control to the page.

Using Type-System Extensions


The Microsoft Ajax Library adds type-system extensions to JavaScript that provide namespaces,
inheritance, interfaces, enumerations, reflection, and helper functions for strings and arrays. These
extensions provide functionality in client script that is like that of the .NET Framework. They enable you to
write Ajax-enabled ASP.NET applications in a structured way that improves maintainability, makes it easier
to add features, and makes it easier to layer the functionality. Adding a ScriptManager control to an
ASP.NET Web Form automatically includes the type-system extensions, so that you can use the library in
client script.

Registering the Custom Script


Use the ScriptManager control to manage resources that you have created for controls that participate in
partial-page updates. Resources include scripts, styles, hidden fields, and arrays. The Scripts collection of
the ScriptManager control contains a ScriptReference object for each script that is available to the
browser. You can specify the scripts declaratively or programmatically.
The ScriptManager control also exposes registration methods that you can programmatically use to
manage client script and hidden fields. When you are registering a script or hidden fields that support
partial-page updates, you must call the registration methods of the ScriptManager control. To register
scripts that are not needed for partial-page updates, you can use the methods of the
ClientScriptManager class.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-14

Introduction to Web Development with Microsoft Visual Studio 2010

Registering the Web Services


To register a Web service that you want to call from an Ajax-enabled ASP.NET Web Form, you register the
Web service by adding it to the Services collection of the ScriptManager control. The ASP.NET Ajax
framework generates a client proxy object for each ServiceReference object in the Services collection.
The proxy classes and their strongly-typed members simplify using Web services from client script.
You can programmatically add ServiceReference objects to the Services collection to register Web
services at run time.

Using Authentication, Profile, and Role Services from Client Script


The Microsoft Ajax Library includes proxy classes for calling the ASP.NET 4.0 forms authentication, profile,
and role application services directly from JavaScript. If you want to use a custom authentication service,
you can register it by using the ScriptManager control.

The ScriptManagerProxy Class


Only one instance of the ScriptManager control can be added to a Web page. The Web page can include
the control directly or indirectly inside a nested component, such as a user control, content page of a
master page, or a nested master page. If the page already contains a ScriptManager control, but a nested
or parent component needs additional features of the ScriptManager control, the component can
include a ScriptManagerProxy control. Then, the ScriptManagerProxy control enables you to add
scripts and services that are specific to nested components.
Question: How many ScriptManager controls can you add to a Web page?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-15

Demonstration: How to Add the ScriptManager Control

Key Points
In the following demonstration, you will see how to add a ScriptManager control to an ASP.NET Ajaxenabled Web site.

Demonstration Steps
1.

Open Visual Studio 2010.

2.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Create a new ASP.NET Web site.

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 Web Site is selected.

In the Web location box of the New Web Site dialog box, ensure File System is selected, and
then click OK.

Note: You can add the ScriptManager control after you create an ASP.NET Web site.
3.

Add a Web Form named Employees.aspx, to the Web site.

In Solution Explorer, right-click C:\...\WebSite1\, and then click Add New Item.

Note: In this demonstration, the name of the Web site is WebSite1.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-16

Introduction to Web Development with Microsoft Visual Studio 2010

4.

In the Add New Item C:\Users\student\Documents


\Visual Studio 2010\WebSites\WebSite1\ dialog box, in the left pane, click either Visual Basic
or Visual C#.

In the middle pane, click Web Form.

In the Name box, type Employees.aspx, clear the Place code in separate file check box, and
then click Add.

Open the Web Form in the Design view.

5.

Add a ScriptManager control to the Web Form.

6.

In the AJAX Extensions tab of the toolbox, double-click the ScriptManager control to add it to
the page.

Set the ID attribute of the ScriptManager control to a value of EmployeesScriptManager.

7.

In the Employees.aspx window, click Design.

In the Properties window, in the ID attribute, change the ScriptManager1 to


EmployeesScriptManager.

Add an UpdatePanel control under the ScriptManager control.

In the AJAX Extensions tab of the toolbox, drag the UpdatePanel control under the
ScriptManager control.

In the Properties window, set the ID property of the UpdatePanel control to a value of
EmployeesUpdatePanel.

In the WebSite1 Microsoft Visual Studio window, click Close button.

Note: After adding the ScriptManager control, you can add controls that you want asynchronously
refreshed to EmployeesUpdatePanel, and set their properties by using the Properties window. You can
also add any code to the events of the page and the controls to the code-behind file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-17

Uses of the UpdatePanel Control

Key Points
The UpdatePanel controls work by specifying regions of a page that can be updated without refreshing
the whole page. The partial-page update process is coordinated by both the ScriptManager server
control and the client PageRequestManager class.
When you enable partial-page updates, controls can asynchronously post back to the server. Because
asynchronous postback is similar to a regular postback, the resulting server page runs the complete page
and control life cycle. However, with an asynchronous postback, page updates are limited to regions of
the page that are enclosed in UpdatePanel controls, and are marked to be updated. The server sends the
HTML markup for only the updated elements to the browser. In the browser, the client
PageRequestManager class performs DOM manipulation to replace existing HTML with the updated
markup.
The UpdatePanel control performs partial-page updates and identifies content that is updated
independently of the rest of the page.

Enabling Partial-Page Updates


The UpdatePanel control requires a ScriptManager control on the Web page. By default, partial-page
updates are enabled because the default value of the EnablePartialRendering property of the
ScriptManager control is true.
The following example shows markup that defines a ScriptManager control and an UpdatePanel control
on a page. The UpdatePanel control contains a Button control that refreshes the content inside the
panel when you click it. By default, the ChildrenAsTriggers property is true. Therefore, the Button
control acts as an asynchronous postback control.
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="MainUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<fieldset>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-18

Introduction to Web Development with Microsoft Visual Studio 2010

<legend>UpdatePanel content</legend>
<!-- Other content in the panel. -->
<%=DateTime.Now.ToString() %>
<br />
<asp:Button ID="RefreshButton" Text="Refresh Panel" runat="server" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>

Notice that the UpdateMode property is set to Conditional to ensure that the content of the
UpdatePanel is only updated when a control inside the UpdatePanel causes a postback.
Note: If the UpdateMode property is set to Always, the UpdatePanel controls content is updated on
every postback that originates from anywhere on the page. In general, an UpdatePanel control should
not be used to update an entire Web Form, only parts of it.

Specifying UpdatePanel Control Content


You can add content to an UpdatePanel control declaratively, or in the designer by using the
ContentTemplate property. In the markup, this property is exposed as a ContentTemplate element. To
add content programmatically, you can use the ContentTemplateContainer property. In the example,
the HTML fieldset and legend elements are used to show how plain HTML elements can be used with
server controls in an UpdatePanel control.
When a page that contains one or more UpdatePanel controls is first rendered, all the contents of the
UpdatePanel controls are rendered and sent to the browser. On subsequent asynchronous postbacks, the
content of individual UpdatePanel controls might be updated. Updates depend on the panel settings, on
the element that caused the postback, and on code that is specific to each panel.

Specifying UpdatePanel Triggers


By default, any postback control inside an UpdatePanel control causes an asynchronous postback and
refreshes the content of the panel. However, you can also configure other controls on the page to refresh
an UpdatePanel control. You do this by defining a trigger for the UpdatePanel control. A trigger is a
binding that specifies the postback control and the event that causes a panel to update. When the
specified event of the trigger control is raisedfor example, a button's Click eventthe update panel is
refreshed.
The following example shows how to specify a trigger for an UpdatePanel control.
[Visual Basic]
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:Button ID="RefreshButton" Text="Refresh Panel" runat="server" />
<asp:UpdatePanel ID="MainUpdatePanel" UpdateMode="Conditional"
runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RefreshButton" />
</Triggers>
<ContentTemplate>
<fieldset>
<legend>UpdatePanel content</legend>
<%=DateTime.Now.ToString() %>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-19

[Visual C#]
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:Button ID="RefreshButton" Text="Refresh Panel" runat="server" />
<asp:UpdatePanel ID="MainUpdatePanel" UpdateMode="Conditional" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="RefreshButton" />
</Triggers>
<ContentTemplate>
<fieldset>
<legend>UpdatePanel content</legend>
<%=DateTime.Now.ToString() %>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>

You can define the trigger by using the asp:AsyncPostBackTrigger element inside the Triggers element
of the UpdatePanel control. If you are editing the page in Visual Studio, you can create triggers by using
the UpdatePanelTrigger Collection Editor dialog box.
A trigger's control event is optional. If you do not specify an event, the trigger event is the default event
of the control. For example, for the Button control, the default event is the Click event.

How UpdatePanel Controls Are Refreshed


The following list describes the property settings of the UpdatePanel control, which determine when a
panel's content is updated during partial-page rendering.

If the UpdateMode property is set to Always, the UpdatePanel controls content is updated on
every postback that originates from anywhere on the page. This includes asynchronous postback
from controls that are inside other UpdatePanel controls, and postback from controls that are not
inside UpdatePanel controls.

If the UpdateMode property is set to Conditional, the UpdatePanel controls content is updated
when one of the following is true:

When the postback is caused by a trigger for that UpdatePanel control.

When you explicitly call the UpdatePanel control's Update method.

When the UpdatePanel control is nested inside another UpdatePanel control, and the parent
panel is updated.

When the ChildrenAsTriggers property is set to true, and any child control of the UpdatePanel
control causes a postback. Child controls of nested UpdatePanel controls do not cause an
update to the outer UpdatePanel control unless they are explicitly defined as triggers for the
parent panel.
If the ChildrenAsTriggers property is set to false, and the UpdateMode property is set to
Always, an exception is thrown. You should use the ChildrenAsTriggers property only when the
UpdateMode property is set to Conditional.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-20

Introduction to Web Development with Microsoft Visual Studio 2010

Demonstration: How to Add the UpdatePanel Control

Key Points
In this demonstration, you will see how to add the UpdatePanel control to an ASP.NET Ajax Web page.

Demonstration Steps
To run the demonstration, you need to perform the following steps:
1.

Open Visual Studio 2010.

2.

3.

4.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then Microsoft Visual Studio 2010.

Create a new ASP.NET Web site.

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 Web Site is selected.

In the Web location box of the New Web Site dialog box, ensure File System is selected, and
then click OK.

Add a Web Form named UpdatePanel.aspx, to the Web site.

In Solution Explorer, right-click C:\Users\student\Documents\Visual Studio


2010\WebSites\WebSite1, and then click Add New Item.

In the Add New Item C:\Users\student\Documents\Visual Studio


2010\WebSites\WebSite1\ dialog box, in the left pane, click either Visual Basic or Visual C#.

In the middle pane, click Web Form.

In the Name box, type UpdatePanel.aspx, and then click Add.

Open the Web Form in the Design view.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

5.

6.

11-21

In the UpdatePanel.aspx window, click Design.

Add ScriptManager and UpdatePanel controls in the Design view of the UpdatePanel.aspx Web
Form.

In the UpdatePanel.aspx window, point to Toolbox.

In Toolbox, under AJAX Extensions, double-click ScriptManager.

In the UpdatePanel.aspx window, point to Toolbox.

In Toolbox, under AJAX Extensions, double-click UpdatePanel.

Add a ContentTemplate element to the UpdatePanel.

In the UpdatePanel.aspx window, click Source.

In the UpdatePanel.aspx window, place the cursor after the opening tag of the UpdatePanel
control, and then type the following code.
<ContentTemplate></ContentTemplate>

7.

8.

On the form, inside the UpdatePanel control, add a Button control to the ContentTemplate.

In the UpdatePanel.aspx window, click Design.

In Toolbox, expand Standard, and then drag the Button control inside the UpdatePanel
control.

Set the Text property of the Button control to InsidePanel.

9.

In the Properties window, change the value of the Text property from Button to InsidePanel.

On the form, outside the UpdatePanel control, add another Button control.

In Toolbox, double-click Button.

10. Set the Text property of the Button control to the value OutsidePanel.

In the Properties window, change the value of the Text property from Button to OutsidePanel.

11. Save the UpdatePanel.aspx Web Form, and then view the page in the browser.

On the File menu of Visual Studio 2010, click Save UpdatePanel.aspx.

In the UpdatePanel.aspx window, right-click anywhere, and then click View in Browser.

Test both InsidePanel and OutsidePanel buttons and verify that the button inside the
UpdatePanel control does not cause a page postback and the button outside UpdatePanel
control causes a postback.

In the http://localhost:49158/WebSite1/UpdatePanel.aspx - Windows Internet Explorer window,


click InsidePanel, and then click OutsidePanel.

Note: Notice that the button inside the UpdatePanel control does not cause a page postback and the
button outside UpdatePanel control causes a page postback.
12. Close Internet Explorer.

In the http://localhost:49158/WebSite1/UpdatePanel.aspx - Windows Internet Explorer window,


click the Close button.

13. Delete the InsidePanel button.

In the UpdatePanel.aspx window, delete the InsidePanel button.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-22

Introduction to Web Development with Microsoft Visual Studio 2010

14. Add a Label control inside the UpdatePanel control.

In Toolbox, under Standard, double-click Label.

15. Add code to the Click event handler to set the Text of the Label to the string Current Time:,
followed by the current date and time.

In the UpdatePanel.aspx window, double-click the OutsidePanel control.

In the UpdatePanel.aspx.vb or UpdatePanel.aspx.cs window, type the following code in the Click
event handler.
[Visual Basic]
Label1.Text = "Current Time: " & DateTime.Now.ToString()
[Visual C#]
Label1.Text = "Current Time: " + DateTime.Now.ToString();

16. Switch to the Design view of the UpdatePanel.aspx Web Form.

In Visual Studio 2010, click UpdatePanel.aspx.

17. View the properties of the UpdatePanel control.

In the UpdatePanel.aspx window, click the UpdatePanel control.

In the Properties window, click the ellipsis of the Triggers property.

18. Add a ControlID property of the new trigger to Button2.

In the UpdatePanelTrigger Collection Editor dialog box, click Add.

In the ControlID property, type Button2, and then click OK.

19. Save the Web site, and then view the UpdatePanel.aspx Web Form in the browser.

On the File menu of Visual Studio 2010, click Save All.

In the UpdatePanel.aspx window, right-click anywhere, and then click View in Browser.

20. Test the OutsidePanel button.

In the http://localhost:49158/WebSite1/UpdatePanel.aspx - Windows Internet Explorer window,


click OutsidePanel two times, and verify that the content in the label changes, but a page refresh
does not occur.

21. Close Internet Explorer.

In the http://localhost:49158/WebSite1/UpdatePanel.aspx - Windows Internet Explorer window,


click the Close button.

In the WebSite1 Microsoft Visual Studio window, click Close button.

Question: What should you define in a trigger in the UpdatePanel control?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-23

UpdateProgress Control

Key Points
The UpdateProgress control renders a div element that is displayed or hidden, depending on whether an
associated UpdatePanel control has caused an asynchronous postback. For initial page rendering and for
synchronous postback, the UpdateProgress control is not displayed.

Associating with an UpdatePanel Control


You can associate an UpdateProgress control with an UpdatePanel control by setting the
AssociatedUpdatePanelID property of the UpdateProgress control. When a postback event originates
from an UpdatePanel control, any associated UpdateProgress controls are displayed. If you do not
associate the UpdateProgress control with a specific UpdatePanel control, the UpdateProgress control
displays progress for any asynchronous postback.
If the ChildrenAsTriggers property of an UpdatePanel control is set to false, and an asynchronous
postback originates from inside that UpdatePanel control, any associated UpdateProgress controls will
be displayed.
The following examples show an UpdateProgress control that shows update status for two UpdatePanel
controls.
[Visual Basic]
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs)
System.Threading.Thread.Sleep(3000)
End Sub
</script>
<html>
<head runat="server">
<title>UpdateProgress Example</title>
<style type="text/css">
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-24

Introduction to Web Development with Microsoft Visual Studio 2010

#FirstUpdatePanel, #SecondUpdatePanel, #UpdatePanelUpdateProgress {


border-right: gray 1px solid; border-top: gray 1px solid;
border-left: gray 1px solid; border-bottom: gray 1px solid;
}
#FirstUpdatePanel, #SecondUpdatePanel {
width:200px; height:200px; position: relative;
float: left; margin-left: 10px; margin-top: 10px;
}
#UpdateProgress1 {
width: 400px; background-color: #FFC080;
bottom: 0%; left: 0px; position: absolute;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="FirstUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
<br />
<asp:Button ID="FirstUpdateButton" runat="server" Text="Refresh Panel"
OnClick="Button_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="SecondUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
<br />
<asp:Button ID="SecondUpdateButton" runat="server" Text="Refresh Panel"
OnClick="Button_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdatePanelUpdateProgress" runat="server">
<ProgressTemplate>
Update in progress...
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
</body>
</html>
[Visual C#]
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
}
</script>
<html >
<head runat="server">
<title>UpdateProgress Example</title>
<style type="text/css">
#FirstUpdatePanel, #SecondUpdatePanel, #UpdatePanelUpdateProgress {
border-right: gray 1px solid; border-top: gray 1px solid;
border-left: gray 1px solid; border-bottom: gray 1px solid;
}

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-25

#FirstUpdatePanel, #SecondUpdatePanel {
width:200px; height:200px; position: relative;
float: left; margin-left: 10px; margin-top: 10px;
}
#UpdatePanelUpdateProgress {
width: 400px; background-color: #FFC080;
bottom: 0%; left: 0px; position: absolute;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="FirstUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
<br />
<asp:Button ID="FirstUpdateButton" runat="server" Text="Refresh Panel"
OnClick="Button_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="SecondUpdatePanel" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<%=DateTime.Now.ToString() %>
<br />
<asp:Button ID="SecondUpdateButton" runat="server" Text="Refresh Panel"
OnClick="Button_Click"/>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdatePanelUpdateProgress" runat="server">
<ProgressTemplate>
Update in progress...
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</form>
</body>
</html>

Specifying Content Layout


When the DynamicLayout property is set to true, the UpdateProgress control initially occupies no space
in the page display. Instead, the page dynamically changes to display the UpdateProgress control
contents when needed. To support dynamic display, the control is rendered as a div element that has its
display style property initially set to none.
When the DynamicLayout property is false, the UpdateProgress control occupies space in the page
display, even if the control is not visible. In that case, the div element for the control has its display style
property set to block, and its visibility is initially set to hidden.

Putting UpdateProgress Controls on the Page


You can put UpdateProgress controls inside or outside UpdatePanel controls. An UpdateProgress
control is displayed whenever the UpdatePanel control it is associated with is updated as a result of an
asynchronous postback. This is true even if the UpdateProgress control is inside another UpdatePanel
control.
If an UpdatePanel control is inside another update panel, a postback that originates inside the child
panel causes any UpdateProgress controls associated with the child panel to be displayed. It also displays
any UpdateProgress controls that are associated with the parent panel. If a postback originates from an
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-26

Introduction to Web Development with Microsoft Visual Studio 2010

immediate child control of the parent panel, only the UpdateProgress controls that are associated with
the parent panel are displayed. This follows the logic for how postbacks are triggered.

Specifying When the UpdateProgress Control is Displayed


You can set the DisplayAfter property to sets the value in milliseconds (ms) before the content of the
UpdateProgress control is displayed.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-27

Partial-Page Updates

Key Points
When you implement partial-page rendering on a Web page, an instance of the PageRequestManager
class becomes available to the page. You can use this class to provide detailed management of the
partial-page rendering. You access the PageRequestManager class by using the getInstance method of
the class. You can also manipulate the instance by using other methodsfor example, the abortPostBack
or the Dispose method.
Note: You do not create an instance of the PageRequestManager class. Instead, you must get a
reference to the current instance.
The PageRequestManager class is a member of the Sys.WebForms namespace in the Microsoft Ajax
Library. The PageRequestManager class therefore belongs to the ASP.NET Ajax client infrastructure. This
client infrastructure provides automatic event binding that works in a similar way to the event binding
provided for server controls.

PageRequestManager Events
The PageRequestManager class contains several events that you can handle to provide customization of
partial-page rendering. The following table provides further information about these events.
PageRequestManager event

When raised

Usage

initializeRequest

Before the processing of the


asynchronous request begins.

Cancel a postback.

beginRequest

Before the processing of an


asynchronous postback starts.

Provide status information to


users.

pageLoading

After the server response to an

Provide custom transition effects.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-28

Introduction to Web Development with Microsoft Visual Studio 2010

PageRequestManager event

When raised

Usage

asynchronous postback is received,


but before any content on the page
is updated.
pageLoaded

After all the content on the page is


refreshed because of a postback.

Provide custom transition effects.

endRequest

After the control is returned to the


browser.

Provide status information to


users.

Implementing a PageRequestManager Event


You can use JavaScript in your Web page to handle the events raised by the PageRequestManager class.
The following code example demonstrates how to get a reference to the current instance of the
PageRequestManager class by calling the getInstance method. The example also specifies a function to
use to handle the beginRequest event of the class.
<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest (ReqHandler);
function ReqHandler(sender, args)
{
...
}
</script>

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-29

Lesson 3

Extending an ASP.NET Web Forms Application by


Using the Ajax Control Toolkit

While Visual Studio 2010 provides a few controls that allow you to build ASP.NET Web Forms applications
with Ajax capabilities, you might want to explore options for adding additional controls and functionalities
to your Web application. Developers at Microsoft and in the community have been working on a series of
Ajax-capable server controls that you can use in your ASP.NET Web Forms applications. These controls
collectively called the Ajax Control Toolkitprovide many controls and extenders that you can use to
enhance your Web applications.
This lesson describes how to download, install, and use the Ajax Control Toolkit.

Lesson Objectives
After completing this lesson, you will be able to:

Describe Ajax Control Toolkit.

Describe Ajax Control Toolkit controls.

Explain how to access the Ajax Control Toolkit.

Add an Ajax Extender Control.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-30

Introduction to Web Development with Microsoft Visual Studio 2010

Overview of the Ajax Control Toolkit

Key Points
The Microsoft Ajax Librarywhich contains the Ajax Control Toolkitis a community-supported library,
and is not supported by Microsoft. The toolkit works with the Ajax features for ASP.NET, and contains a
collection of Web-client components that you can use to enhance your Web applications. You can also
use the infrastructure of the toolkit to write reusable and extensible ASP.NET Ajax extenders and controls.
Note: There is a difference between extenders and controls. Extenders add to an existing control, but do
not change the core functionality of the control, while controls provide new functionality, typically by
wrapping an existing control.

Microsoft Ajax Library Download Content


You can download the Microsoft Ajax Library in the form of a zip file. The download contains several
folders of content, including the following:

Scripts folder. This folder contains all the Microsoft Ajax Library JavaScript files.

AspNetAjaxBetaSamples. This is folder containing a Visual Studio solution, and BetaSamples that
contains sample code illustrating how you can use features of the Microsoft Ajax Library.

Web Forms folder. This folder contains the two assemblies that are required in order to use the
controls from the Ajax Control Toolkit as Web server controls in ASP.NET Web Forms applications:
System.Web.Ajax.dll, and AjaxControlToolkit.dll.

Question: What advantages does the Ajax Control Toolkit (part of the Microsoft Ajax Library) provide?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-31

Overview of Ajax Control Toolkit Controls

Key Points
The Ajax Control Toolkit contains more than 40 controls that enable you to easily create rich, interactive
Web pages. You can test the controls by running the WebSite ASP.NET Web Site project that is part of the
BetaSamples.sln solution.

Ajax Control Toolkit Controls


The following are some of the controls and brief descriptors of the functionalities they provide, including
the CalendarExtender and ModalPopupExtender, which are used in the Lab exercises.

Accordion
The Accordion is a Web control that allows you to provide multiple panes, and display them one at a
time. This is similar to placing several CollapsiblePanelExtender controls, where only one can be
expanded at a time.

AnimationExtender
The AnimationExtender is a simple extender that allows you to utilize the powerful animation framework
with existing pages in a declarative manner. It plays animations whenever a specific event such as an
OnLoad, OnClick, OnMouseOver, or OnMouseOut event is raised by the target control.

AutoCompleteExtender
You can attach the AutoCompleteExtender control to any TextBox control, and then associate that
control with a popup panel to display words that begin with the prefix typed into the textbox.

CalendarExtender
The CalendarExtender is an ASP.NET Ajax extender that can be attached to any ASP.NET TextBox
control. It provides client-side date-selecting functionality with customizable date format and UI in a
popup control. You can interact with the calendar by clicking on a day to set the date, or use the Today
link to set the current date. In addition, you can use the left and right arrows to move forward or

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-32

Introduction to Web Development with Microsoft Visual Studio 2010

backward by a month. By clicking on the title of the calendar, you can change the view from Days in the
current month, to Months in the current year. Another click will switch to Years in the current Decade. The
click action allows you to easily jump to dates in the past or the future from within the calendar control.
The calendar associated with a button has been initialized with the following code.
<ajaxToolkit:Calendar runat="server"
TargetControlID="Date1"
CssClass="ClassName"
Format="MMMM d, yyyy"
PopupButtonID="Image1" />

In the previous code example:

TargetControlID Is the ID of the TextBox control to extend with the calendar.

CssClass - Name of the CSS class used to style the calendar. See the Calendar Theming section for
more information.

Format The format string used to display the selected date.

PopupButtonID The ID of a control to show the calendar popup when clicked. If this value is not
set, the calendar will pop up when the textbox receives focus.

PopupPosition - Indicates where the calendar popup should appear at the BottomLeft (default),
BottomRight, TopLeft, TopRight, Left, or Right of the TextBox.

SelectedDate - Indicates the date the Calendar extender is initialized with.

CollapsiblePanelExtender
The CollapsiblePanelExtender is an extender that allows you to add collapsible sections to your Web
page. This extender targets any ASP.NET Panel control. The page developer specifies the controls on the
page that should be the open or close controller for the panel, or the panel can be set to automatically
expand or collapse when the mouse pointer moves in or out of it, respectively.

ComboBox
The ComboBox is an ASP.NET Ajax control thatlike the AutoCompleteExtendercombines the
flexibility of a TextBox with a list of options that users are able to choose from. The ComboBox borrows
many of its properties, behaviors, and naming conventions from the Windows Forms ComboBox control,
and is derived from the same base class as the ListBox, BulletedList, and DropDownList Web controls. A
ComboBox is similar to a DropDownList that can be typed directly into, like a TextBox.

ConfirmButtonExtender
The ConfirmButtonExtender is an extender that catches click events on a button, or any instance of a
type derived from Button, and displays a message to the user. If the OK button is clicked in the message
that is displayed, the button or link functions normally. If not, the click is trapped, and the button will not
perform its default submit behavior. Optionally, a client script is executed if the OnClientCancel property
is already set.

DragPanelExtender
The DragPanelExtender extender allows developers to easily add drag ability to their controls. The
DragPanelExtender targets any ASP.NET panel, and takes an additional parameter that signifies the
control to use as the drag handle. Once initialized, the user can drag the panel around the Web page by
using the drag handle.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-33

DropDownExtender
The DropDownExtender is an ASP.NET Ajax extender that can be attached to almost any ASP.NET
control to provide a drop-down menu. The menu that displays is another panel or control. In the above
code example, the drop-down is a panel that contains LinkButton controls. The drop-down is activated
by clicking or right-clicking the attached control.

DropShadowExtender
The DropShadowExtender is an extender which applies a Drop Shadow to a Panel. It allows you to
specify the width and opaqueness of a shadow, or if you want to set rounded corners. For pages that
allow the user to move or resize the panel, the DropShadowExtender has a mode that will resize or
reposition it to match that of the target panel at run time.

DynamicPopulateExtender
The DynamicPopulateExtender is a simple extender that replaces the contents of a control with the
result of a Web service or page method call. The method call returns a string of HTML that is inserted as
the children of the target element.

FilteredTextBoxExtender
The FilteredTextBoxExtender is an extender that prevents a user from entering invalid characters into a
text box. You should use this extender to provide convenience for your users, but never assume that the
data being sent to the server only consists of valid characters.

HoverMenuExtender
You can attach the HoverMenuExtender to any ASP.NET Web Control, and associate that control with a
popup panel to display additional content.

HTMLEditor
You can create and edit HTML content by using the HTMLEditor. You can use the various buttons in the
toolbar for content editing. You can see the generated HTML markup, and preview the document.

ListSearchExtender
The ListSearchExtender lets you search for items in a ListBox control or DropDownList control, by
typing. The extender performs an incremental search within the ListBox control that is based on the
content typed. The prompt message that displays when you click the list can be customized along with its
CSS class and position.
You can customize the prompt message that displays when you click the list that includes its CSS class and
position.

MaskedEditExtender
You can attach the MaskedEditExtender to a TextBox control to restrict the kind of text that can be
entered. The MaskedEditExtender control applies a mask to the input, and permits only certain types of
characters and/or text to be entered. The supported data formats are: Number, Date, Time, and DateTime.
For more information about additional Ajax Control Tooklit controls, see the Companion Content
section on the CD.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-34

Introduction to Web Development with Microsoft Visual Studio 2010

Accessing the Ajax Control Toolkit

Key Points
Before you can use the Ajax Control Toolkit, you must download it. You can then add the Toolkit controls
to the Toolbox in Visual Studio 2010, and then install the provided templates.

Add the Control Toolkit to the Toolbox


To add Control Toolkit items to the Toolbox:
1.

Download the Microsoft Ajax Library from the CodePlex Web site.

2.

Unpack the Ajax Library into a folder on your computer, such as


C:\Program Files\ASP.NET Ajax Library.

3.

Create a new Web site, or open an existing Web site.

4.

In Visual Studio 2010, right-click the Toolbox, and then click Add Tab.

5.

Type the name Ajax Control Toolkit for the new tab.

6.

In the Ajax Control Toolkit tab, right-click the Toolbox, and then click Choose Items.

7.

In the Choose Toolbox Items dialog box, click Browse.

8.

Browse to the C:\Program Files\ASP.NET Ajax Library\WebForms\Debug folder.

9.

In the Debug folder, click AjaxControlToolkit.dll, and then click Open.

10. In the Choose Toolbox Items dialog box, click OK.


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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-35

Demonstration: How to Add an Ajax Extender Control

Key Points
In this demonstration, you will see how to create a sample Web application that uses several features and
controls of the Control Toolkit.

Demonstration Steps
1.

Open Visual Studio 2010.

2.

3.

4.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Create a new ASP.NET Web site named AjaxExtenderControl.

On the File menu of Visual Studio 2010, 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 Web Site is selected, in the Web location box, type
C:\Users\student\Documents
\Visual Studio 2010\WebSites\AjaxExtenderControl
\AjaxExtenderControl, and then click OK.

Add a Web Form named AjaxExtenderControl.aspx to the Web site.

In Solution Explorer, right-click C:\...\AjaxExtenderControl\, and then click Add New Item.

In the Add New Item C:\Users\student\Documents\Visual Studio


2010\WebSites\AjaxExtenderControl\ dialog box, in the left pane, click either Visual Basic or
Visual C#.

In the middle pane, click Web Form.

In the Name box, type AjaxExtenderControl.aspx, clear the Place code in separate file check
box, and then click Add.

Open the Web Form in Design view.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-36

Introduction to Web Development with Microsoft Visual Studio 2010

5.

Create a tab named Ajax Control Toolkit, in the Toolbox.

6.

In the AjaxExtenderControl.aspx window, click Design.

In the AjaxExtenderControl.aspx window, point to Toolbox, right-click anywhere in Toolbox, click


Add Tab, type Ajax Control Toolkit, and then press ENTER.

Navigate to C:\Program Files\ASP.NET Ajax Library\WebForms\Debug, and add the items from
the AjaxControlToolkit.dll file to the Ajax Control Toolkit tab.

On the Start menu, click Computer.

In the Computer window, navigate to C:\Program Files\ASP.NET Ajax


Library\WebForms\Debug, and then drag the AjaxControlToolkit.dll file to the Ajax Control
Toolkit tab of the Toolbox.

Note: You can view the added Toolbox items in the Ajax Control Toolkit tab. If you cannot view the
items, right-click in the Ajax Control Toolkit tab, click Reset Toolbox, and then drag the
AjaxControlToolkit.dll file to the Ajax Control Toolkit tab of the Toolbox.
7.

8.

Add a Label and a Button control to the AjaxExtenderControl.aspx Web form.

In Toolbox, under Standard, double-click the Label control.

In Toolbox, under Standard, double-click the Button control.

In the AjaxExtenderControl.aspx window, double-click the Button control.

Create a Click event handler for the Button control, and set the Text property of the label to the
string, Button click occurred.

In the AjaxExtenderControl.aspx.vb or AjaxExtenderControl.aspx.cs code-behind window, in the


event handler, add the code to set the Text property of the Label1.Text to the string Button
click occurred.
[Visual Basic]
Label1.Text = Button click occurred
[Visual C#]
Label1.Text = Button click occurred;

9.

Save the changes, and view the AjaxExtenderControl.aspx Web Form in the browser.

On the File menu of Visual Studio 2010, click Save All.

In AjaxExtenderControl Microsoft Visual Studio window, click AjaxExtenderControl.aspx,


right-click anywhere, and then click View in Browser.

10. Test the Button control, and verify that the text of the label changes.

In the http://localhost:49158/AjaxExtenderControl
/AjaxExtenderControl.aspx - Windows Internet Explorer window, click Button.

Note: Verify that the text of the label changes to Button click occurred.
11. Close Internet Explorer.

In the http://localhost:49158/AjaxExtenderControl
/AjaxExtenderControl.aspx - Windows Internet Explorer window, click the Close button.

12. Add a ScriptManager control at the top of the form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-37

In Toolbox, on the AJAX Extensions tab, drag a ScriptManager onto the top of the form.

13. Add a ConfirmButtonExtender control onto the Button1 control.

In Toolbox, on the Ajax Control Toolkit tab, drag the ConfirmButtonExtender control onto the
Button1 control.

14. Set the ConfirmText property of the ConfirmButtonExtender control to Continue?.

In the Properties window, click Button1_ConfirmButtonExtender from the drop-down list.

In the Properties window, set the ConfirmText property of the ConfirmButtonExtender control
to Continue?.

15. Save the changes, and view the AjaxExtenderControl.aspx Web Form in the browser.

On the File menu of Visual Studio 2010, click Save AjaxExtenderControl.aspx.

In the AjaxExtenderControl.aspx window, right-click anywhere, and then click View in Browser.

16. Test the Button control, and verify that the confirmation message box appears.

In the http://localhost:49158/AjaxExtenderControl
/AjaxExtenderControl.aspx - Windows Internet Explorer window, click Button.

In the Message from webpage message box, click OK.

In the AjaxExtenderControl Microsoft Visual Studio window, click the Close button.

In the http://localhost:49158/AjaxExtenderControl
/AjaxExtenderControl.aspx - Windows Internet Explorer window, click the Close button.

In the Explorer window, click Close button.

Note: Verify that the text of the label changes to Button click occurred.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-38

Introduction to Web Development with Microsoft Visual Studio 2010

Lab: Creating a Microsoft ASP.NET Ajax-Enabled Web


Forms Application

Note: You can perform tasks in this lab either by using 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.

Introduction
In this lab, you will implement partial-page updates by using ASP.NET Ajax, create a modal dialog, and
customize Dynamic Data field templates by using Ajax server controls. In addition, you will display
progress when updating a page with partial rendering.

Objectives
After completing this lab, you will be able to:

Implement partial-page updates by using ASP.NET Ajax.

Display a modal dialog.

Display a client-side controlled Calendar.

Display progress when updating a page with partial rendering.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-39

Lab Scenario

You are a developer at Contoso, Ltd, which is a large organization with a global customer base. Your
organization uses.NET applications to create, customize, and manage its customer information.
You are assigned the task of improving the responsiveness of the Web application user interface. You also
need to avoid full-page updates where possible, and display a message when performing a partial update.
For this purpose, you need to implement ASP.NET Ajax in the Customer Management application. You
also need to ensure that partial page updates are possible without writing any client-side coding. In
addition, you need to create a modal About box, add a client-side controlled Calendar control to a
Dynamic Data field template user control, and add a progress indicator to the ImportCountries Web Form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-40

Introduction to Web Development with Microsoft Visual Studio 2010

Section 1: Visual Basic


Exercise 1: Creating a Modal About Box
The main tasks for this exercise are as follows:
1.

Open an existing Web site.

2.

Add a new Web Form.

3.

Add a reference to the Ajax Control Toolkit assembly.

4.

Register the Ajax Toolkit assembly, namespace, and TagPrefix.

5.

Change the ScriptManager control in the master page.

6.

Add the ScriptManagerProxy control.

7.

Add the HTML and UI controls.

8.

Add the event handler and code.

9.

Map navigation to the About Web Form.

10. Test the modal About box.

Task 1: Open an existing Web site

Log on to the 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\M11\VB folder.

Task 2: Add a new Web Form

Add a new Web Form named About.aspx, based on the master page Site.master.

Change the ID property of the Content control to AboutContent.


<asp:Content ID="AboutContent" ContentPlaceHolderID="MainContentPlaceHolder"
Runat="Server">

Task 3: Add a reference to the Ajax Control Toolkit assembly

Add a reference to the C:\Program Files\ASP.NET Ajax Library


\WebForms\Debug\AjaxControlToolkit.dll assembly.

Task 4: Register the Ajax Toolkit assembly, namespace, and TagPrefix

Add a Register directive to the web.config file by using the following attribute values:

assembly: AjaxControlToolkit

namespace: AjaxControlToolkit

tagPrefix: ajaxToolKit

<pages>
<controls>
<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"
tagPrefix="ajaxToolKit" />
</controls>
</pages>

Save and close the web.config file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-41

Task 5: Change the ScriptManager control in the master page

Open the Site.master master page in Source view.

Locate the ScriptManager control.


<asp:ScriptManager ID="MainScriptManager" runat="server" />

Change the ScriptManager control to a ToolkitScriptManager.


<ajaxToolKit:ToolkitScriptManager ID="MainScriptManager" runat="server" />

Save the Site.master master page.

Close the Site.master master page.

Task 6: Add the ScriptManagerProxy control

Add a ScriptManagerProxy control named AboutScriptManagerProxy, to the AboutContent


control.
<asp:ScriptManagerProxy runat="server" ID="AboutScriptManagerProxy" />

Task 7: Add the HTML and UI controls

Append a Panel control named AboutPanel, to the Content control. The panel can be made
invisible by using an inline style of display: none.
<asp:Panel ID="AboutPanel" runat="server" Style="display: none">
</asp:Panel>

Add an UpdatePanel control named AboutUpdatePanel, with an empty ContentTemplate


element, to the AboutPanel control.
<asp:UpdatePanel ID="AboutUpdatePanel" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>

Add a Panel control named AboutPopupPanel, with a cascading style sheet (CSS) class of
aboutPopupPanel, to the ContentTemplate element in the AboutUpdatePanel control.
<asp:Panel runat="server" ID="AboutPopupPanel" CssClass="aboutPopupPanel">
</asp:Panel>

Add the following HTML tags and text within the AboutPopupPanel control.
<br />
&nbsp;<b>About Contoso Customer Management</b>&nbsp;<br />
<br />
&nbsp;Copyright 2010 by Contoso&nbsp;<br />
<br />

Append a Button control named ShowModalButton, with a CSS class of displayNone, to the
AboutPopupPanel control.
<asp:Button ID="ShowModalButton" runat="server" CssClass="displayNone" />

Append a ModalPopupExtender control named AboutModalPopupExtender, with the following


attribute values to the AboutPopupPanel control:

TargetControlID: ShowModalButton

PopupControlID: AboutPanel

CancelControlID: CloseButton

BackgroundCssClass: modalPopup

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-42

Introduction to Web Development with Microsoft Visual Studio 2010

<ajaxToolKit:ModalPopupExtender ID="AboutModalPopupExtender" runat="server"


TargetControlID="ShowModalButton"
PopupControlID="AboutPanel" CancelControlID="CloseButton"
BackgroundCssClass="modalPopup" />

Append a Button control named CloseButton, which does not trigger validation, set the OnClick
event to CloseButton_Click, set the Text property to Close, and add two HTML line break elements
to the AboutPopupPanel control.
<asp:Button ID="CloseButton" runat="server" CausesValidation="False"
OnClick="CloseButton_Click" Text="Close" />
<br />
<br />

Add the following styles to the Styles/Site.css stylesheet.


div.aboutPopupPanel
{
background-color: White;
text-align: center;
border: 2px solid Black;
}
.modalPopup
{
position: relative;
background-color: Gray;
-ms-filter: alpha(opacity=70);
z-index: 1;
}
.displayNone
{
display: none;
}

Save and close the Site.css file.

Task 8: Add the event handler and code

View the code-behind file of the About.aspx Web Form.

Show the AboutModalPopupExtender control in the Page.Load event.


Protected Sub CloseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles CloseButton.Click
' Close about box
AboutModalPopupExtender.Hide()
End Sub

Hide the AboutModalPopupExtender control in the CloseButton_Click event handler.


Protected Sub CloseButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles CloseButton.Click
' Close about box
AboutModalPopupExtender.Hide()
End Sub

Task 9: Map navigation to the About Web Form

Open the web.sitemap file.

Add an About menu command to the Help menu, making it use the About Web Form, by adding a
new siteMapNode within the Help siteMapNode.
<siteMapNode title="About" description="" url="~/About.aspx" />

Save and close the web.sitemap file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-43

Task 10: Test the modal About box

Build the solution.

Run the CustomerManagement Web application.

Close the About box.

Show the About box, using the menu.

Close the About box.

Close the CustomerManagement Web application.

Close the About.aspx.vb code file.

Close the About Web Form.

Results: After completing this exercise, you will have added a new Web Form content page, and
included a ScriptManagerProxy, two Panel controls, one UpdatePanel control, and a
ModalPopupExtender control to the Web Form. In addition, you will have added event handlers and
code to create a modal About box, and then tested the About box.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-44

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 2: Customizing Dynamic Data Field Templates with Ajax Server


Controls
The main tasks for this exercise are as follows:
1.

Add the CalendarExtender control to the DateTime_Edit field template.

2.

Test the DateTime_Edit field template.

Task 1: Add the CalendarExtender control to the DateTime_Edit field template

Open the DateTime_Edit.ascx user control Dynamic Data field template in the Source view.

Add a CalendarExtender control named DateTimeEditCalendarExtender, to the user control by


using the following attribute values:

TargetControlID: TextBox1

PopupPosition: Right
<ajaxToolKit:CalendarExtender ID="DateTimeEditCalendarExtender" runat="server"
TargetControlID="TextBox1" PopupPosition="Right" />

Save and close the DateTime_Edit.ascx user control.

Task 2: Test the DateTime_Edit field template

Build the solution.

Run the CustomerManagement Web application.

Test the CalendarExtender control by adding a new entry to the Customers table, click the
ModifiedDate box, and then select a date from the calendar.

Cancel the new customer entry.

Close the CustomerManagement Web application.

Results: After completing this exercise, you will have added a CalendarExtender control to the
dynamic data DateTime_Edit field template user control, and tested the template.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-45

Exercise 3: Adding the Country Import Progress Indicator


The main tasks for this exercise are as follows:
1.

Add the ScriptManagerProxy control.

2.

Add the HTML and UI controls.

3.

Test the update progress.

Task 1: Add the ScriptManagerProxy control

Open the ImportCountries Web Form in the Source view.

Rename the Content control from Content1 to ImportCountriesContent.

Add a ScriptManagerProxy control named ImportCountriesScriptManagerProxy, to the Content


control.
<asp:ScriptManagerProxy runat="server" ID="ImportCountriesScriptManagerProxy" />

Task 2: Add the HTML and UI controls

Add an UpdatePanel control named ImportCountriesUpdatePanel, to the


ImportCountriesContent control, with an empty ContentTemplate element, after the
ImportCountriesScriptManagerProxy control.
<asp:UpdatePanel ID="ImportCountriesUpdatePanel" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>

Move the existing content of the ImportCountriesContent control to the ContentTemplate


element.

Format the document markup.

Add an UpdateProgress control named ImportCountriesUpdateProgress, to the


ImportCountriesContent control, after the ImportCountriesScriptManagerProxy control, by using
the following attribute values:

AssociatedUpdatePanelID: ImportCountriesUpdatePanel

DisplayAfter: 0

Add an opening and a closing ProgressTemplate tag with the text, Processing... to the
ImportCountriesUpdateProgress control.

Save and close the ImportCountries.aspx Web Form.

Task 3: Test the update progress

Build the solution.

Debug the application.

Filter the countries

Note: Notice that the text, Processing..., displays in the upper-left corner of the Web site for a short
period of time.

Task 4: Turn off the virtual machine and revert the changes

Turn off the 10267A-GEN-DEV virtual machine.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-46

Introduction to Web Development with Microsoft Visual Studio 2010

Revert the changes made to the 10267A-GEN-DEV virtual machine.

Results: After completing this exercise, you will have added a ScriptManagerProxy, an UpdatePanel,
and an UpdateProgress control, and tested the update progress of the ImportCountries Web form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-47

Section 2: Visual C#
Exercise 1: Creating a Modal About Box
The main tasks for this exercise are as follows:
1.

Open an existing Web site.

2.

Add a new Web Form.

3.

Add a reference to the Ajax Control Toolkit assembly.

4.

Register the Ajax Toolkit assembly, namespace, and TagPrefix.

5.

Change the ScriptManager control in the master page.

6.

Add the ScriptManagerProxy control.

7.

Add the HTML and UI controls.

8.

Add the event handler and code.

9.

Map navigation to the About Web Form.

10. Test the modal About box.

Task 1: Open an existing Web site

Log on to the 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\M11\CS folder.

Task 2: Add a new Web Form

Add a new Web Form named About.aspx, based on the master page, Site.master.

Change the ID property of the Content control to AboutContent.


<asp:Content ID="AboutContent" ContentPlaceHolderID="MainContentPlaceHolder"
Runat="Server">

Task 3: Add a reference to the Ajax Control Toolkit assembly

Add a reference to the C:\Program Files\ASP.NET Ajax Library


\WebForms\Debug\AjaxControlToolkit.dll assembly.

Task 4: Register the Ajax Toolkit assembly, namespace, and TagPrefix

Add a Register directive to the web.config file by using the following attribute values:

assembly: AjaxControlToolkit

namespace: AjaxControlToolkit

tagPrefix: ajaxToolKit

<pages>
<controls>
<add assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"
tagPrefix="ajaxToolKit" />
</controls>
</pages>

Save and close the web.config file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-48

Introduction to Web Development with Microsoft Visual Studio 2010

Task 5: Change the ScriptManager control in the master page

Open the Site.master master page in Source view.

Locate the ScriptManager control.


<asp:ScriptManager ID="MainScriptManager" runat="server" />

Change the ScriptManager control to a ToolkitScriptManager.


<ajaxToolKit:ToolkitScriptManager ID="MainScriptManager" runat="server" />

Save the Site.master master page.

Close the Site.master master page.

Task 6: Add the ScriptManagerProxy control

Add a ScriptManagerProxy control named AboutScriptManagerProxy, to the AboutContent


control.
<asp:ScriptManagerProxy runat="server" ID="AboutScriptManagerProxy" />

Task 7: Add the HTML and UI controls

Append a Panel control named AboutPanel, to the Content control. The panel can be made
invisible by using an inline style of display: none.
<asp:Panel ID="AboutPanel" runat="server" Style="display: none">
</asp:Panel>

Add an UpdatePanel control named AboutUpdatePanel, with an empty ContentTemplate element


to the AboutPanel control.
<asp:UpdatePanel ID="AboutUpdatePanel" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>

Add a Panel control named AboutPopupPanel, with a cascading style sheet (CSS) class of
aboutPopupPanel, to the ContentTemplate element in the AboutUpdatePanel control.
<asp:Panel runat="server" ID="AboutPopupPanel" CssClass="aboutPopupPanel">
</asp:Panel>

Add the following HTML tags and text within the AboutPopupPanel control.
<br />
&nbsp;<b>About Contoso Customer Management</b>&nbsp;<br />
<br />
&nbsp;Copyright 2010 by Contoso&nbsp;<br />
<br />

Append a Button control named ShowModalButton, with a CSS class of displayNone to the
AboutPopupPanel control.
<asp:Button ID="ShowModalButton" runat="server" CssClass="displayNone" />

Append a ModalPopupExtender control named AboutModalPopupExtender, with the following


attribute values to the AboutPopupPanel control:

TargetControlID: ShowModalButton

PopupControlID: AboutPanel

CancelControlID: CloseButton

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-49

BackgroundCssClass: modalPopup

<ajaxToolKit:ModalPopupExtender ID="AboutModalPopupExtender" runat="server"


TargetControlID="ShowModalButton"
PopupControlID="AboutPanel" CancelControlID="CloseButton"
BackgroundCssClass="modalPopup" />

Append a Button control named CloseButton, which does not trigger validation and with the
OnClick event set to CloseButton_Click and the Text property set to Close, and two HTML line
break elements to the AboutPopupPanel control.
<asp:Button ID="CloseButton" runat="server" CausesValidation="False"
OnClick="CloseButton_Click" Text="Close" />
<br />
<br />

Add the following styles to the Styles/Site.css stylesheet.


div.aboutPopupPanel
{
background-color: White;
text-align: center;
border: 2px solid Black;
}
.modalPopup
{
position: relative;
background-color: Gray;
-ms-filter: alpha(opacity=70);
z-index: 1;
}
.displayNone
{
display: none;
}

Save and close the Site.css file.

Task 8: Add the event handler and code

View the code-behind file of the About.aspx Web Form.

Show the AboutModalPopupExtender control in the Page.Load event.


// Show about box
AboutModalPopupExtender.Show();

Hide the AboutModalPopupExtender control in the CloseButton_Click event handler.


protected void CloseButton_Click(object sender, EventArgs e)
{
// Close about box
AboutModalPopupExtender.Hide();
}

Task 9: Map navigation to the About Web Form

Open the web.sitemap file.

Add an About menu command to the Help menu, making it use the About Web Form, by adding a
new siteMapNode within the Help siteMapNode.
<siteMapNode title="About" description="" url="~/About.aspx" />

Save and close the web.sitemap file.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-50

Introduction to Web Development with Microsoft Visual Studio 2010

Task 10: Test the modal About box

Build the solution.

Run the CustomerManagement Web application.

Close the About box.

Show the About box using the menu.

Close the About box.

Close the CustomerManagement Web application.

Close the About.aspx.cs code file.

Close the About Web Form.

Results: After completing this exercise, you will have added a new Web Form content page, and
included a ScriptManagerProxy, two Panel controls, one UpdatePanel control, and a
ModalPopupExtender control to the Web Form. In addition, you will have added event handlers and
code to create a modal About box, and then tested the About box.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-51

Exercise 2: Customizing Dynamic Data Field Templates with Ajax Server


Controls
The main tasks for this exercise are as follows:
1.

Add the CalendarExtender control to the DateTime_Edit field template.

2.

Test the DateTime_Edit field template.

Task 1: Add the CalendarExtender control to the DateTime_Edit field template

Open the DateTime_Edit.ascx user control Dynamic Data field template in the Source view.

Add a CalendarExtender control named DateTimeEditCalendarExtender, to the user control by


using the following attribute values:

TargetControlID: TextBox1

PopupPosition: Right
<ajaxToolKit:CalendarExtender ID="DateTimeEditCalendarExtender" runat="server"
TargetControlID="TextBox1" PopupPosition="Right" />

Save and close the DateTime_Edit.ascx user control.

Task 2: Test the DateTime_Edit field template

Build the solution.

Run the CustomerManagement Web application.

Test the CalendarExtender control by adding a new entry to the Customers table, click the
ModifiedDate box, and then select a date from the calendar.

Cancel the new customer entry.

Close the CustomerManagement Web application.

Results: After completing this exercise, you will have added a CalendarExtender control to the
dynamic data DateTime_Edit field template user control and tested the template.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-52

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Adding the Country Import Progress Indicator


The main tasks for this exercise are as follows:
1.

Add the ScriptManagerProxy control.

2.

Add the HTML and UI controls.

3.

Test the update progress.

Task 1: Add the ScriptManagerProxy control

Open the ImportCountries Web Form in the Source view.

Rename the Content control from Content1 to ImportCountriesContent.

Add a ScriptManagerProxy control named ImportCountriesScriptManagerProxy, to the Content


control.
<asp:ScriptManagerProxy runat="server" ID="ImportCountriesScriptManagerProxy" />

Task 2: Add the HTML and UI controls

Add an UpdatePanel control named ImportCountriesUpdatePanel, to the


ImportCountriesContent control, with an empty ContentTemplate element, after the
ImportCountriesScriptManagerProxy control.
<asp:UpdatePanel ID="ImportCountriesUpdatePanel" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>

Move the existing content of the ImportCountriesContent control to the ContentTemplate


element.

Format the document markup.

Add an UpdateProgress control named ImportCountriesUpdateProgress, to the


ImportCountriesContent control, after the ImportCountriesScriptManagerProxy control by using
the following attribute values:

AssociatedUpdatePanelID: ImportCountriesUpdatePanel

DisplayAfter: 0

Add an opening and a closing ProgressTemplate tag with the text, Processing... to the
ImportCountriesUpdateProgress control.

Save and close the ImportCountries.aspx Web Form.

Task 3: Test the update progress

Build the solution.

Debug the application.

Filter the countries.

Note: Notice that the text, Processing..., displays in the upper-left corner of the Web site for a short
period of time.

Task 4: Turn off the virtual machine and revert the changes

Turn off the 10267A-GEN-DEV virtual machine.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-53

Revert the changes made to the 10267A-GEN-DEV virtual machine.

Results: After completing this exercise, you will have added a ScriptManagerProxy, an UpdatePanel,
and an UpdateProgress control, and tested the update progress of the ImportCountries Web form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-54

Introduction to Web Development with Microsoft Visual Studio 2010

Lab Review

Review Questions and Answers


1.

To implement partial-page rendering, what controls should you use?

2.

What is the prerequisite step to use a control from the Ajax Control Toolkit?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Creating a Microsoft ASP.NET Ajax-enabled Web Forms Application

11-55

Module Review and Takeaways

Review Questions and Answers


1.

What is the design goal of ASP.NET Ajax?

2.

What features does the ScriptManager control provide?

3.

How can you use the Ajax Control Toolkit to enhance your applications?

Real-World Issues and Scenarios


1.

You need to implement client-side functionality that is not provided by the standard ASP.NET Web
server controls. What is the easiest way to do this?
Download and use the Ajax Control Toolkit.

2.

You do not have the experience of a client-side developer, but you have been asked to implement
asynchronous updates to a Web Form. How do you do this?
You add an UpdatePanel to the Web Form, and place the controls and elements that should be
updated asynchronously in the UpdatePanel control.

Best Practices
Mention some best practices in the context of your own business situations.

Keep in mind that even if you implement asynchronous event processing, and thus create a
responsive user interface for your users, the load on the Web server is the same. This means that each
time an asynchronous callback is made, the entire page from which the callback is initiated must go
through the full page life cycle on the server. This can quickly overburden the server if you are not
careful with the amount of asynchronous callbacks the application uses.

The UpdatePanel control should generally only be used with parts of a page, not the entire page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

11-56

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-1

Module 12
Consuming Microsoft Windows Communication
Foundation Services
Contents:
Lesson 1: Overview of Windows Communication Foundation Services

12-3

Lesson 2: Calling Windows Communication Foundation Services

12-13

Lesson 3: Working with WCF Data Services

12-23

Lab: Consuming Windows Communication Foundation Services

12-36

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-2

Introduction to Web Development with Microsoft Visual Studio 2010

Module Overview

Making code functionality available across a disconnected network such as the Internet, differs from
making that functionality available in a class or a component, because potential users do not have and
should not have access to your code, for obvious reasons. There is a way to make the same functionality in
your classes or components available, without giving the userssuch as partners, customers, and
vendorsfull access to your code. If you need to keep the communication secure, you can create a frontend that exposes the functionality in a non-intrusive manner, and in a manner that is accessible to
everyone on the network by using the HTTP protocol or Secure HTTP (HTTPS). However, for many
companies, browsing data-driven Web pages does not adequately satisfy their business requirements.
Programmable units of logic and functionality that directly link organizations, applications, and services
are a better solution. Microsoft Windows Communication Foundation (WCF) services provide this direct
linking of applications. Using WCF services, you can expand the functionality that you want to offer to
users.
In this module, you will learn how to call a WCF service directly by using a proxy from a Web application.
In addition, you will learn how to work with WCF Data Services to directly expose data over the Web,
making it possible to automatically query the same data, even from a browser.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-3

Lesson 1

Overview of Windows Communication Foundation


Services

One of the challenges that you may encounter when you create feature-rich Web sites is application
integration. You often have to combine several applications into a single, easy-to-use solution. The
problem with this is that the applications that you want to combine may be on a variety of platforms, and
each platform may run a different operating system. The applications may also use several different
programming languages.
With the move to a service-oriented architecture (SOA), software development has changed, because SOA
services are distinct software units of abstraction. Today it is becoming more typical for applications to
interact through services.
To appeal to a wide audience, services benefits must be reflected in the tools and technologies that
developers use. WCF is designed to address these requirements.
In this lesson, you will learn the key features of WCF, and the purpose of WCF services.

Lesson Objectives
After completing this lesson, you will be able to:

Describe WCF.

Describe WCF services.

Describe the purpose of using WCF services.

Describe various uses of WCF services.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-4

Introduction to Web Development with Microsoft Visual Studio 2010

What Is Windows Communication Foundation?

Key Points
The global acceptance of Web serviceswhich includes standard protocols for application-to-application
communicationhas changed software development. For example, the functions that Web services now
provide include security, distributed transaction coordination, and reliable communication. The benefits of
the changes in Web services should be reflected in the tools and technologies that developers use. This is
why Microsoft created WCF, which is designed to offer a manageable approach to distributed computing,
interoperability, and direct support for service orientation.
WCF is a part of the Microsoft .NET Framework that provides a unified programming model for rapidly
building service-oriented applications that communicate across the Web and the enterprise. WCF is an
integration of older .NET Framework technologies such as XML Web services, .NET Framework Remoting,
and Microsoft .NET Enterprise Services, into a single service-oriented programming model.
WCF simplifies the development of connected applications through a new service-oriented programming
model that supports many styles of distributed application development by providing a layered
architecture. At its base, the WCF channel architecture provides asynchronous, untyped message-passing
primitives. Built on top of this base are protocol facilities for secure, reliable, transacted data exchange,
and a broad choice of transport and encoding options.
The typed programming modelalso known as the service modelfeatures straightforward mapping of
XML Web services concepts to those of the .NET Framework common language runtime (CLR), including
flexible and extensible mapping of messages to service implementations in languages such as Microsoft
Visual Basic or Microsoft Visual C#.
With WCF, you can build secure, reliable, and transacted solutions that integrate across platforms, and
interoperate with your existing investments. Using WCF, you can send data as asynchronous messages
from one service endpoint to another. A service endpoint can be part of a continuously available service
that is hosted by Internet Information Services (IIS), or it can be a service hosted in an application. An
endpoint can be a client of a service that requests data from a service endpoint. The messages can be as

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-5

simple as a single character or word sent as XML, or as complex as a stream of binary data. This module
covers IIS-hosted WCF services.

Interoperability with Applications Built on Other Technologies


While WCF introduces a new development environment for distributed applications, it is designed to
interoperate well with non-WCF applications, interoperate with other platforms, and interoperate with the
Microsoft technologies that preceded WCF.

Interoperability with Other XML Web Services Platforms


Corporations today typically have systems and applications that they have purchased from many
suppliers. Often, communication is required with various other software applications that are written in
various languages, and are running on various operating systems.
Because the fundamental communication mechanism in WCF is Simple Object Access Protocol (SOAP)based XML Web services, WCF-based applications can communicate with other software running in a
variety of contexts:

WCF-based applications that are running in a different process on the same Windows-based
computer.

WCF-based applications that are running on another Windows-based computer.

Applications that are built on other technologies, such as Java 2 Enterprise Edition (J2EE) application
servers that support standard XML Web services.

To allow more than just basic communication, WCF implements XML Web services technologies as
defined by the WS-* specifications.
WCF implements interoperable XML Web services complete with cross-platform security, reliability,
transactions, and other services.

Interoperability with Microsoft Technologies


Many Microsoft customers have made significant investments in the .NET Framework technologies
included with WCF. Protecting those .NET Framework investments is a fundamental goal of the WCF
designers. Installing WCF does not break existing technology, so organizations do not need to change
existing applications to use it.
Question: Which three main technologies does WCF replace?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-6

Introduction to Web Development with Microsoft Visual Studio 2010

What Is a WCF Service?

Key Points
A WCF service is an application that is delivered as a service that can be integrated with other WCF
services by using Internet standards such as HTTP and XML, and other standard protocols, including
Transmission Control Protocol (TCP).
WCF services are similar to components, because they represent black-box functionality that you can use
to add features to a Web Form, Windows Form, or even another WCF service, without worrying about
how the supporting service is implemented.

Application-to-Application Communication Across the Internet


WCF services interact directly with other applications across any disconnected network, such as the
Internet. As a result, WCF services do not have user interfaces (UIs); instead, WCF services provide
standard, defined interfacescalled contractswhich describe the services provided.
A WCF service can be used internally by a single application, or externally by many applications that
access it through a network such as the Internet. There are many benefits to using WCF servicesfor both
consumers and developersincluding programming language, protocol, and platform independence.

Programming Language independence


You can access a WCF service from any .NET Framework-based programming language, such as Visual
Basic or Visual C#. Therefore, because of this flexibility, you do not have to learn a new programming
language every time you want to use or consume a WCF service.

Protocol Independence
Unlike current component technologies, WCF services do not use protocols that are specific to certain
object models, such as the Distributed Component Object Model (DCOM). WCF services communicate by
using standard Web protocols and data formats such as HTTP, XML, and SOAP. Any server that supports
these Web standards can access or host WCF services.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-7

Platform Independence
Because WCF services are accessed by using a standard interface, they enable disparate systems to work
together. Servers that can support Web Forms can also support WCF services.

Multiple Message Patterns


Messages are exchanged in one of several patterns. The most common pattern is the request/reply
pattern, where one endpoint requests data from a second endpoint, and the second endpoint replies.
There are other patterns, such as a one-way message in which a single endpoint sends a message without
any expectation of a reply. A more complex pattern is the duplex exchange pattern, where two endpoints
establish a connection, and then send data back and forth, similar to an instant messaging program.

Service Metadata
WCF supports publishing service metadata using formats that are specified in industry standards, such as
Web Services Description Language (WSDL), XML Schema, and WS-Policy. This metadata can be used to
automatically generate and configure clients for accessing WCF services. Metadata can be published over
HTTP and HTTPS, or using the Web Service Metadata Exchange standard.

Data Contracts
Because WCF is built using the .NET Framework, it also includes code-friendly methods of supplying the
contracts that you want to enforce. One of the universal types of contracts is the data contract. As you
code your service using Visual Basic or Visual C#, the easiest way to handle data is by creating classes that
represent a data entity with properties that belong to the data entity. WCF includes a comprehensive
system for working with data in this manner.
Question: How do WCF services help you to make the application platform and technology independent?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-8

Introduction to Web Development with Microsoft Visual Studio 2010

WCF Service Communication

Key Points
All communication with a WCF service occurs through the endpoints of the service. An endpoint is what
provides a client access to the functionality offered by the WCF service. An endpoint consists of four
properties: address, binding, contract, and behaviors.

Endpoint Structure
Each endpoint consists of the properties that are listed in the following table.
Endpoint property

Description

Address

Uniquely identifies the endpoint, and tells potential consumers of the service
where it is located. It is represented in the WCF object model by the
EndpointAddress class. An EndpointAddress class contains:
A Uri property, which represents the address of the service, an Identity
property, which represents the security identity of the service and a
collection of optional message headers.
The optional message headers are used to provide additional and more
detailed addressing information to identify or interact with the endpoint.

Binding

Specifies how to communicate with the endpoint. This includes:


The transport protocol to use, such as HTTP or TCP.
The encoding to use for the messages, such as binary or text.
The necessary security requirements, such as SSL.

Contract

Outlines what functionality the endpoint exposes to the client. A contract


specifies:
What operations can be called by a client.
The form of the message.
The type of input parameters or data required to call the operation.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

Endpoint property

Description

Behaviors

12-9

What type of processing or response message the client can expect.

Customizes the local behavior of the service endpoint by participating in the


process of building a WCF runtime. An example of an endpoint behavior is the
ListenUri property, which allows you to specify a different listening address
than the SOAP or WSDL address.

Question: How does communication with a WCF service occur?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-10

Introduction to Web Development with Microsoft Visual Studio 2010

Uses of WCF Services

Key Points
WCF services enable you to share programming logic and capabilities with numerous Web and
Windows applications, and with applications that run on other platforms. This allows you to use existing
functionality. You can think of a WCF service as a component that can expose its methods through
disparate networks, including the Internet and the Web.
WCF services also use standard Web protocols and the features that are available in Microsoft Visual
Studio 2010. Visual Studio 2010 simplifies the use of WCF services.
The following table lists some uses of WCF services.
WCF service

Description

Authentication services

Provides user authentication.

Weather reports

Provides updated weather reports for selected locations.


For example, a Web site can provide local weather forecasts for a specified
city or area by consuming a weather report WCF service.

Exchange rates

Provides updated exchange rates for all currencies.


For example, a travel Web site can provide exchange rates for likely vacation
destinations by consuming an exchange rates WCF service.

Airfare quotes

Provides updated airfares from one or more airlines.


For example, a travel Web site can offer automatically discounted prices from
preferred airlines by consuming an airfare quotes WCF service.

Stock quotes

Provides updated stock market quotes.


For example, a company can offer to post its own stock price on its Web site
by consuming a stock quotes WCF service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-11

WCF service

Description

Partnering services

Provides business partners with the opportunity to access your services on


their Web site.
For example, convention Web sites can offer hotel registration services.

News headlines

Provides updated news headlines.


For example, a company can post headlines from their business market on its
Web site by consuming a news headline WCF service.

Order tracking

Provides the status of orders by linking existing enterprise resource


management systems to internal and external Web sites.
For example, combining results from internal ERP applications with supplier
and shipping company order tracking WCF services would give customers a
complete view of the status of their orders.

Advantages
One of the primary advantages of the WCF services architecture is that it allows programs that are written
in different languages on different platforms to communicate with each other in a standard way.
Whenever you need to expose functionality to anyone that cannot or should not access your code or
components directly, you should consider using a WCF service.
Another reason for WCF services is that other companies expose a lot of functionality this way, and you
can access the functionalitypotentially for free. Regardless of whether you are paying for the service,
you can access the functionality as if you were using your own components or classes.

Example of a WCF Service


A hypothetical travel Web site offers several features that are based on WCF services. In this scenario, the
user enters a destination city name, and the Web Form uses the city name as a parameter in calls to
several WCF services. From the users perspective, this is a sophisticated travel Web site. From a
developer's perspective, the Web site is a graphical interface that combines several WCF services from
unrelated companies.
This Web site provides advantages to both the travel agency and the various WCF service providers:
Advantages for the travel agency include:

The applications that the travel agency can access are not limited by the travel agency developers
programming skills, availability, or subject expertise.
The travel agency does not bear the high maintenance costs of keeping data such as weather reports
or exchange rates up-to-date.
WCF services use the Internet, so the travel agency does not have to create or maintain dedicated
connections to offer the service.
WCF services are independent of language, protocol, and platform, so the travel agency developers
do not have to learn how the WCF service was built and deployed.
Advantages for the WCF service providers:
The WCF service provider may be able to charge the Web site for the use of the service.
A bank can access the customer base of multiple travel agencies, by offering an application such as an
exchange rate calculator as a WCF service.
The WCF service provider does not bear the high cost of developing and marketing a Web site to the
public.
The service providers do not require expensive dedicated connections to offer the service, because
WCF services can use the Internet to communicate.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-12

Introduction to Web Development with Microsoft Visual Studio 2010

The WCF service can be consumed by a wide variety of applications, because WCF services are
independent of language, protocol, and platform.

Question: What is the primary reason for using WCF services?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-13

Lesson 2

Calling Windows Communication Foundation Services

You can access a WCF service from a Web application programmatically by creating a proxy to handle the
call.
In this lesson, you will learn how to create a Service reference proxy for a WCF Service, and learn how to
call a WCF Service method from a Web Form.

Lesson Objectives
After completing this lesson, you will be able to:

Explain how to consume a WCF service.

Explain how to add a Service reference using Visual Studio 2010.

Describe Service Reference files.

Programmatically call a WCF service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-14

Introduction to Web Development with Microsoft Visual Studio 2010

Consuming a Windows Communication Foundation Service

Key Points
A WCF service must be hosted before you can access it. WCF services can be hosted in a number of
different ways, such as by using:

A console application.

A Windows Forms application.

IIS.

A Windows service.

Windows Process Activation Service (WAS).

The console application and Windows Forms application are also referred to as self-hosting options,
because the application must be running for the WCF to be available for consumption. The Window
service option means that the WCF service is running inside a Windows service. The WAS enables you to
host any WCF service, and support any transport inside the IIS model. WAS handles the creation of worker
processes and provides the configuration from the original W3svc.exe.While IIS makes a Web application
or Web service available over the HTTP protocol, WAS makes it available over different protocols,
including HTTP, TCP, and Named Pipes.

Locating a WCF Service


WCF services can be published and registered in a Universal Description, Discovery, and Integration
(UDDI) register, where it can be located or discovered by the potential users. You can also find WCF
services from within Visual Studio 2010, provided the WCF services are part of the current solution. In
summary, you need to know the address of the WCF service to use it. When working with WCF Services
hosted in IIS, this address is a standard URL, such as http://localhost
/CustomerWCF/Customers.svc. Notice the .svc extension, which is mandatory.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-15

Consuming a WCF Service


You can consume WCF services in several ways. If you are using WCF on the client-side, WCF comes with
tools that can generate proxy classes to call WCF services. WCF provides the standards and tools support
primarily through the ServiceModel Metadata Utility Tool, SvcUtil.exe. SvcUtil.exe is used to generate
service model code from metadata documents, and metadata documents from service model code. In
addition, Visual Studio 2010 comes with easy-to-use features to add service references to your projects
and seamlessly generate proxy classes for you.
Essentially, you have the following options:

Retrieve the WSDL from the service, and manually create a proxy to call the service. This is a typical
scenario when you do not have WCF on the client-side.

Use the Add Service Reference dialog box in Visual Studio 2010 to generate a proxy to use in your
client.

Use the SvcUtil.exe command-line tool to generate proxy classes.

Question: What is the name of the command-line tool that is used for generating WCF service proxy
classes?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-16

Introduction to Web Development with Microsoft Visual Studio 2010

Adding a Service Reference by Using Visual Studio 2010

Key Points
To simplify the coding model, applications use a device reference to locally represent each WCF service.
You can add a Service reference to your project by using the Add Service Reference dialog box. The Add
Service Reference dialog box enables you to add references to WCF services and WCF Data Services.
To add a reference to a service that is contained in your solution, in the Add Service Reference dialog
box, click Discover, or if you know the address where the service is hosted, enter the URL in the Address
box, and then click Go. This returns a list of available services. The Services list displays an expandable list
of services that are returned. Each service might contain multiple service contracts and/or endpoints.
When you expand a service in the Services list and select the associated contract, the Operations list
displays a list of operations that are available for the service contract.
When you have located the desired WCF service, selected the appropriate contract and optionally
specified the namespace, click OK. Visual Studio downloads the service description to the local computer,
and then generates a proxy class for the chosen WCF service and contract. The proxy class contains
methods for calling each service method that is exposed in the contract. This class is contained in the local
.wsdl file's code-behind file.
Question: How do you open the Add Service Reference dialog box?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-17

Overview of Service Reference Metadata Files

Key Points
When you add a Service reference to a WCF service, a number of metadata files are added to the
App_WebReferences folder in your Web application root. In the App_WebReferences folder, a subfolder
that is named after the namespace and that is specified at the time the Service reference was added, is the
actual container of the following files.

Reference.svcmap
The Reference.svcmap file is the main reference file that contains references to the metadata files and
code generation operations, as shown in the following markup.
<?xml version="1.0" encoding="utf-8"?>
<ReferenceGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" ID="62879ab4-0459-4bbe-8f8a-f2cdd0acbe2f"
xmlns="urn:schemas-microsoft-com:xml-wcfservicemap">
<ClientOptions>
<GenerateAsynchronousMethods>false</GenerateAsynchronousMethods>
<EnableDataBinding>true</EnableDataBinding>
<ExcludedTypes />
<ImportXmlTypes>false</ImportXmlTypes>
<GenerateInternalTypes>false</GenerateInternalTypes>
<GenerateMessageContracts>false</GenerateMessageContracts>
<NamespaceMappings />
<CollectionMappings />
<GenerateSerializableTypes>true</GenerateSerializableTypes>
<Serializer>Auto</Serializer>
<UseSerializerForFaults>true</UseSerializerForFaults>
<ReferenceAllAssemblies>true</ReferenceAllAssemblies>
<ReferencedAssemblies />
<ReferencedDataContractTypes />
<ServiceContractMappings />
</ClientOptions>
<MetadataSources>
<MetadataSource

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-18

Introduction to Web Development with Microsoft Visual Studio 2010

Address="http://localhost:1112/Services/Customers.svc" Protocol="http"
SourceId="1" />
</MetadataSources>
<Metadata>
<MetadataFile FileName="Orders.wsdl" MetadataType="Wsdl"
ID="7a434a6f-6322-4449-96f8-66477acef937" SourceId="1"
SourceUrl="http://localhost/Orders.svc?wsdl" />
<MetadataFile FileName="Orders.xsd" MetadataType="Schema"
ID="5c4c1e42-26fe-4324-be24-857eb1c1b70a" SourceId="1"
SourceUrl="http://localhost/Orders.svc?xsd=xsd1" />
<MetadataFile FileName="Orders1.xsd" MetadataType="Schema"
ID="ef73a985-3021-45a6-beba-8ff5aeff9e5f" SourceId="1"
SourceUrl="http://localhost/Orders.svc?xsd=xsd0" />
<MetadataFile FileName="Orders.disco" MetadataType="Disco"
ID="5cacad50-604e-4cb6-a1f4-d68cee01a104" SourceId="1"
SourceUrl="http://localhost/Orders.svc?disco" />
<MetadataFile FileName="Orders2.xsd" MetadataType="Schema"
ID="ed769a90-9384-49ec-b76b-a3e8df5016a0" SourceId="1"
SourceUrl="http://localhost/Orders.svc?xsd=xsd2" />
</Metadata>
<Extensions>
<ExtensionFile FileName="configuration91.svcinfo"
Name="configuration91.svcinfo" />
<ExtensionFile FileName="configuration.svcinfo"
Name="configuration.svcinfo" />
</Extensions>
</ReferenceGroup>

The MetadataFile elements point to the .wsdl, .xsd, and .disco files, and the ExtensionFile elements point
to the Configuration91.svcinfo and Configuration.svcinfo files.

.disco
The .disco discovery file contains the contractRef element that links to other documents, including the
WSDL and documentation on the server. The disco files are not used for configuration or proxy
generation.

.wsdl
The .wsdl file contains the WSDL markup for the service.

.xsd
The .xsd files are the XML schema files that are used to describe the schemas used.

configuration.svcinfo and configuration91.svcinfo


The configuration.svcinfo and configuration91.svcinfo files track the configuration added to the project
configuration file, web.config.
Question: Which metadata file is the main reference file?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-19

Demonstration: How to Programmatically Call a WCF Service

Key Points
In this demonstration, you will see how to create a proxy to call a WCF service from a Web Form.

Demonstration Steps
To create a proxy to call a WCF service from a Web Form, you need to perform the following steps:
1.

Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.

2.

Open Microsoft Visual Studio 2010.

3.

4.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Open the Web application and the code-behind file for the Web Form from which you will be calling
the WCF service, or create a new Web site and use the Default Web form of the Web site.

On the File menu of Visual Studio 2010, 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, click ASP.NET Web Site.

In the Web location list, ensure File System is selected, and then click OK.

In Solution Explorer, right-click C:\Users\Admin\Documents\Visual Studio


2010\WebSites\WebSite1\, and then click Add Service Reference.

Enter the URL of the WCF service that you want to access, and create a service reference for the WCF
service.

In the Add Service Reference dialog box, in the Address box, type
http://localhost:1112/Services/Customers.svc, and then click Go.

In the Services list, expand Customers, and then select the ICustomers contract.

Notice the service method that displays in the Operations list, and then click OK.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-20

Introduction to Web Development with Microsoft Visual Studio 2010

5.

6.

Open the Default.aspx Web Form in Source view, remove the existing markup from the
BodyContent Content control, and add a Button and GridView control.

In Solution Explorer, right-click Default.aspx, and then click View Markup.

Select the markup between the opening and closing Content tags for the BodyContent control,
and then press the DELETE key.

In the Default.aspx window, point to Toolbox, expand Standard, and then double-click Button.

In Toolbox, expand Data, and then double-click GridView.

Create an instance of the proxy of the WCF service in the Click event procedure of the Button
control.
[Visual Basic]
Dim customersWcfClient As New ServiceReference1.CustomersClient
[Visual C#]
ServiceReference1.CustomersClient customersWcfClient =
new ServiceReference1.CustomersClient();

In the Default.aspx window, click Design.

In the Default.aspx window, double-click Button.

In the Default.aspx.vb or Default.aspx.cs code window, type the following code in the Click event
procedure of the Button control.
[Visual Basic]
Dim customersWcfClient As New ServiceReference1.CustomersClient
[Visual C#]
ServiceReference1.CustomersClient customersWcfClient =
new ServiceReference1.CustomersClient();

Note: In the code example, ServiceReference1 is the name of the WCF reference, and CustomersClient
is the name of the WCF service.
7.

Import the System.Security.Principal namespace.


[Visual Basic]
Imports System.Security.Principal
[Visual C#]
using System.Security.Principal;

In the Default.aspx.vb or Default.aspx.cs code window, add the following at the top of the code
file.
[Visual Basic]
Imports System.Security.Principal
[Visual C#]
using System.Security.Principal;

8.

Impersonate a user account that can be impersonated to allow access to secure resources from the
WCF service by using Windows credentials.
[Visual Basic]
customersWcfClient.ClientCredentials.Windows.ClientCredential.User
Name = "10267A-GEN-DEV\Student"
customersWcfClient.ClientCredentials.Windows.ClientCredential.Pass

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-21

word = "Pa$$w0rd"
customersWcfClient.ClientCredentials.Windows.AllowedImpersonationL
evel = TokenImpersonationLevel.Impersonation
[Visual C#]
customersWcfClient.ClientCredentials.Windows.ClientCredential.User
Name = "10267A-GEN-DEV\\Student";
customersWcfClient.ClientCredentials.Windows.ClientCredential.Pass
word = "Pa$$w0rd";
customersWcfClient.ClientCredentials.Windows.AllowedImpersonationL
evel = TokenImpersonationLevel.Impersonation;

In the Default.aspx.vb or Default.aspx.cs code window, append the following code to the Click
event procedure of the Button control.
[Visual Basic]
customersWcfClient.ClientCredentials.Windows.ClientCredential.
UserName = "10267A-GEN-DEV\Student"
customersWcfClient.ClientCredentials.Windows.ClientCredential.
Password = "Pa$$w0rd"
customersWcfClient.ClientCredentials.Windows.AllowedImpersonat
ionLevel = TokenImpersonationLevel.Impersonation
[Visual C#]
customersWcfClient.ClientCredentials.Windows.ClientCredential.
UserName = "10267A-GEN-DEV\\Student";
customersWcfClient.ClientCredentials.Windows.ClientCredential.
Password = "Pa$$w0rd";
customersWcfClient.ClientCredentials.Windows.AllowedImpersonat
ionLevel = TokenImpersonationLevel.Impersonation;

9.

Call the GetCountries method of the WCF service, requesting countries starting with the letter D.
[Visual Basic]
GridView1.DataSource = customersWcfClient.GetCountries("D")
GridView1.DataBind()
[Visual C#]
GridView1.DataSource = customersWcfClient.GetCountries("D");
GridView1.DataBind();

In the Default.aspx.vb or Default.aspx.cs code window, append the following code to the Click
event procedure of the Button control.
[Visual Basic]
GridView1.DataSource = customersWcfClient.GetCountries("D")
GridView1.DataBind()
[Visual C#]
GridView1.DataSource = customersWcfClient.GetCountries("D");
GridView1.DataBind();

10. Close the WCF service client.


[Visual Basic]
customersWcfClient.Close()
[Visual C#]
customersWcfClient.Close();

In the Default.aspx.vb or Default.aspx.cs code window, append the following code to the Click
event procedure of the Button control.
[Visual Basic]

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-22

Introduction to Web Development with Microsoft Visual Studio 2010

customersWcfClient.Close()
[Visual C#]
customersWcfClient.Close();

11. Build and run the Microsoft ASP.NET Web application.

In Visual Studio 2010, on the Debug menu, click Start Without Debugging.

In the Windows Internet Explorer window, click Button.

In the http://localhost:49157/WebSite1/Default.aspx - Windows Internet Explorer window and


WebSite1 - Microsoft Visual Studio window, click the Close button.

Note: Verify that the customers' details display on the Web Form by using the WCF service.
Question: What is the default name for the proxy created by using the Add Service Reference dialog
box?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-23

Lesson 3

Working with WCF Data Services

To provide a richer user experience while maintaining ease of deployment, the architecture of Web
applications is changing dramatically. The technological shift towards Asynchronous JavaScript and XML
(Ajax)based frameworks and tools, and the trend for building rich, interactive applications with
applications such as Microsoft Silverlight 4, has changed how presentation, functionality, and data are
delivered to client Web browsers.
In traditional Web applications, to drive interaction, a server-side component renders HTML content with:
presentation aspects such as fonts, colors, and layout; the data or content itself; and client-side code, such
as JavaScript. One key trait of the new architecture for Web applications is that presentation and data are
no longer embedded in the same container and delivered through the same channel.
Ajax-based Web sites serve pages containing presentation and functionality, and then the JavaScript code
that represents the page functionality fetches data separately by using Extensible Markup
Language/Hypertext Transfer Protocol (XMLHTTP). Silverlight applications remove the option of a serverside rendering process that mixes data and code; code to drive the presentation aspects is precompiled
and deployed as a single file on the Web server. After reaching the client Web browser, the code calls
back into the Web server to retrieve the actual data to display within the user interface.
Orthogonal-to-single data source Web applications and their architecturea new class of application
called mashupshas also emerged on the Web. Mashups are front-ends that aggregate and combine
data that is available in pure data form on the Webcurrently most of them are in the form of Really
Simple Syndication (RSS)/Atom feedsand add value on top of the individual data pieces. This
architecture makes it particularly interesting to talk about data services; the services that applications use
to find and manipulate data on the Web regardless of the presentation technology used in the user
interface, or whether the front-end is hosted on the same site as the server hosting the data.
In this lesson, you will learn how to serve data to a mashup application by using WCF Data Services.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-24

Introduction to Web Development with Microsoft Visual Studio 2010

Lesson Objectives
After completing this lesson, you will be able to:

Describe WCF Data Services.

Create WCF Data Services.

Explain how to add WCF Data Services to an existing Web site by using Visual Studio 2010.

Examine a WCF Data Service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-25

Overview of WCF Data Services

Key Points
The WCF Data Services framework consists of a combination of patterns and libraries that enable the
creation and consumption of data services for the Web. The goal of the WCF Data Services framework is
to facilitate the creation of flexible data services that are naturally integrated with the Web. WCF Data
Services use Uniform Resource Identifiers (URIs) to point to pieces of data, and simple, well-known
formats to represent that data, such as JavaScript Object Notation (JSON) and ATOM, an XML-based feed
format. This results in the data service being surfaced as a representational state transfer (REST)-style
resource collection that can be addressed with URIs, and that agents can interact with, by using standard
HTTP verbs such as GET, POST, PUT, or DELETE.
In order for the system to understand and use semantics over the data that it exposes, WCF Data Services
models the data that is exposed through the data service, by using an Entity Data Model (EDM). The EDM
organizes the data in the form of instances of entities, and associations between them.
For relational data, WCF Data Services supports exposing an EDM model that is created by using the
Microsoft ADO.NET Entity framework. To use nonrelational data sources or additional database access
technologies such as LINQ to SQL, a mechanism is provided that enables any data source to be modeled
as an entity, and exposed as a data service.

Example
For example, a service can be used to track customer data. The URI that represents all Customer entities in
this example service is http://myserver/data.svc
/Customers. In this context, the /Customers part of the URI points to the Customers entity set, which is
the container for Customer instances. It is also possible to point to a single entity by using a URI, such as
http://myserver/data.svc
/Customers('ALFKI'). This URI results in a single Customer entity whose keyas defined in the EDM
schemahas a value of ALFKI. If the Customer entity includes properties, you can address those

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-26

Introduction to Web Development with Microsoft Visual Studio 2010

properties individually. For example, the URI, http://myserver/data.svc/Customers('ALFKI')/ContactName


represents the Contact Name of the Customer entity with key, ALFKI.
Because EDM schemas not only describe the structure of the entity types, but also the associations
between them, the system can use that information to provide a mechanism for association traversal. For
example, if each of the customers in the data service has a set of Sales Orders associated with it, the
http://myserver/data.svc/Customers('ALFKI')/Orders URI would represent the set of Sales Orders
associated with the Customer whose key has a value of ALFKI.
An application can operate on the entities data, and on entities that are related to the target entity. For
example, if you want an application to display a grid with a master-details style, the application needs to
efficiently retrieve both the target Customer, and that customer's orders for display. The
http://myserver/data.svc
/Customers('ALFKI')?$expand=Orders,AlternateContacts URI addresses a single customer, and states that
the customer's orders and alternate contact information should be returned inline in the same response
from the data service.
All of these URIs represent resourcessuch as a customer or the sales orders associated with the
customerwith the key, ALFKI.
In addition to the key-based selection, you can include simple predicates in WCF Data Service URIs. This
enables the representation of sets based on the properties of the entities, such as the set of active sales
orders for the customer with key, ALFKI, which in the WCF Data Service URI form, is
http://myserver/data.svc
/Customers('ALFKI')/Orders?$filter=Active eq true.
You can use the $filter operator in conjunction with string, math, or date functions as shown in
http://myserver/data.svc/Customers('ALFKI')/Orders?$filter=Active eq true and (year(OrderDate) eq 2007)
URI, which represents the set of active orders made in the year 2007 for the customer, ALFKI.
WCF Data Service URIs can also include control information in the query string to adjust how data is
presented to the caller. Common requirements for Web applications include aspects such as being able to
request data in pages, and to sort the data by various properties. For example, the
http://myserver/data.svc
/Customers('ALFKI')/Orders?$filter=Active eq true&$orderby=OrderDate URI lists the same Sales Orders,
but the data is ordered by date.

Format Independent
WCF Data Services uses simple formats to represent data, and supports more than one format to
accommodate as many client agents as possible. Currently, WCF Data Services can represent data in JSON
and Atom Publishing Protocol (AtomPub) formats. The default representation format is AtomPub, and it is
generated by using a fixed mapping of the entity structure to XML elements in AtomPub. Semantics
provided by the EDM schema, are then added to make the information useful.
The WCF Data Services framework also enables the use of regular authentication schemes supported by
the execution environment that hosts a particular data service, including ASP.NET and WCF.

Storage Independent
WCF Data Services expose data regardless of the underlying data source. In general, WCF Data Services
accept an HTTP request for a resource identified by a URI, deserialize the request, and then pass a
representation of that request to a WCF Data Service provider to run the request on the underlying data
store. This separation of the WCF Data Services protocolsuch as URI, payload format, and interaction
modelfrom the data store, enables WCF Data Services to expose data at the level of abstraction

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-27

presented to it by the provider, which may be different from the schema of the underlying store. WCF
Data Services enables you to easily create data services by using the following:

Entity Framework data sources, which expose a conceptual model of data that is stored in relational
databases, including Microsoft SQL Server, Oracle, IBM DB2, and MySql.

Any additional implementation that supports updated semantics for WCF Data Services. This enables
WCF Data Services to expose any data store as REST-based endpoints, regardless of the storage
mechanism.

A significant amount of access to relational databases occurs through stored procedures. WCF Data
Services supports the use of stored procedures in the following ways:

WCF Data Services supports the Entity Framework as a data source, which makes it simple to relate
entities exposed through a data service to stored procedures within a relational database.

Allows use of service operations to relate stored procedures to entities exposed through a WCF Data
Service.

Question: What is the goal of the WCF Data Services framework?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-28

Introduction to Web Development with Microsoft Visual Studio 2010

Creating WCF Data Services

Key Points
The WCF Data Service server framework consists of two halves: an upper-half, and a lower-half. The
upper-half of the framework is the runtime itself. This part is fixed, and it implements URI translation,
Atom/JSON wire formats, and the interaction protocol. This is what makes a WCF Data Service look like a
WCF Data Service. The lower-half of the framework is the data-access layer, which is pluggable.
Communication between layers happens in terms of the IQueryable interface, and a set of conventions to
link CLR graphs into the URI/payload patterns of WCF Data Services.

Selecting a Data Source


The first step in creating a WCF Data Service is to determine the data source to be exposed as a set of
REST-based endpointsyou need to select or create a data access layer. For relational data stored in SQL
Server or other third-party databases, WCF Data Services currently enables you to easily expose a
conceptual model that is created by using the ADO.NET Entity Framework. A mechanism that enables any
data source to be exposed as a WCF Data Service is provided for all other data sources such as an XML
document, a Web service, or application logic layer, or to use additional database access technologies
such as LINQ to SQL.

Creating a Data Service by Using the ADO.NET Entity Framework


WCF Data Services are a specialized form of WCF services. You can host WCF Data Services in various
environments. To create a data service, you must first create a Web project and establish a connection
with the database, which the service will expose. Then, create the data service itself within the Web
application.
The following are the steps to create a WCF Data Service, which is hosted inside an ASP.NET site:
1.

Create a project.

Create an ASP.NET Web Application project or an ASP.NET Web site in Visual Studio 2010, or use
an existing Web application project or Web site.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

2.

Create an EDM representation of your database by using the ADO.NET Entity Framework.

3.

12-29

Assuming that you already have a database that you want to expose as a data service, create an
EDM schema that relates 1:1 with your database by using the Add New Item dialog box and the
ADO.NET Entity Data Model template. The file name extension for ADO.NET EDM is .edmx.

Create a data service.

Create the actual data service by using the Add New Item dialog box and the WCF Data Service
template. The file name extension for WCF Data Service is .svc.
In the service code file, locate the TODO: put your data source class name here comment, and
then add the name of your data class, including a namespace.

4.

Enable access to the data service.

5.

By default, a data service does not expose any resources. For security purposes, access to
resources needs to be explicitly enabled before any resources or associations become accessible.
To enable the read and write access to all resources in the EDM associated with the service, locate
the InitializeService method. Remove the comment from one of the methods on the config
objectsuch as the SetEntitySetAccessRule methodand supply an asterisk (*) as the first
parameter or the name of the entity in your data model, if you do not want to allow access to all
entities.

Test the data service.

Run the Web application or Web site, add the name of the WCF Data Service filesuch as
WebDataService.svc to the URLand then press ENTER. You can see the data returned from the
data source, in an XML format.

Prerequisites for Creating Data Services


To create a data service by using WCF Data Services in your own environment, you must have Visual
Studio 2010. If you use your data service to access data that is stored in a relational database, you will
need a database with updated data access providers, such as SQL Server 2005 or SQL Server 2008. The
ADO.NET Entity Framework runtime and associated tools are included in Visual Studio 2010.
Question: What is the file extension for a WCF Data Service?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-30

Introduction to Web Development with Microsoft Visual Studio 2010

Demonstration: How to Add WCF Data Services to an Existing Web Site

Key Points
In this demonstration, you will see how to create add a WCF Data Service to an existing Web site.

Demonstration Steps
To add WCF Data Services to an existing Web site, perform the following steps:
1.

Log on to 10267A-GEN-DEV as Student, with the password, Pa$$w0rd.

2.

Open Microsoft Visual Studio 2010.

3.

4.

On the Start menu of 10267A-GEN-DEV, point to All Programs, click Microsoft Visual Studio
2010, and then click Microsoft Visual Studio 2010.

Open the CustomerManagement solution from the D:\Demofiles\M12\CS or D:\Demofiles\M12\VB


folder.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project.

In the Open Project dialog box, in the File name box, type either
D:\Demofiles\M12\VB\CustomerManagement.sln or
D:\Demofiles\M12\CS\CustomerManagement.sln, and then click Open.

Add a new WCF Data Service named Countries.

In Solution Explorer, right-click either the D:\Demofiles\M12


\VB\CustomerManagement\ or D:\Demofiles\M12\CS
\CustomerManagement\ Web site, and then click Add New Item.

In the Add New Item D:\Demofiles\M12\VB\CustomerManagement\ or Add New Item


D:\Demofiles\M12\CS\CustomerManagement\ dialog box, in the middle pane, click WCF
Data Service.

In the Name box, type Countries.svc, and then click Add.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

5.

12-31

Add the existing EDM namespace and class name to the declaration of the generic Countries class,
CustomerManagementModel.Entities.
[Visual Basic]
Public Class Countries
Inherits DataService(Of CustomerManagementModel.Entities)
[Visual C#]
public class Countries : DataService<CustomerManagementModel.Entities>

In the App_Code/Countries.vb or App_Code/Countries.cs window, modify the following class


definition code from,
[Visual Basic]
Public Class Countries
' TODO: replace [[class name]] with your data class name
Inherits DataService(Of [[class name]])
[Visual C#]
public class Countries: DataService< /* TODO: put your data source class name here
*/ >

to:
[Visual Basic]
Public Class Countries
Inherits DataService(Of CustomerManagementModel.Entities)
[Visual C#]
public class Countries : DataService<CustomerManagementModel.Entities>

6.

Allow read access to the Countries and Customers entities of the EDM by using the
IDataServiceConfiguration.SetEntitySetAccessRule method in the Shared or static
InitializeService method of the DataService class.
[Visual Basic]
config.SetEntitySetAccessRule("Countries",
EntitySetRights.AllRead)
config.SetEntitySetAccessRule("Customers",
EntitySetRights.AllRead)
[Visual C#]
config.SetEntitySetAccessRule("Countries",
EntitySetRights.AllRead);
config.SetEntitySetAccessRule("Customers",
EntitySetRights.AllRead);

In the App_Code/Countries.vb or App_Code/Countries.cs window, replace the following code of


the class definition,
[Visual Basic]
' TODO: set rules to indicate which entity sets and service
operations are visible, updatable, etc.
' Examples:
' config.SetEntitySetAccessRule("MyEntityset",
EntitySetRights.AllRead)
' config.SetServiceOperationAccessRule("MyServiceOperation",
ServiceOperationRights.All)
[Visual C#]
// TODO: set rules to indicate which entity sets and service
operations are visible, updatable, etc.
// Examples:
// config.SetEntitySetAccessRule("MyEntityset",
EntitySetRights.AllRead);

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-32

Introduction to Web Development with Microsoft Visual Studio 2010

// config.SetServiceOperationAccessRule("MyServiceOperation",
ServiceOperationRights.All);

with:
[Visual Basic]
config.SetEntitySetAccessRule("Countries",
EntitySetRights.AllRead)
config.SetEntitySetAccessRule("Customers",
EntitySetRights.AllRead)
[Visual C#]
config.SetEntitySetAccessRule("Countries",
EntitySetRights.AllRead);
config.SetEntitySetAccessRule("Customers",
EntitySetRights.AllRead);

7.

8.

Save and close the Countries code-behind file.

In the CustomerManagement Microsoft Visual Studio window, on the File menu, click either
Save App_Code/Countries.vb or Save App_Code/Countries.cs.

In the App_Code/Countries.vb or App_Code/Countries.cs window, click the Close button.

Build the solution.

9.

In the CustomerManagement Microsoft Visual Studio window, on the Build menu, click Build
Solution.

View the service in the browser.

In Solution Explorer, right-click Countries.svc, and then click View in Browser.

Note: Notice that the XML returned from the service contains both Countries and Customers entities.
10. View the Countries entity by browsing to the URL
http://localhost:1111/CustomerManagement/Countries.svc/Countries or
http://localhost:1110/CustomerManagement/Countries.svc/Countries.

In the Address bar of Internet Explorer, type http://localhost:1111


/CustomerManagement/Countries.svc/Countries or
http://localhost:1110/CustomerManagement/Countries.svc
/Countries, and then press ENTER.

Note: Notice that the XML returned from the service contains all the Countries from the data model.
Notice how it looks similar to the way Dynamic Data applies routing, by appending the name of the entity
to the URL.
11. View the Customers entity by browsing to the URL
http://localhost:1111/CustomerManagement/Countries.svc/Customers or
http://localhost:1110/CustomerManagement/Countries.svc/Customers.

In the Address bar of Internet Explorer, type


http://localhost:1111/CustomerManagement/Countries.svc
/Customers or http://localhost:1110/CustomerManagement/Countries.svc
/Customers, and then press ENTER.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-33

Note: Notice that the XML returned from the service contains all the Customers from the data model.
12. View the information for the last name, Abercrombie, by browsing to the URL,
http://localhost:1111/CustomerManagement/Countries.svc
/Customers?$filter=LastName eq 'Abercrombie' or
http://localhost:1110/CustomerManagement/Countries.svc
/Customers?$filter=LastName eq 'Abercrombie'.

In the Address bar of Internet Explorer, type


http://localhost:1111/CustomerManagement/Countries.svc
/Customers?$filter=LastName eq 'Abercrombie' or
http://localhost:1110/CustomerManagement/Countries.svc
/Customers?$filter=LastName eq 'Abercrombie', and then press ENTER.

Note: Notice that the XML returned from the service contains a single customer, Kim Abercrombie.
Mention that the $filter operator is used with the LastName column. That column cannot be queried
directly, because it is not the primary key of the entity.
13. View the countries for which the InternetTLD starts with less than B by using the URL,
http://localhost:1111/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B' or
http://localhost:1110/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B'.

In the Address bar of Internet Explorer, type


http://localhost:1111/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B' or
http://localhost:1110/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B', and then press ENTER.

Note: Notice that the XML returned from the service contains all countries for which the InternetTLD
starts with less than B. Mention that the $filter operator is used with the Name column. That column
cannot be queried directly, because it is not the primary key of the entity.
14. Close Internet Explorer.

In the http://localhost:1111/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B' Windows Internet Explorer or
http://localhost:1110/CustomerManagement/Countries.svc
/Countries?$filter=InternetTLD lt 'B' Windows Internet Explorer window, click the Close button.

15. Close Visual Studio 2010.

In the CustomerManagement Microsoft Visual Studio window, click the Close button.

Question: Which template will you use to add a WCF Data Service to a project in Visual Studio 2010?
Answer: You can use the WCF Data Service item template to add a WCF Data Service item to a project in
Visual Studio 2010.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-34

Introduction to Web Development with Microsoft Visual Studio 2010

Additional Reading
For more information about the URI format for addressing WCF Data Services Resources, see
Addressing Resources (WCF Data Services) at
http://go.microsoft.com/fwlink/?LinkID=193102&clcid=0x409.
For more information about WCF Data Services query operators, see Query Operators (WCF Data
Services) at http://go.microsoft.com
/fwlink/?LinkID=193103&clcid=0x409.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-35

Examining a WCF Data Service

Key Points
You can add the WCF Data Service, and then examine Data Service files. The WCF Data Service contains a
markup file and a code file.

Markup File
The WCF Data Service markup file is the Customers.svc file, which is also known as the hosting file for the
WCF Data Service. The Factory attribute should always stay the same. You can change the Service
attribute if you are using an ASP.NET Web application, but not an ASP.NET Web site. The Service attribute
refers to the class that defines the data service.

Code File
The WCF Data Service code file is either App_Code/Customers.vb or App_Code/Customers.cs. The
DataService class is where you add operations and set the access rules for the entities. Locate this class in
the App_Code folder of the Web site root folder when using a WCF Data Service in an ASP.NET Web site.
Question: Which attribute in the markup or host file refers to the code-behind file or the class that
defines the data service?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-36

Introduction to Web Development with Microsoft Visual Studio 2010

Lab: Consuming Windows Communication


Foundation Services

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 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 discover the WCF service at a specific address by using a .svc file. In addition, you will
create a service reference proxy for the Customers WCF service, and call the WCF service method from a
Web Form. Finally, you will implement and test a WCF Data Service.

Objectives
After completing this lab, you will be able to:

Reuse existing functionality exposed by using WCF Services.

Discover WCF Services.

Create a Service reference proxy for a WCF service.

Call the WCF Service method from a Web Form by using the Service reference proxy.

Implement and test a WCF Data Service.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-37

Lab Scenario

You are a developer at Contoso, Ltd, which is a large organization with a global customer base. You need
to implement a Web Form that can be called by external customers to retrieve the information in your
database. The senior developer has created a WCF Web service that exposes a method that returns the
countries, and the WCF service method will be available to some customers. However, other customers
need to see the country data on a Web page. Therefore, it is your responsibility to discover the WCF
service from within your Web site, create a proxy object to call the WCF service method from a new Web
Form, and display the returned countries. Finally, you need to implement and test a WCF Data Service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-38

Introduction to Web Development with Microsoft Visual Studio 2010

Section 1: Visual Basic


Exercise 1: Creating a WCF Service Reference Proxy
The main tasks for this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Discover the WCF services at a specific address by using a .svc file.

3.

Examine the Web reference files.

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 Microsoft Visual Studio 2010.

Open the CustomerManagement solution from the D:\Labfiles\Starter\M12\VB folder.

Task 2: Discover the WCF services at a specific address by using a .svc file

Open the Add Service Reference dialog box.

Browse the WCF services at a specific address,


http://localhost:1112/Services/Customers.svc.

Open the Customers WCF services.

View the operations of the Customers WCF service.

Note: Notice the single method, GetCountries, in the Operations pane.

Specify the service reference name as CustomersService.

Task 3: Examine the Web reference files

Open the Reference.svcmap file, and examine the Web reference files.

Note: Notice that the MetadataFile elements and ExtensionFile elements point to the Customers.wsdl,
Customers.xsd, Customers1.xsd, Customers.disco, and Customers2.xsd files, and configuration91.svcinfo
and configuration.svcinfo files respectively.

Close the Reference.svcmap file.

Open the Customers.disco file, and examine the Web reference files.

Note: Notice the discovery file contains the contractRef element that links to other documents, including
the WSDL, and documentation on the server.

Close the Customers.disco file.

In the App_WebReferences/CustomersService/Customers.disco window, click the Close button.

Open the Customers.wsdl file, and examine the Web reference files.

In Solution Explorer, right-click Customers.wsdl, and then click Open.

Note: View the WSDL for the WCF service, its methods, and the bindings.
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-39

Close the Customers.wsdl file.

Results: After completing this exercise, you will have discovered a WCF service and seen its methods, by
using the WCF service file with the extension, .svc.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-40

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 2: Calling a WCF Service Method from a Web Form


The main tasks for this exercise are as follows:
1.

Create the Customers Web Form.

2.

Add controls for specifying countries to return.

3.

Add a GridView control.

4.

Call the WCF service.

5.

Test the Customers Web Form.

Task 1: Create the Customers Web Form

Create a folder named Services.

Add a Web Form named Customers, to the Services folder. The Web Form should not be based on a
master page.

Note: The Customers Web Form should not be based on a master page.

Set the page title to Countries by Contoso.

Link the Styles/Site.css stylesheet to the Customers Web Form.


<head runat="server">
<title>Countries by Contoso</title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
</head>

Task 2: Add controls for specifying countries to return

Add a Label control named StartingLettersLabel, to the div element of the Customers Web Form.

Add a TextBox control named StartingLettersTextBox, to the div element of the Customers Web
Form, for specifying the starting letters of the countries to return.

Add a RequiredFieldValidator control named StartingLettersRequiredFieldValidator, for requiring


input in the StartingLettersTextBox control.

Add a Button control named GetCountriesButton, to the div element of the Customers Web Form.
Create the Click event handler.

Task 3: Add a GridView control

Add a GridView control named CustomersGridView, to the div element of the Customers Web
Form, using a style of DDGridView.

Save the Customers Web Form.

Close the Customers Web Form.

Task 4: Call the WCF service

Import the CustomersService namespace to the Customers Web Form.


Imports CustomersService

In the GetCountriesButton.Click event, declare and instantiate an instance of the CustomersClient


class, named customersService.
Dim customersService As New CustomersClient()

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-41

Call the GetCountries WCF service method, passing the content of the Text property of the
StartingLettersTextBox TextBox control, and assign the return value to the DataSource property of
the CustomersGridView control.
CustomersGridView.DataSource =
customersService.GetCountries(StartingLettersTextBox.Text)

Implement data binding for the CustomersGridView control.


CustomersGridView.DataBind()

Save the code-behind file of the Customers Web Form.

Task 5: Test the Customers Web Form

View the Customers Web Form in the browser.

Get all countries beginning with the letter a.

Close the Internet Explorer browser.

Close the Customers Web Form.

Result: After completing this exercise, you will have created a Customers Web Form, and added
controls for specifying countries to return. Additionally, you will have added a GridView control, and
called the WCF service. Finally, you will have tested the Customers Web Form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-42

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Implementing WCF Data Services


The main tasks for this exercise are as follows:
1.

Add a WCF Data Service.

2.

Test the Data Service.

Task 1: Add a WCF Data Service

Add a new WCF Data Service in the Services folder named CustomersWcfDS, by using the Add New
Item dialog box and the WCF Data Service template.

Add the existing EDM namespace and class name to the declaration of the generic
CustomerManagementModel.Entities.
Public Class CustomersWcfDS
Inherits DataService(Of CustomerManagementModel.Entities)

Allow read access to the Countries and Customers entities of the EDM by using the
IDataServiceConfiguration.SetEntitySetAccessRule method in the Shared InitializeService
method of the DataService class.
config.SetEntitySetAccessRule("Countries", EntitySetRights.AllRead)
config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead)

Save and close the CustomersWcfDS code-behind file.

Move the CustomersWcfDS code-behind file from the Services\App_Code folder to the App_Code
folder in the root folder.

Delete the App_Code folder from the Services folder.

Task 2: Test the Data Service

Run the application.

View the entities available with the Customers Data Service by browsing to the URL,
http://localhost:1111/CustomerManagement/Services
/CustomersWcfDS.svc.

Note: Notice that the XML that was returned from the service contains both the Countries and
Customers entities.

View the Countries entity by browsing to the URL,


http://localhost:1111/CustomerManagement/Services
/CustomersWcfDS.svc/Countries.

Note: Notice that the XML that was returned from the service contains all of the Countries from the data
model.

View the Customers entity by browsing to the URL,


http://localhost:1111/CustomerManagement/Services
/CustomersWcfDS.svc/Customers.

Note: Notice the XML that was returned from the service contains all of the Customers from the data
model.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-43

View the information for the country, India, by browsing to the URL,
http://localhost:1111/CustomerManagement/Services
/CustomersWcfDS.svc/Countries?$filter=Name eq 'India'.

Note: Notice the XML that was returned from the service contains a single country, India.

View the countries for which the InternetTLD starts with less than B by using the URL,
http://localhost:1111/CustomerManagement/Services
/CustomersWcfDS.svc/Countries?$filter=InternetTLD lt 'B'.

Note: Notice the XML that was returned from the service contains all countries for which the InternetTLD
starts with less than B.

Close Internet Explorer.

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 added and tested a WCF Data Service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-44

Introduction to Web Development with Microsoft Visual Studio 2010

Section 2: Visual C#
Exercise 1: Creating a WCF Service Reference Proxy
The main tasks for this exercise are as follows:
1.

Open an existing ASP.NET Web site.

2.

Discover the WCF services at a specific address by using a .svc file.

3.

Examine the Web reference files.

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 Microsoft Visual Studio 2010.

Open the CustomerManagement solution from the D:\Labfiles\Starter\M12\CS folder.

Task 2: Discover the WCF services at a specific address by using a .svc file

Open the Add Service Reference dialog box.

Browse the WCF services at http://localhost:1112/Services/Customers.svc.

Open the Customers WCF services.

View the operations of the Customers WCF service.

Note: Notice the single method, GetCountries, in the Operations pane.

Specify the service reference name as CustomersService.

Task 3: Examine the Web reference files

Open the Reference.svcmap file and examine the Web reference files.

Note: Notice that the MetadataFile elements, and ExtensionFile elements, point to the Customers.wsdl,
Customers.xsd, Customers1.xsd, Customers.disco, and Customers2.xsd files, and configuration91.svcinfo
and configuration.svcinfo files respectively.

Close the Reference.svcmap file.

Open the Customers.disco file, and examine the Web reference files.

Note: Notice the discovery file contains the contractRef element that link to other documents, including
the WSDL and documentation on the server.

Close the Customers.disco file.

In the App_WebReferences/CustomersService/Customers.disco window, click the Close button.

Open the Customers.wsdl file, and examine the Web reference files.

In Solution Explorer, right-click Customers.wsdl, and then click Open.

Note: View the WSDL for the WCF service, its methods, and the bindings.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-45

Close the Customers.wsdl file.

Results: After completing this exercise, you will have discovered a WCF service and viewed its methods,
by using the WCF service file with the extension, .svc.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-46

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 2: Calling a WCF Service Method from a Web Form


The main tasks for this exercise are as follows:
1.

Create the Customers Web Form.

2.

Add controls for specifying countries to return.

3.

Add a GridView control.

4.

Call the WCF service.

5.

Test the Customers Web Form.

Task 1: Create the Customers Web Form

Create a folder named Services.

Add a Web Form named Customers, to the Services folder. The Web Form should not be based on a
master page.

Note: The Customers Web Form should not be based on a master page.

Set the page title to Countries by Contoso.

Link the Styles/Site.css stylesheet to the Customers Web Form.


<head runat="server">
<title>Countries by Contoso</title>
<link href="~/Styles/Site.css" rel="stylesheet"
type="text/css" />
</head>

Task 2: Add controls for specifying countries to return

Add a Label control named StartingLettersLabel, to the div element of the Customers Web Form.

Add a TextBox control named StartingLettersTextBox, to the div element of the Customers Web
Form, for specifying the starting letters for the countries to return.

Add a RequiredFieldValidator control named StartingLettersRequiredFieldValidator, for requiring


input in the StartingLettersTextBox control.

Add a Button control named GetCountriesButton, to the div element of the Customers Web Form.
Create the Click event handler.

Task 3: Add a GridView control

Add a GridView control named CustomersGridView, using a style of DDGridView, to the div
element of the Customers Web Form.

Save the Customers Web Form.

Close the Customers Web Form.

Task 4: Call the WCF service

Import the CustomersService namespace to the Customers Web Form.


using CustomersService;

In the GetCountriesButton.Click event, declare and instantiate an instance of the CustomersClient


class, named customersService.
CustomersClient customersService = new CustomersClient();

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-47

Call the GetCountries WCF service method, passing the content of the Text property of the
StartingLettersTextBox TextBox control, and assign the return value to the DataSource property of
the CustomersGridView control.
CustomersGridView.DataSource =
customersService.GetCountries(StartingLettersTextBox.Text);

Implement data binding for the CustomersGridView control.


CustomersGridView.DataBind();

Save the code-behind file of the Customers Web Form.

Task 5: Test the Customers Web Form

View the Customers Web Form in the browser.

Get all countries beginning with the letter a.

Close the Internet Explorer browser.

Close the Customers Web Form.

Result: After completing this exercise, you will have created a Customers Web Form, and added
controls for specifying countries to return. Additionally, you will have added a GridView control, and
called the WCF service. Finally, you will have tested the Customers Web Form.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-48

Introduction to Web Development with Microsoft Visual Studio 2010

Exercise 3: Implementing WCF Data Services


The main tasks for this exercise are as follows:
1.

Add a WCF Data Service.

2.

Test the Data Service.

Task 1: Add a WCF Data Service

Add a new WCF Data Service in the Services folder named CustomersWcfDS, by using the Add New
Item dialog box and the WCF Data Service template.

Add the existing EDM namespace and class name to the declaration of the generic
CustomerManagementModel.Entities.
public class Customers :
DataService<CustomerManagementModel.Entities>

Allow read access to the Countries and Customers entities of the EDM by using the
IDataServiceConfiguration.SetEntitySetAccessRule method in the Shared InitializeService
method of the DataService class.
config.SetEntitySetAccessRule("Countries",
EntitySetRights.AllRead);
config.SetEntitySetAccessRule("Customers",
EntitySetRights.AllRead);

Save and close the CustomersWcfDS code-behind file.

Move the CustomersWcfDS code-behind file from the Services\App_Code folder to the App_Code
folder in the root folder.

Delete the App_Code folder from the Services folder.

Task 2: Test the Data Service

Run the application.

View the entities available with the Customers Data Service by browsing to the URL,
http://localhost:1110/CustomerManagement/Services
/CustomersWcfDS.svc.

Note: Notice that the XML returned from the service contains both the Countries and Customers
entities.

View the Countries entity by browsing to the URL, http://localhost:1110


/CustomerManagement/Services/CustomersWcfDS.svc/Countries.

Note: Notice that the XML returned from the service contains all of the Countries from the data model.

View the Customers entity by browsing to the URL, http://localhost:1110


/CustomerManagement/Services/CustomersWcfDS.svc/Customers.

Note: Notice the XML returned from the service, it contains all of the Customers from the data model.

View the information for the country, India, by browsing to the URL,
http://localhost:1110/CustomerManagement/Services
/CustomersWcfDS.svc/Countries?$filter=Name eq 'India'.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-49

Note: Notice the XML returned from the service, it contains a single country, India.

View the countries for which the InternetTLD starts with less than B by using the URL,
http://localhost:1110/CustomerManagement/Services
/CustomersWcfDS.svc/Countries?$filter=InternetTLD lt 'B'.

Note: Notice the XML returned from the service, it contains all countries for which the InternetTLD starts
with less than B.

Close Internet Explorer.

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 added and tested a WCF Data Service.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-50

Introduction to Web Development with Microsoft Visual Studio 2010

Lab Review

Review Questions and Answers


1.

What are the elements in the Customers.discomap file?

2.

How do you define data source to the CustomersGridView control?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Consuming Microsoft Windows Communication Foundation Services

12-51

Module Review and Takeaways

Review Questions and Answers


1.

Does a WCF service have a user interface?

2.

How do you access a WCF service from a Web Form?

3.

What is the name of the dialog box that you can use to add a reference to a WCF service in Visual
Studio 2010?

Real-World Issues and Scenarios


1.

You need to expose data to a client that does not have access to your intranet. What is the easiest
way to implement this?
You should create and publish a WCF service.

2.

You need to expose data internally to a variety of clients, including Web applications, Windows
Forms, and console applications. What is the best way to implement this?
Create and publish a WCF service, because it will allow different types of hosting and different types
of connections, all depending on the actual connectivity requirements of the consuming application.

Best Practices
Mention some best practices in the context of your own business situations.

When you expose data externally through a service, or you do not know who will be accessing your
service, you should always return any data using data types that map to simple data types, such as
strings and integers, which can be used directly with XML.

When you add a reference to a WCF service, always give the service reference a name that spells out
what the service reference refers to. Do not use the default names, such as ServiceReference1.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

12-52

Introduction to Web Development with Microsoft Visual Studio 2010

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

QuickStart Intelligence

Notes

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

Potrebbero piacerti anche