You are on page 1of 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

v

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 Thomsen—Subject Matter Expert
Carsten Thomsen is an independent consultant who has worked since 1990 as a software developer,
analyst, architect, and author. He holds a number of Microsoft certifications, including MCTS and MCPD,
in various tools and applications, including the Microsoft® .NET Framework, Microsoft Visual Basic®,
Microsoft Visual C#®, and Microsoft Office SharePoint® Server 2007. He works with architecture,
research, analysis, development, and troubleshooting, and spends countless hours with the Windows®
operating system and many other Microsoft server products, including Hyper-V™ and SQL Server®.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based 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 .NET–Based 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

x

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 .NET–based languages.

Create an ASP.NET Web Form.

Add functionality to an ASP.NET Web Form.

Implement master pages and user controls.

Validate user input.

Debug ASP.NET 4.0 Web applications.

Manage data in an ASP.NET 4.0 Web application.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based
Languages” describes the different programming languages that are available when you develop
Microsoft .NET Framework applications. This module explains the fundamental aspects of writing code
and creating components by using two of the .NET Framework–based languages, Visual Basic and Visual
C#. It also provides an overview of Microsoft Visual Studio 2010, and explains how to create a simple Web
application.
Module 3, “Creating a Microsoft® ASP.NET Web Form” explains how to create Web Forms, and then
populate them with server controls.
Module 4, “Adding Functionality to a Microsoft ASP.NET Web Form” describes the various methods that
you can use to add code to your Microsoft ASP.NET Web application. It explains how to use Web server
controls, event handlers, code-behind files, and components. In addition, it explains how to use page
events, especially the Page_Load event.
Module 5, “Implementing Master Pages and User Controls” explains how to create and implement master
pages, and how to implement user controls in a Web application.
Module 6, “Validating User Input” provides an overview of user input validation. It covers information on
adding, positioning, and configuring validation controls on a Web Form. In addition, it covers information
on validating Web Forms.
Module 7, “Troubleshooting Microsoft ASP.NET Web Applications” describes the steps required to enable
tracing and debugging, including how you can use tracing and debugging in a Web application.
Module 8, “Managing Data in a Microsoft ASP.NET 4.0 Web Application” provides an overview of
Microsoft ADO.NET. It explains how to programmatically work with data by using ADO.NET, and how to
create a connection to access the data that is stored in a Microsoft SQL Server database. In addition, it
explains how to use the DataSet and DataReader objects to support the local data storage and data
manipulation requirements of Web Forms.
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.

guarantees or conditions. • Lessons: Guide you through the learning objectives and provide the key points that are critical to the success of the in-class learning experience. • Lab Answer Keys: Provide step-by-step lab solution guidance at your finger tips when it’s needed. you will have the opportunity to complete an online evaluation to provide feedback on the course. or resell this content. training facility. hands-on platform for you to apply the knowledge and skills learned in the module. redistribute. and provided to you by QuickStart Intelligence. send e-mail to mcphelp@microsoft. • • Modules: Include companion content. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. common issues and troubleshooting tips with answers. MSDN®. It is illegal to reprint. • To provide additional comments or feedback on the course." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.exe. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. To inquire about the Microsoft Certification Program. • Module Reviews and Takeaways: Provide improved on-the-job reference material to boost knowledge and skills retention. Additionally. best practices. which contain the review questions and answers. detailed demo steps and additional reading links. Course Companion Content on the http://www. such as questions and answers. tightly-focused format. • Labs: Provide a real-world. which is just right for an effective in-class learning experience. they include Lab Review questions and answers and Module Reviews and Takeaways sections. Resources: Include well-categorized additional resources that give you immediate access to the most up-to-date premium content on TechNet.com.microsoft. easy-to-navigate digital content with integrated premium on-line resources designed to supplement the Course Handbook. send e-mail to support@mscourseware. and real-world issues and scenarios with answers. a self-extracting executable file that contains all the files required for the labs and demonstrations.com/learning/companionmoc/ Site: Searchable. The Licensed Content is licensed "as-is. and instructor. Microsoft Press® Student Course files on the http://www.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.com/learning/companionmoc/ Site: Includes the Allfiles.microsoft. for each lesson. • Course evaluation At the end of the course. .com.

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. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.NET Framework 4. redistribute. and provided to you by QuickStart Intelligence. 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. or resell this content. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The lab files are located on the student computers. 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 . you will use Microsoft Virtual Server 2005 R2 with SP1 to perform the labs.com or by calling +1 800-785-3448. . It is illegal to reprint. 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. Virtual Machine Configuration In this course." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.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.

and provided to you by QuickStart Intelligence. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. . The Licensed Content is licensed "as-is.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. or resell this content. redistribute.

NET Web Applications in Microsoft Visual Studio® 2010 Contents: Lesson 1: Introduction to the .QuickStart Intelligence Exploring Microsoft® ASP. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.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.NET Framework 1-3 Lesson 2: Overview of ASP.com or by calling +1 800-785-3448. redistribute. guarantees or conditions. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.NET Web Applications in Microsoft Visual Studio® 2010 1-1 Module 1 Exploring Microsoft® ASP.

. and ASP.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. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. which you can use to develop your Web applications. or resell this content. Microsoft ASP.NET. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. including Web applications. • Describe the lab application. • Describe ASP. you will be able to: • Describe the .NET Framework provides components that modularize and simplify distributed applications development.NET Framework. It is illegal to reprint. guarantees or conditions.NET Framework. The Microsoft . you will learn about the key features of the .NET is one of the numerous technologies that are part of the . Please report any unauthorized use of this content to piracy@microsoft.NET Framework. You will also view a sample of the complete Web application that you will build in the labs throughout this course.NET. and provided to you by QuickStart Intelligence. In this module." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Module Objectives After completing this module.

redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will learn about the . Lesson Objectives After completing this lesson.NET Framework.QuickStart Intelligence Exploring Microsoft® ASP. . You will also learn about Visual Studio 2010. mainly in the context of developing Web applications. Developers face several challenges when they create Web applications. guarantees or conditions. you will be able to: • Describe Microsoft .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.NET Web Applications in Microsoft Visual Studio® 2010 1-3 Lesson 1 Introduction to the . In this lesson. It is illegal to reprint. the development tool that you can use to create Web applications. • List the benefits of using the. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.com or by calling +1 800-785-3448. • Identify the key features of Visual Studio 2010. The Licensed Content is licensed "as-is. • Describe the components of the .NET Framework 4.NET Framework.NET Framework resolves many of these problems.NET." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. and the .

This commonality makes it easy to integrate applications built by using the .NET. seamless and secure communication.NET Framework.NET Framework environment. Microsoft . guarantees or conditions. Web applications. The . The . In the .NET is built on an open architecture. This includes Web servers running Internet Information Services (IIS) for hosting Web applications and services.NET Framework provides a foundation to build and run applications and services.NET is to simplify the development of Windows® applications. and services.NET Framework is the infrastructure of Microsoft .NET provides an infrastructure to integrate. and SQL Server 2008 R2. The Licensed Content is licensed "as-is. and provides a common library of functions to build applications and services.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. code execution is efficient.NET Technologies Microsoft .NET Key Points The goal of Microsoft .) The . The . This includes mobile applications.NET Framework. applications hosted in the cloud by Windows Azure™. redistribute. which makes it easily extendable when you build and run Web applications and services.NET Framework helps minimize the efforts in software deployment.NET Framework is the Microsoft platform for building applications that have visually stunning user experiences. or resell this content. custom applications.NET includes the following technologies and products: • . and servers hosting services. including Windows services and Windows Communication Foundation (WCF) services. run. With these features." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. operate. and manage the . Microsoft . and the ability to model a range of business processes.QuickStart Intelligence 1-4 Introduction to Web Development with Microsoft® Visual Studio® 2010 Introduction to Microsoft . Please report any unauthorized use of this content to piracy@microsoft.NET Framework–based solutions on servers such as Windows Server® 2008 R2. Microsoft SharePoint® Server 2010. and promotes the safe execution of code. it also reduces versioning conflicts.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. It is illegal to reprint. (Cloud. . and applications hosted by Microsoft SQL Server® 2008. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. where software and data is provided on demand. or cloud computing refers to Internet based computing. • Servers. Microsoft . the .

. It is illegal to reprint. • Visual Studio 2010 and other developer tools." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. redistribute. Windows-based applications.NET Framework to develop your application? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Web applications. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. Microsoft . you can rapidly develop WCF services. and provided to you by QuickStart Intelligence. and personal computers. The Licensed Content is licensed "as-is.QuickStart Intelligence Exploring Microsoft® ASP.NET enables you to provide a consistent user experience across many devices such as mobile devices. Using these tools. Web browsers.com or by calling +1 800-785-3448. Question: What is the biggest advantage to using the . and thereby ensure enriched user experiences. and Windows Azure-based applications.NET Web Applications in Microsoft Visual Studio® 2010 1-5 • Clients.

Extensible Stylesheet Language Transformation (XSLT). interfaces. It is illegal to reprint.NET Framework classes is open to the developer. and gaming.NET Framework helps you to build applications that work the way you want.NET-compatible language can use. Desktop applications were created for office productivity. . home computing. These benefits include: • Web standards and practices. redistribute.NET Framework. with the . and provided to you by QuickStart Intelligence.NET Framework Key Points During the early years of Windows-based application development. Simple Object Access Protocol (SOAP). services. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. whether Windows-based or Web-based. in the programming language you prefer. developers had to specialize in the type of applications that they developed. XML Path Language (XPath). • By providing a comprehensive and consistent programming model and a common set of APIs. Extensible Hypertext Markup Language (XHTML). across platforms.com or by calling +1 800-785-3448.NET Framework fully supports existing Internet technologies. and other Web standards.QuickStart Intelligence 1-6 Introduction to Web Development with Microsoft® Visual Studio® 2010 Benefits of the . Today. XML. most applications were developed using the Windows application programming interface (API). the . and typically by using the C or C++ programming languages. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. Visual Basic.NET type is available to all . or Visual Basic scripting for use with classic Active Server Pages (ASP). The hierarchy of the . software.NET Framework provides several benefits for developing applications and services. and provides a common type system that any . developers had to specialize in developing applications in C or C++. • Unified application models. The functionality of a .NET classes through inheritance.NET-based applications. For example. and choose the programming language of your choice. or extensions. and devices. The . With the introduction of Microsoft Visual Basic® and the Internet. The . you can use your skills to develop any type of application. • Ease of use. guarantees or conditions.NET Framework organizes code in hierarchical namespaces and classes. The . You can access and extend . • Extensible classes. including HTML. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Hypertext Transfer Protocol (HTTP).

If you have the . redistribute. • Easier updates.com/fwlink/?LinkID=192007&clcid=0x409) provides support for smaller devices.QuickStart Intelligence Exploring Microsoft® ASP. these applications are easier to install.NET Framework that is installed on the computer will be updated with the latest fixes and service packs. Please report any unauthorized use of this content to piracy@microsoft. You can now extend your applications and services uniformly—from very small devices. The Licensed Content is licensed "as-is.NET Framework installed on your local computer.NET Web Applications in Microsoft Visual Studio® 2010 1-7 • Easier installation of commercial applications.com/fwlink/?LinkID=192006&clcid=0x409) is a hardware-independent environment that supports building and running managed applications on resource-constrained computing devices. If you receive Automatic Updates from Windows Update.NET Framework has two separate editions that are built to run on different devices: The .NET Micro Framework (http://go. to servers. .NET Framework to support their core functionality." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Device support.NET Framework to develop Web applications? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. to the cloud—by using the same programming model and tool chain throughout. The . and provided to you by QuickStart Intelligence. The Windows Update service updates the . It is illegal to reprint. Many applications from Microsoft and third-party vendors use the . the version of the .microsoft.microsoft.NET Compact Framework (http://go. guarantees or conditions. Question: What are the main advantages of using the . The .com or by calling +1 800-785-3448. or resell this content.NET Framework automatically.

• The . objectoriented collection of reusable features that you can use for common development needs. • Common language runtime.NET environment consists of various components that help you build and run . cryptography. and security.NET Framework must run on an operating system. The . data access. developing a Web application in both Visual Basic and Microsoft Visual C#®. depending on a number of factors—such as the origin of the component. The . All applications and all Microsoft .QuickStart Intelligence 1-8 Introduction to Web Development with Microsoft® Visual Studio® 2010 Components of the . In addition. while unmanaged code does not target the common language runtime. It promotes robustness by implementing a strict type-and-code-verification infrastructure called the common type system. you can extend classes by creating your own libraries. Each This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. It exposes common language runtime features. • Languages. database connectivity. and Web services. Managed code is run under the management of CLR. garbage collection. numeric algorithms. • Operating system.NET Framework class libraries.NET–based languages access the same . exception handling.NET–based applications. redistribute. The common language runtime (CLR) is the virtual machine component of the . graphical user interface (GUI) applications.NET Framework class library.NET Framework provides a variety of development languages that enables developers to transfer their skills and development techniques to the . The . Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. including command-line applications. thread management. • During development.NET Framework class library is a comprehensive. It is illegal to reprint. CLR provides features that simplify development in multiple programming languages—for example. and provided to you by QuickStart Intelligence.NET–based applications. and network communications. guarantees or conditions.NET Framework class library—also known as the Base Class Library (BCL)—provides features that include user interface (UI). and simplifies the development of. The .NET Framework Key Points The . Web application development. 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 Licensed Content is licensed "as-is. . The CLR component manages code at run time.com or by calling +1 800-785-3448.NET Framework that provides core services such as memory management. Web Forms.NET development process. and enforces security by awarding varying degrees of trust to a component.

and provided to you by QuickStart Intelligence. Note: For more information about WCF. Windows Presentation Foundation (WPF) provides classes for smart-client applications that combine user interface.NET." • Windows Workflow Foundation. one application domain is created for each Web site. • Windows Forms. • Windows Presentation Foundation. Windows Internet Explorer® Creates application domains to run managed 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. and media. The .NET Framework. "Managing Data in a Microsoft ASP. Any language that conforms to the Common Language Specification (CLS) can run with CLR.NET Framework 4 supplies a comprehensive collection of classes that provide features in many technology areas. and Data Services. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. Application Hosting The CLR manages the execution of code for a variety of applications and services. ASP. Microsoft-provided runtime hosts are listed in the following table. guarantees or conditions. each type of application requires a runtime host to start it.NET 4. redistribute.0 Web Application. Windows Workflow Foundation (WF) provides a programming model and tools to build workflow-enabled applications that model business processes.NET also creates an application domain for each Web application that will run on a Web server. "Consuming Windows Communication Foundation Services. Thirdparty organizations also can provide additional languages. Microsoft Visual C++®.NET.NET Web Applications in Microsoft Visual Studio® 2010 1-9 language provides broadly the same functionality. and Microsoft Visual F#®.com or by calling +1 800-785-3448. Runtime host Description ASP." • Windows Communication Foundation. By default. Data Access provides functionality to access external data sources. In the . The . • Data Access. Windows Forms is the core development platform for building smart client applications. ASP. Visual C#. creates the application domains within the process.NET Framework 4 Technologies The . see Module 12. and loads user code into the application domains. it also supports the development of third-party runtime hosts. The Licensed Content is licensed "as-is. including extensive XML support.NET Loads the common language runtime into the process that is to handle the Web request. The runtime host loads the runtime into a process. However.NET. which also includes the Entity Framework. including: • ASP.NET Framework supports the download and execution of browser-based controls. WCF provides a unified programming model for serviceoriented applications.NET is a programming framework for building powerful Web applications and services. . Note: For more information about ADO. Data Access is mainly implemented in Microsoft ADO. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Microsoft provides support for languages such as Visual Basic. documents.NET Framework not only provides several runtime hosts.QuickStart Intelligence Exploring Microsoft® ASP. see Module 8.

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

Windows-based applications. debug. guarantees or conditions.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 . It is illegal to reprint. and WF-enabled applications • Tools for working with cascading style sheets (CSS). JavaScript. or resell this content. Visual Studio 2010 is a complete development environment in which you can design. The Licensed Content is licensed "as-is.NET applications and services.com or by calling +1 800-785-3448. 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. including support for the Entity Framework and language-integrated query (LINQ) • Multi-targeting support to enable developers to select the version of the . Please report any unauthorized use of this content to piracy@microsoft. Features of Visual Studio 2010 Visual Studio 2010 provides the following features: • Support for various programming languages • Tools for building Web applications. and jQuery • Support for Microsoft Silverlight® • Complete error handing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. develop. remote debugging. . Asynchronous JavaScript and XML (Ajax).NET Framework that they want their application to target • Support for ASP.NET development. including the Apply Styles and Manage Styles windows • Data access tools. and deploy your .NET.QuickStart Intelligence Exploring Microsoft® ASP. including local debugging. WPF applications. WCF services.

which provide the building blocks for constructing distributed Web-based applications. guarantees or conditions.NET Web application—provide an easy way to build dynamic Web sites. you will be able to: • Describe the client-server interaction.NET Web application. • Describe the components of an ASP. Lesson Objectives After completing this lesson.NET Web Forms—which are part of an ASP.NET. In this lesson. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET dynamic compilation execution model. the components of an ASP. It is illegal to reprint. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.NET Web application.NET is a programming framework for building Web applications.NET ASP. • Describe the ASP. • Describe the process of generating and rendering markup and code. ASP.NET dynamic compilation execution model. or resell this content. redistribute. • Describe ASP.QuickStart Intelligence 1-12 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lesson 2 Overview of ASP. and the ASP.NET extensions. you will learn about the key features of ASP.NET Web applications.com or by calling +1 800-785-3448. . • Describe the ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET also includes the technology to build Web-based WCF services. ASP. Please report any unauthorized use of this content to piracy@microsoft.NET and ASP.

after loading a page. However. “Managing State in Web Applications. and the connection closes after the response has been sent to the client. This happens by using functionality of the HTTP protocol. which is rendered as a button on the Web page. and provided to you by QuickStart Intelligence. therefore. guarantees or conditions. redistribute. This involves state management. including POST and GET methods. or resell this content. who can then click this element. a typical submit function can be triggered by exposing an HTML input element of type submit to the user.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. In HTML. Note: State management is covered in detail in Module 13. Please report any unauthorized use of this content to piracy@microsoft. This can make it difficult to make a Web application appear as a connected application.QuickStart Intelligence Exploring Microsoft® ASP.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. back to the client. to recognize a user and any information they have included on a Web page. it is possible. It is illegal to reprint.” • On the client side. This means that there is no connection between a client and a Web server. The HTTP protocol is stateless by nature. • When a client requests a page by typing an address—also known as a Uniform Resource Locator (URL)—in a Web browser. Server-side This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. the user submits the page to the server. the client-side code can also be used to trigger a postback. the Web server can be made to recognize a user as they make repeated requests. from one request to the next. the Web server responds by sending the HTML (and potentially client-side code for the requested resource. programmatically. . which means that communication works in a disconnected manner. • The connection between the client and the server opens when the request comes in. The Licensed Content is licensed "as-is. such as a page or file). effectively triggering what is called a postback. You can use the client-side code on the client to work with information and controls without submitting to the server.

QuickStart Intelligence 1-14 Introduction to Web Development with Microsoft® Visual Studio® 2010 code runs only on the server.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. but it can be used to inject client-side code into the page that is rendered on the client. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. or resell this content.NET makes the client-server interaction seem trivial. The Licensed Content is licensed "as-is. because of the event-driven programming that you can use over HTTP. .

NET Web application consists of one or more Web Forms. This results in a simplified development process. It is illegal to reprint.NET Web applications in any . . because you can test the application without creating an external hosting environment. ASP. • You can use Visual Studio 2010 to build and run an ASP. generate additional Web Forms. The Licensed Content is licensed "as-is. ASP. • The built-in Windows authentication and Forms authentication helps keep Web applications and any associated data. VBScript.NET Web application.NET is the Web Form.QuickStart Intelligence Exploring Microsoft® ASP. Web developers who used Microsoft technologies implemented dynamic Web sites by using classic ASP technology. and provided to you by QuickStart Intelligence. What Is ASP. or Ajax to process various user actions on the client.NET? Microsoft ASP.com or by calling +1 800-785-3448.NET: • The fundamental component of ASP. A typical ASP.NET Framework.NET is a set of Web application development technologies. You can also use JavaScript. A Web Form is the Web page that users view in a browser. an ASP. Please report any unauthorized use of this content to piracy@microsoft. redistribute. It is a dynamic page that the Web server processes. guarantees or conditions. a traditional HTML Web page can run script on the client to perform basic tasks. The following are some key aspects of ASP.NET? Key Points Prior to the . or take advantage of the built-in security on the server.NET. or resell this content.NET is part of the .NET is device-independent. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Form can also run server-side code to access a database.NET. Because ASP.NET—unlike ASP—offers performance optimizations. unlike ASP. and early binding. jQuery. However. and Web-based WCF services.NET Web Applications in Microsoft Visual Studio® 2010 1-15 What Is ASP.NET enables programmers to build dynamic Web sites. • ASP.NET-based language. and that can access server resources. and allows you to develop a single Web Form that you can view on most devices that have Internet access and a Web browser. Classic ASP is interpreted code. you can develop ASP. which is compiled code. Web applications. secure. In other words.NET Framework and ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. strong typing.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You can make configuration settings at the time your ASP. and about error conditions. performance optimizations. which you can use to create a consistent layout for the pages in your application.NET health monitoring provides reporting of key events and information about the health of an application.QuickStart Intelligence 1-16 Introduction to Web Development with Microsoft® Visual Studio® 2010 • A deployed ASP. therefore.NET application runs as a process in the Internet Information Services (IIS) Web server. or the contents of a shopping cart.NET includes features that enable you to monitor the health and performance of your ASP. applications. then add or revise the configuration settings at any time. You can authenticate users by using Windows authentication. Please report any unauthorized use of this content to piracy@microsoft. you can manage authentication by using your own user database through ASP. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. including Visual Basic. • The ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET applications use a configuration system that enables you to define configuration settings for your Web server. and also other Web-based WCF services. It is illegal to reprint. and early binding.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. After the code is compiled.NET configuration ASP.NET provides an advanced security infrastructure for authenticating and authorizing user access. reusable controls. In addition to themes. Health monitoring and performance features ASP. among other benefits. . Forms authentication provider ASP. State management functionality ASP.NET always runs with a particular Windows identity. "Consuming Windows Communication Foundation Services. ASP.NET technology also supports Web-based WCF services. with minimal impact on operational Web applications and servers. you can secure your application by using Windows-based capabilities. ASP. and Microsoft Jscript® 8. guarantees or conditions.NET applications that benefit from the common language runtime." • ASP. the CLR component further compiles ASP. Alternatively. or for individual applications. such as customer information. Security infrastructure ASP.NET.NET forms authentication and ASP.NET code to native code.NET application. type safety. see Module 12. Visual C#.NET applications are deployed. ASP. Web-based WCF services are distributed applications that use XML and SOAP to transfer information between clients.NET membership. you can define master pages. and other ASP.NET features. or resell this content. inheritance. These languages enable you to develop ASP. which provides improved performance.NET code is compiled.NET compiler All ASP.NET provides intrinsic state management functionality that enables you to store information between page requests. redistribute.0. which is supplied by IIS. Note: For more information about WCF Services. for a Web site. such as NTFS file system access control lists (ACLs) and database permissions. The following table describes the various features of ASP. and performing other security-related tasks. You can code your applications in any programming language compatible with CLR. which enables strong typing.com or by calling +1 800-785-3448. The page and controls framework also provides features to control the overall look and feel of your Web site by using themes and skins. Feature Description Page and controls framework Page and controls framework encapsulates common UI functionality in easy-to-use.

com/fwlink/?LinkID=192015&clcid=0x409. see the ASP.NET Control Designers Overview page at http://go.NET Web Applications in Microsoft Visual Studio® 2010 1-17 Feature Description Troubleshooting support ASP. For more information about the Extensible Designer Environment. the ASP. or resell this content.NET Web applications.NET Health Monitoring Overview page at http://go.NET Health Monitoring. Please report any unauthorized use of this content to piracy@microsoft.NET Dynamic Data is covered in Module 10." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. ASP.NET Dynamic Data is a framework that lets you easily create data-driven ASP. 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. . It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. guarantees or conditions. ASP. redistribute. and deriving UI behavior from it.com or by calling +1 800-785-3448.NET includes an extensible hosting environment that controls the life cycle of an application from the time a user first accesses a resource—such as a page in the application—to the time when which the application is shut down. In addition. and provided to you by QuickStart Intelligence. and all languages supported by CLR and script languages.NET page framework provides a trace mode that enables you to insert instrumentation messages into your ASP. Web-based WCF services ASP.NET Web pages.microsoft. see the ASP. Extensible designer environment ASP.NET supports Web-based WCF services. This is done by automatically discovering datamodel metadata at run time. Extensible hosting environment and application life-cycle management ASP. For more information about ASP.NET Dynamic Data ASP. You can debug both managed and unmanaged objects.NET takes advantage of the run-time debugging infrastructure to provide cross-language and cross-computer debugging support. The Licensed Content is licensed "as-is.com/fwlink/?LinkID=192014&clcid=0x409.NET includes enhanced designer support for Web server controls for use with a visual design tool such as Visual Studio 2010.QuickStart Intelligence Exploring Microsoft® ASP.microsoft.

Every Web application has one or more web.NET Web Application The components of an ASP. . such as unhandled errors. Components of an ASP. and contain the server-side code for the Web Form.QuickStart Intelligence 1-18 Introduction to Web Development with Microsoft® Visual Studio® 2010 Components of ASP. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.NET page. you must understand how to implement and use all of the components. or .aspx pages. • WCF service references. One example is a user control with textboxes and validation for username and password input. The Licensed Content is licensed "as-is. and each Web server has only one machine.config file. • Configuration files.ascx files.NET Framework code in the same file.master files. • User Controls. WCF service references allow the Web application to send and receive data from a Web-based WCF service. The Global. • Code-behind files. When you create a Web application. This means that the code and the page markup share a single file.NET Web application contains different components." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. • Global. Master pages provide a streamlined and consistent UI across Web Forms. • Master Pages. Database connectivity allows the Web application to transfer data to and from database sources.config configuration files. or . redistribute. Web Forms provide the UI for the Web application. User Controls provide the UI for specific functionality to be reused in different Web Forms. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. which contains both the page markup and the .asax application file contains code for responding to application-level events that are raised by ASP.NET Web Applications Key Points An ASP. Configuration files are XML files that define the settings for the Web application and the Web server. It is illegal to reprint.NET Web application include: • Web Forms.asax file. or . You can also create a single-file ASP. • Database connectivity. and provided to you by QuickStart Intelligence. Code-behind files are associated with Web Forms.NET.

The CSS files and the contained styles are used to design the Web application. The Licensed Content is licensed "as-is. text files. and more reliable? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence Exploring Microsoft® ASP. easier. It is illegal to reprint. • CSS. Question: What are the tools in Visual Studio 2010 that make application development faster. guarantees or conditions. and for specifying fonts.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. or resell this content. redistribute. both with regard to element positioning on a Web Form. and XSLT files. XML files. colors. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . Please report any unauthorized use of this content to piracy@microsoft. and text.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. • First. . compilation moves through various stages. The ASP. Code Generation and Rendering When the compilers are requested to compile the code for your Web site. redistribute. guarantees or conditions. This means that both inline code and code-behind files are compiled.com or by calling +1 800-785-3448. This Web server may be local or remote.NET just in time (JIT) compiler. or resell this content. ASP. compilers work on your markup and code to generate markup and code that will display and behave correctly on the clients. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. You will learn more about differences between the two project types in later modules. • When compiling the application.NET compiler is called the ASP. such as the Visual Basic or Visual C# compiler.NET Web application project." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. as part of the deployment to the Web server on which the Web site will run.NET Web Site project. and not the ASP. all files in the Web site are copied to the destination Web server. This ASP. on an individual basis. The Web site content is parsed. However.NET compiles the files when a user accesses the Web site. the application is compiled into one or more assemblies in the Temporary ASP. This means that the markup adheres to certain standards that the browsers of the intended clients can render correctly. and provided to you by QuickStart Intelligence. The first page can be any page—not This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. and the actual compilation of each item is handed over to the appropriate compiler.NET Files folder when the first page is requested.NET compiler manages the compilation process dynamically. Note: The following description is for working with an ASP. The Web Forms or User Controls are turned into a class definition with methods for rendering the page or control. during compilation.

If the visibility of the source code is of concern to you.NET Web Applications in Microsoft Visual Studio® 2010 1-21 just the home page or default page. and provided to you by QuickStart Intelligence. Although the source code is available on the Web server. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you can either utilize the Web application project instead of the Web site project. The Licensed Content is licensed "as-is. However. or you can use the precompilation model. It is illegal to reprint.com or by calling +1 800-785-3448. This compilation model can be very convenient. guarantees or conditions. the source code is accessible to any user on your network who has the correct access permissions to the folders on the Web server. The assemblies are located in a subfolder with a name derived from a special naming convention that allows dynamic and random directory names. Please report any unauthorized use of this content to piracy@microsoft. it does not imply that a Web site user can access the source code and markup." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . redistribute. or resell this content. this is restricted by the Web server. Developers can open a Web Form or a corresponding code-behind file and make modifications to it—even on the live server—and changes are effective immediately.QuickStart Intelligence Exploring Microsoft® ASP. This makes it easy to locate the assemblies when requested.

such as those for Visual Basic and Visual C#. First Request When a client requests a Web page for the first time. Dynamic compilation execution allows you to modify your source code without having to explicitly compile your code before deploying the Web application. Note: MSIL is an assembly-level programming language that gets executed at run time.NET works to send information to a requesting client. which is then run. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. The client browser issues a GET HTTP request to the server. and runs the Microsoft intermediate language (MSIL) code.QuickStart Intelligence 1-22 Introduction to Web Development with Microsoft® Visual Studio® 2010 ASP. 3.NET Dynamic Compilation Execution Model Key Points ASP. Please report any unauthorized use of this content to piracy@microsoft. ASP. The client browser issues a GET HTTP request to the server." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . In this model. The compiled resources are then cached. or resell this content. Second Request When the user requests the same Web page for the second time. The various compilers. compile the Visual Basic and Visual C# code into MSIL.NET invokes the compiler. the following events occur: 1.NET Web pages and code files use dynamic compilation by default when a user requests a resource for the first time. The runtime loads. 4. which ensures that subsequent requests are performed efficiently. the following events take place: 1. It is illegal to reprint. 2.com or by calling +1 800-785-3448. guarantees or conditions. If the code is not already compiled in a dynamic-link library (DLL). The ASP.NET parser interprets the source code. you will learn how dynamic compilation in ASP.

This provides faster response time. guarantees or conditions. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.aspx content may still be parsed. The advantages of precompilation include: • Improved response time for users. It is illegal to reprint. error checking.NET can precompile a Web site before it is made available to users. Precompilation You can choose to precompile an entire site before you make it available to users. • Ability to identify compilation errors before users access the site. source-code protection. • Ability 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.NET Web Applications in Microsoft Visual Studio® 2010 2. The Licensed Content is licensed "as-is. redistribute.com or by calling +1 800-785-3448.QuickStart Intelligence Exploring Microsoft® ASP. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note: The . Web Application Precompilation ASP. 1-23 The runtime loads and immediately runs the MSIL code that was already compiled during the first request of the page. because pages and code files do not require compilation on first request. and efficient deployment. particularly if the content page has changed. or resell this content.

" What Is ASP. The jQuery library is an open source JavaScript library. What Is ASP.NET Ajax. The Licensed Content is licensed "as-is. and the jQuery library.NET Dynamic Data. and provided to you by QuickStart Intelligence. The ASP.NET Framework that provide specific functionality for ASP.NET Dynamic Data brings major usability and rapid application development (RAD) changes to the existing ASP. ASP. The ASP.NET data controls.NET Ajax server-side controls to add Ajax functionality to an ASP.NET Ajax? ASP.NET Ajax library helps you build rich client-side applications.NET Ajax-Enabled Web Forms Application.com or by calling +1 800-785-3448.QuickStart Intelligence 1-24 Introduction to Web Development with Microsoft® Visual Studio® 2010 ASP. When This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and respond to the server request in a manner that does not distract the user or interrupt what the user is currently doing. This framework can also be used for creating custom controls and client-side JavaScript code. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.NET Ajax provides the ability to asynchronously send a section or part of a Web page to the server. Developers familiar with the ASP. Note: For more information about ASP. "Creating a Microsoft 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.NET Ajax framework includes the Ajax Control Toolkit. and ASP. which is a collection of highly interactive client-side controls. It is illegal to reprint.NET Dynamic Data? ASP. . redistribute.NET.NET Ajax. which is an extensive JavaScript library.NET Framework Extensions Key Points There are a number of frameworks within the .NET Ajax framework can be used with server-side code and controls that automatically produce the client-side code. see Module 11. The client-side ASP. RAD is significantly increased by using a rich scaffolding framework. Two of these frameworks are ASP.NET server-side programming model can use ASP.NET application without writing any JavaScript code.

.QuickStart Intelligence Exploring Microsoft® ASP. or resell this content. you can use ASP.NET Web applications.com or by calling +1 800-785-3448. Note: For more information about ASP. see Module 10. and Delete (CRUD) operations are supported.NET Dynamic Data to create a fully functional and datadriven Web site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and the nullable fields. "Managing Data by Using Microsoft ASP. Update. the field length. It is illegal to reprint.NET Dynamic Data. Therefore. A scaffolding framework provides a functional Web site for viewing and editing data. Please report any unauthorized use of this content to piracy@microsoft. You can easily customize the scaffolding framework by changing the elements or creating new ones to override the default behavior. ASP." This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Dynamic Data is a framework that allows you to easily create data-driven ASP.NET pages. Existing applications can easily integrate scaffolding elements with the ASP. Smart validation is automatically available. Full Create.NET Dynamic Data. and provided to you by QuickStart Intelligence. redistribute.NET Web Applications in Microsoft Visual Studio® 2010 1-25 connected to a data source. and it provides validation based on the database constraints for the data type. It does this by automatically discovering the data-model metadata at run time and deriving UI behavior from it. Read. The Licensed Content is licensed "as-is. guarantees or conditions.

NET Framework. • Describe the lab application setup. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 1-26 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lesson 3 Overview of the Lab Application In this lesson. Lesson Objectives After completing this lesson. guarantees or conditions. You will also explore a complete version of the lab application.com or by calling +1 800-785-3448.NET 4. you will be able to: • Describe the lab scenario. • View the components of an ASP. or resell this content. you will explore the lab application that you will build throughout the remainder of this course.0 Web application project. • Explore Visual Studio 2010. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Explore the . redistribute. It is illegal to reprint. and understand some of its functionality. . and provided to you by QuickStart Intelligence.

redistribute. To do this. The senior developer has advised you to become familiar with the features and functionalities of both the . Ltd." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 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. Please report any unauthorized use of this content to piracy@microsoft. you need to create a Customer Management Web application for managing your customers electronically from anywhere within the intranet. The Web application will also be made available over the Internet to employees in remote locations who are not connected to the intranet. As part of your job. or resell this content. 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. It is illegal to reprint.QuickStart Intelligence Exploring Microsoft® ASP. guarantees or conditions.NET Framework 4 and Visual Studio 2010. . and provided to you by QuickStart Intelligence. without installing any extra software on the client.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.NET Web Applications in Microsoft Visual Studio® 2010 1-27 Lab Scenario You are a junior developer in Contoso.

Functional Requirements • Provide logon abilities. • Create new country rows. guarantees or conditions. including ensuring required information is entered. • Display all country-related data in a spreadsheet-like view. • Edit existing customer rows. • Edit existing country rows. • Edit a customer row in spreadsheet-like view.com or by calling +1 800-785-3448. • Validate user input. • Create new customer rows. • Display information about a single customer. or resell this content. and provided to you by QuickStart Intelligence.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. The Licensed Content is licensed "as-is. and in the correct format. • Display all customer names in a spreadsheet-like view. • Display information about a single country. Application Requirements The application must meet the functional and UI requirements listed in the Functional Requirements and User Interface Requirements sections. to enable the sales staff of Contoso. • Store customer rows. Please report any unauthorized use of this content to piracy@microsoft. . • Edit a country-related data in spreadsheet-like view. Ltd to maintain customer and country items. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Store country rows. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

• Expose all country rows to external customers and vendors by using a WCF service or an independent Web Form. but any number of customers can live in the same country. • Menu. . that is. A single customer is located in a specific country. It is illegal to reprint. 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. The Customers page displays the following information. and provided to you by QuickStart Intelligence. This is a simple greeting page that the user sees whenever they open the application. Functionality Description Customers New—Creates a new customer row. About Displays a modal About dialog box. The Licensed Content is licensed "as-is. so there is a many-to-one relationship between customers and countries. is based on a sitemap XML file. which is accessible on all pages. Application Building A single application will be built throughout the modules. Countries New—Creates a new country row. redistribute. and is automatically assigned. The application consists of the following components: • Home Page. Import Imports countries from an XML file. and the path to the page or Web Form. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. User Interface Requirements • Present input validation error messages in place. The Menu. Customers Page Customer rows are stored in the CustomerManagement database in the Customers table. This field is read-only. Breadcrumb The breadcrumb displays the current location in the application. next to input fields that did not pass the input validation. guarantees or conditions. All—Shows all customer rows. • 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.QuickStart Intelligence Exploring Microsoft® ASP. The value of this field can be used when navigating directly to a specific customer. Field Description ID The unique identifier of the customer. even if the lab exercises in the first few modules only introduce the concepts to be used in later modules. or resell this content.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. and it provides the functionalities that are listed in the following table." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. All—Shows all country rows. Please report any unauthorized use of this content to piracy@microsoft.

Please report any unauthorized use of this content to piracy@microsoft. The value of this field can be used when navigating directly to a specific country. This field only accepts numeric characters 0–9. Address. Phone This is the phone number of the customer. and is limited to 50 characters. This field is mandatory. and is limited to 30 characters. The Licensed Content is licensed "as-is. This field is mandatory. News Subscriber This Boolean field indicates if the customer subscribes to newsletters. guarantees or conditions. City This is the name of the city in which the customer lives. This field is mandatory. This field is This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and is limited to 80 characters Credit Limit This is the credit limit assigned to the customer. Countries Page Country rows are stored in the Contoso database in the Countries table.com or by calling +1 800-785-3448. This field is mandatory. • The textbox for the Credit Limit field only accepts numeric characters. if filled in. and is limited to 30 characters. and is mandatory. It is illegal to reprint. and it is automatically assigned. Country This is the unique ID of the country in which the customer lives. Country. saved in the appropriate format for the country in which the customer resides. which consists of street name. and is limited to 50 characters. Last Name. Address This is the address of the customer. and is limited to 30 characters. house and door number. The input validation. This field is readonly. State This is the name of the state or region in which the customer lives. City. Web Address This is the Web address (URL) of the customer. which must take place at both the client-side and server-side. or when saving or updating customer information. Field Description ID This is a read-only field with the unique identifier of a country. Zip Code. and only numbers less than or equal to 50. and provided to you by QuickStart Intelligence. . redistribute.000. Zip Code This is the zip code for the customer. • The E-mail Address field must contain a valid e-mail address. includes the following functionalities: • You will be required to add information to the First Name. • The Web Address field must contain a valid Web address (URL). This field is mandatory. Name This is the English name of the country. and is limited to 10 characters. Last Name The last name of the customer is limited to 30 characters. Created Date This is the date when the customer row is created in the application." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and is limited to 50 characters. and Web Address fields when adding or editing a customer row. A message will display if any mandatory information is left blank. Input Validation The Customers Web Form provides input validation by using various techniques. This field requires the E-mail Address field to be filled in. or resell this content. E-mail Address This is the e-mail address of the customer.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. The Countries page displays the information listed in the following table. This field is mandatory.

NET Login controls. The input validation—which must take place on both client-side and server-side—includes the following: • You will be required to add information to the User name and Password fields when authenticating. A message will display if any information has been left out. once the user clicks the Login button. The user logs out by clicking the appropriate link. such as 1 for Canada and United States.com or by calling +1 800-785-3448. A message will display if any information has been left out. The Licensed Content is licensed "as-is. This field is mandatory. Dialing Country Code This is the international dialing code when dialing from outside the country. which will start the process of authenticating the given user credentials. . and is limited to 30 characters. Login The user must log in. 353 for Ireland. The user names and passwords are stored in the standard ASPNETDB profile database that is created in SQL Server 2008 Express Edition.NET Web Applications in Microsoft Visual Studio® 2010 Field 1-31 Description mandatory. . when saving or updating country information.NET login controls must be visible on all pages. It is illegal to reprint. 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. Please report any unauthorized use of this content to piracy@microsoft. redistribute. 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. Internet Top Level Domain This is the country-specific Top-Level Domain (TLD) for Internet domains. such as . and provided to you by QuickStart Intelligence. such as 011 for the United States. and the standard ASP. Input Validation The Login Web Form provides input validation when authenticating as a user. the user can see who has logged in. Input Validation The Countries Web Form provides input validation when creating or editing countries by using various techniques." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • The text box for the International Dialog Code field only accepts numeric characters in the format 999.de for Germany. This field is mandatory. guarantees or conditions. Format This is the format for displaying and entering a phone number.au for Australia. The value in this field must be case sensitive. and International Dialing Code fields when adding or editing a country. Phone No. 45 for Denmark.QuickStart Intelligence Exploring Microsoft® ASP. . and 34 for Spain. • Password: The password associated with the given user name. This field is mandatory. or resell this content. • Login: The Login button. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . 44 for Great Britain. The formatting will be applied to the user input when this field has been specified in the database. 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.ie for Ireland. The Login page displays the following information: • User name: The user name of the user trying to authenticate. The input validation—which must take place on both client-side and server-side—includes the following functionalities: • You will be required to add information to the Name. Using the standard ASP. Internet Top Level Domain. or .dk for Denmark.no for Norway. and 00 for member countries of the European Union.

which is saved in the appropriate format for the country in which the customer resides. nonclustered index sorted in ascending order. non-clustered index that is sorted in ascending order. This is a nonunique. State nvarchar 30 No This is the name of the state or region in which the customer lives. ZipCode nvarchar 10 Yes This is the customer zip code. This is a non-unique. and provided to you by QuickStart Intelligence. This is a nonunique. newsequentialid() This is the unique ID of the customer row. referencing the ID of the corresponding country in the Countries table.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. LastName nvarchar 30 Yes This is the last name of the customer. CountryID uniqueidentifier N/A Yes This is the unique ID of the country in which the customer lives. which includes street name and door number. The Licensed Content is licensed "as-is. The Customers table includes the following fields. This is the primary key. City nvarchar 30 Yes This is the name of the city in which the customer lives. guarantees or conditions.com or by calling +1 800-785-3448. which is automatically assigned by the database. if not supplied on insert. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint. or resell this content. Address nvarchar 50 Yes This is the customer address. Phone varchar 30 No This is the customer phone number. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a foreign key. 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. Please report any unauthorized use of this content to piracy@microsoft. non-clustered index that is sorted in ascending order. .

DialingCountry Code varchar 5 Yes This is the international dialing code when dialing from outside the country.com or by calling +1 800-785-3448. non-clustered index that is sorted in ascending order. and 34 for Spain.000 No N/A Yes Description This is the credit limit assigned to the customer. . or resell this content. Name nvarchar 50 Yes This is the English name of the country. This indicates whether or not the customer subscribes to Contoso newsletters. This is also a unique. CreditLimit int N/A Yes NewsSubscri ber bit CreatedDate smalldatetime 50. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. such as 1 for Canada and United States. redistribute. 45 for Denmark. 44 for Great Britain. 353 for Ireland. 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. Url nvarchar 80 No This is the address of the customer’s Web site.QuickStart Intelligence Exploring Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft. It is automatically assigned by the database.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. 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. It is illegal to reprint. This is the primary key. 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 also a non-unique. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. The Countries table includes the following fields. getdate() This is the date that the customer row is created in the application.

This data must be imported into the Countries table. It is illegal to reprint. Ltd. . Existing Countries On a monthly basis. International DialingCode varchar 5 Yes This is the code or number that must be used to dial a number outside the country from where the call originates. and buttons to load or import the data and export it to the SQL Server 2008 database. guarantees or conditions. . . such as . and provided to you by QuickStart Intelligence. such as 011 for the United States. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. but only those countries with a value for the PhoneNoFormat field should be imported.au for Australia. redistribute. or .com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. This field is mandatory.ie for Ireland. and 00 for member countries of the European Union." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a file selection control for locating the XML file with the Country data to import. an update to the country rows is sent electronically to Contoso. Please report any unauthorized use of this content to piracy@microsoft. and these country rows are all placed in a single XML file.de for Germany. . Import Countries Page The Import Countries Web Form contains a Label.no for Norway.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.dk for Denmark. InternetTLD char 2 Yes This is the country-specific TLD for Internet domains. or resell this content.

aspx Web Form is the home page for the Customer Management Web application.QuickStart Intelligence Exploring Microsoft® ASP. The Default. or resell this content.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Default. the instructor will demonstrate the features and functionalities of the Customer Management application.aspx Web Form—like the other Web forms in the application—is based on the Site. The Licensed Content is licensed "as-is. You can open the Lab solution on the virtual machine and view the steps demonstrated. guarantees or conditions. Open the solution code by accessing the CustomerManagement solution file from the D:\Labfiles\Solution\M16\VB or D:\Labfiles\Solution\M16\CS folders. Users can browse to other Web Forms by using the Menu or SiteMapPath controls.master master page.NET Web Applications in Microsoft Visual Studio® 2010 1-35 Walkthrough: The Lab Solution In this demonstration. and provided to you by QuickStart Intelligence. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute.

Open Visual Studio 2010." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Open the finished lab solution. including System. click Open Project.NET Framework in the context of Web application development. click Microsoft Visual Studio 2010.sln. Examine some of the .NET Framework namespaces and classes. • In the Open Project dialog box. Note: You will learn more about the features offered by Ajax Extensions and the Ajax Library in Module 11. and view the About box by clicking About on the Help menu.NET Ajax-Enabled Web Forms Application. and provided to you by QuickStart Intelligence. On the Start menu of 10267A-GEN-DEV. type D:\Labfiles\Starter\M16\VB\CustomerManagement. • In the Start page – Microsoft Visual Studio (Administrator) window. redistribute. “Creating a Microsoft® ASP.sln or D:\Labfiles\Starter\M16\CS\CustomerManagement.UI. Ajax Library.Page class. Explore the Ajax Extensions and the Ajax Library features. including the Ajax Extensions." This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is.NET Framework Key Points In this demonstration you will examine the . Please report any unauthorized use of this content to piracy@microsoft. Demonstration Steps The main tasks are as follows: 1. and Dynamic Data. It is illegal to reprint.UI. and then click Open.com or by calling +1 800-785-3448. on the File menu. or resell this content. and then click Microsoft Visual Studio 2010.Web. • Run the solution.Web. point to All Programs. 4. .NET framework extensions. guarantees or conditions. and examine the System.Web and System. in the File name box. • 2.QuickStart Intelligence 1-36 Introduction to Web Development with Microsoft® Visual Studio® 2010 Demonstration: Exploring the . and explore the ASP. 3.

Please report any unauthorized use of this content to piracy@microsoft. redistribute. guarantees or conditions. and Dynamic Data. such as Ajax. view code for some of the Module 6 and later lab exercises.com or by calling +1 800-785-3448. • Run the solution. "Managing Data by Using Microsoft ASP. 6." Result: At the end of this demonstration. • On the Customers menu. Note: You will learn more about how Dynamic Data works in Module 10. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and provided to you by QuickStart Intelligence.QuickStart Intelligence Exploring Microsoft® ASP. or resell this content. • On the Countries menu. 1-37 Explore how Dynamic Data works.NET Web Applications in Microsoft Visual Studio® 2010 5.NET Dynamic Data. The Licensed Content is licensed "as-is. click All.NET Framework 4 features in the context of Web application development. click All. If time permits. It is illegal to reprint. including some the new functionalities. you will have a basic understanding of the.

in the Name box. and using components and controls. ensure that File System is selected. click Microsoft Visual Studio 2010." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. right-click the Web site. and then click OK. • On the Start menu of 10267A-GEN-DEV. ensure that . Open Microsoft Visual Studio 2010.com or by calling +1 800-785-3448. • In the New Web Site dialog box. It is illegal to reprint. and provided to you by QuickStart Intelligence. click ASP. click New Web Site. • In the middle pane. guarantees or conditions.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. in the left pane. Demonstration Steps The main tasks are as follows: 1. • In the Start Page – Microsoft Visual Studio window. click Visual Basic or Visual C#. Add the Default. type Default. 2. • In Solution Explorer. click Web Form. in the middle pane. and then click Add. and then click Add New Item.NET Empty Web Site. and then click Microsoft Visual Studio 2010. . on the File menu. point to All Programs. • In the Web location list.aspx Web Form to the CustomerManagement Web site. Create a new ASP.NET Web site with the following settings: Name: WebSite1 Location: File system Language: Visual Basic or Visual C# 3. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • In the New Web Site dialog box. • In the Add New Item dialog box.aspx. in the middle pane. The Licensed Content is licensed "as-is. redistribute. designing Web Forms.NET Framework 4 is selected in the target framework list. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. adding code. under Installed Templates.

6. guarantees or conditions. • In the Default. It is illegal to reprint.QuickStart Intelligence Exploring Microsoft® ASP.NET Web Applications in Microsoft Visual Studio® 2010 4." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and then double-click the box next to the Click event.com or by calling +1 800-785-3448.aspx window. expand Standard. click Source. • In the Default. • In the Default.aspx window. 1-39 Open the Web Form in both the Design view and the Source view. The Licensed Content is licensed "as-is.aspx window.aspx window. • In Toolbox. • In the CustomerManagement – Microsoft Visual Studio (Administrator) window. • In the Default. or resell this content. • In the Properties window. you will understand the advantages of using Visual Studio 2010 for developing ASP. and then double-click the Button control. select the div element. 5. redistribute. click the Button control. • In the Default.aspx window. click the Events icon. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Add a Button control to the Web Form. Please report any unauthorized use of this content to piracy@microsoft. click Design.NET applications. and provided to you by QuickStart Intelligence. Add code to the Button Click event. . click Design. point to Toolbox. Result: At the end of this demonstration.

In Solution Explorer.com or by calling +1 800-785-3448. redistribute.NET 4. In Solution Explorer. and identify where project references go. and the references.0 Web application." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Examine the Web Forms. guarantees or conditions. • In Solution Explorer. you will have identified and examined the functionality and importance of the components of an ASP. It is illegal to reprint. review the various files. or resell this content. • 2. the assembly info file. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • 3. and class files. the class files. designer code files. The Licensed Content is licensed "as-is. the web. Web Forms.NET 4. Examine the solution and project files. and provided to you by QuickStart Intelligence. review the various files. and the designer code files. review the ASP. . the code-behind files. In Solution Explorer. including the solution file.NET folders.NET folders.0 Web Application Project In this demonstration. notice the solution and project files. you will examine the various components of a Web application project. Examine the ASP. • 4.config files. code-behind files.QuickStart Intelligence 1-40 Introduction to Web Development with Microsoft® Visual Studio® 2010 Demonstration: Exploring the Components of an ASP. Please report any unauthorized use of this content to piracy@microsoft. the project file.config files. Examine the assembly info file and the web. Result: At the end of this demonstration. the references. the ASP.NET folders. Demonstration Steps The main tasks are as follows: 1. and if time allows create a new one.

NET? 3. or resell this content. . and provided to you by QuickStart Intelligence. guarantees or conditions. What is the purpose of the code-behind files in ASP.NET Web Applications in Microsoft Visual Studio® 2010 1-41 Lab Review Review Questions and Answers 1. What are Web Forms? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET? 2. redistribute. What is the major advantage of using ASP. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.QuickStart Intelligence Exploring Microsoft® ASP. It is illegal to reprint.com or by calling +1 800-785-3448.

Web sites.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. 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 Framework. and provided to you by QuickStart Intelligence. You are unsure of the functionality of a particular class. or online communities. You are unsure whether to use dynamic compilation or precompilation. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. Which components are included in the . Which type of component should you create? 4.NET Framework documentation." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. guarantees or conditions. What is the purpose of CLR? 3. 2. . You need to develop an application that contains projects that target multiple versions of the . It is illegal to reprint. redistribute. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 1-42 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Review and Takeaways Review Questions and Answers 1. How can you determine the functionality of the class? Use the . You need to create a programmable Web component that you can share among multiple Web applications. Which tool enables you to accomplish this? Real-World Issues and Scenarios 1.NET Framework 4? 2.

QuickStart Intelligence Exploring Microsoft® ASP. The Licensed Content is licensed "as-is. redistribute. guarantees or conditions. . It is illegal to reprint.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.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. or resell this content.

redistribute. . Please report any unauthorized use of this content to piracy@microsoft.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. or resell this content. It is illegal to reprint. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.

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

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 Framework–based languages,
Microsoft Visual C#® and Microsoft Visual Basic®. Visual Studio 2010 offers end-to-end Web
development capabilities, and scalable and reusable server-side components. These capabilities and
components enable you to improve your productivity, and effectively create applications and Microsoft
ASP.NET Web sites.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based Languages

2-3

Lesson 1

Choosing a Programming Language

Key Points
To create your Web applications, you have a wide choice of programming languages. For many years, the
programmer’s choice of the programming language was based on the available platform, framework, and
integrated development environment (IDE), although some programmers did choose a programming
language purely because they liked the syntax of that programming language. However, all this changed
when the .NET Framework was introduced, because it is programming language-independent. This is
because the Microsoft intermediate language (MSIL) that is executed at runtime gets converted into
machine code when the program is run by the .NET common language runtime (CLR).
For a programming language to be compatible with the .NET Framework, the corresponding compiler—at
build time—must compile the code into MSIL (or IL as it is generally called). At run time, MSIL is compiled
by the just in time (JIT) compiler. In effect, the .NET CLR understands only one language—MSIL. Therefore,
if your platform or framework is the .NET Framework, you have several options when choosing a
programming language. Many programming languages for the .NET Framework have the .NET
Framework Base Class Library (BCL), which has most of the functionality. It is generally not the
functionality that sets the programming languages apart, but the syntax, the code structure, and the
corresponding editor where you write your code.
Visual Studio 2010 includes Visual Basic and Visual C# to help create Web applications. Web development
has become very powerful, and yet simpler than ever before with the inclusion of ASP.NET Asynchronous
JavaScript and XML (Ajax), the Ajax Library, Dynamic Data, language-integrated query (LINQ), many
controls, support for cascading style sheets (CSS), and scripting such as JavaScript and jQuery.
In this lesson, you will explore the features of Visual Basic and Visual C#, and examine the considerations
for choosing between the two programming languages. You will have situations that require multiple
programming languages within the same application; therefore, you need to know how to work with code
in multiple-language scenarios.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based Languages

2-5

Features of Visual Basic

Key Points
While the current Visual Basic 10.0 version is designed around the .NET Framework, if you are used to
developing applications in the Component Object Model (COM)–based Visual Basic 6.0 or earlier, you will
find Visual Basic 10.0 easy to use. While Visual Basic 6.0 was mostly used for creating COM components
and Windows®-based applications, Visual Basic 10.0 can be used for developing any type of .NET
Framework application or service, including Web applications, Windows Forms applications, Windows
Communication Foundation (WCF) services, Asynchronous JavaScript and XML (Ajax)–based Web
applications, device applications, and Microsoft Silverlight® applications.
If you have worked in a previous version of Visual Basic, you will find that not much has changed,
although many additions have been made. For example, there are changes to the COM-based
deterministic finalization, which has now been replaced by the garbage collection feature of CLR, thus
eliminating deterministic finalization and helping to reduce memory waste from unclaimed objects.

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

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based 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, Ajax–based 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 Framework–based languages. The default color displays keywords colored in blue, and
strings colored in red. Visual C# also provides a background compilation model—similar to Visual Basic
Text Editor—in which the code compiles in the background as you type, and catches compile-time and
syntax errors. Any errors caught by the background compilation are underlined with a squiggly line, with
different colors indicating the type of error. If you hover the pointer over one of these squiggly lines,
IntelliSense displays a description of the error. The errors are added to the Error window when the project
is rebuilt.
When you add an interface to a type declaration, you can use the editor to add the method signatures for
an interface by right-clicking the name of the interface. You can click the Implement Interface, and then
click Implement interface again. In the following code, the code between lines 3 through 10 has been
inserted by the Visual C# Text Editor after adding IDisposable to the class declaration.
1 public class Class1 : IDisposable
2 {
3
#region IDisposable Members
4
5
public void Dispose()
6
{
7
throw new NotImplementedException();
This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 type—for example, Services.Customers—then the actual namespace for the type is
Services.Customers, because the default namespace is ignored. In addition, types in project subfolders

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based 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 constructs—such 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 Framework–based programming languages, such as Visual Basic and
Visual C#. Therefore, as a developer, you need to at least understand both languages, because it is very
likely that you will work with both. You might need to copy some functionality written in a programming
language other than the one you master the best. Depending on the amount of code, you will either copy
some lines of code, and then translate them into a programming language of choice, or you will add a
project to your current solution.
If you add a project to your current solution, then you have a solution made up of at least two projects,
written in two different programming languages. This is an everyday reality for many .NET developers.
Thus, even if you do not master the two languages, you should at least be able to read and understand
the code written in either language.
Question: In what real-world scenarios do you use mixed languages?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 .NET–Based 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 .NET–Based Languages

2-13

Lesson 2

Overview of Visual Studio 2010

Visual Studio 2010 is a comprehensive tool for creating all types of .NET Framework–based applications,
including Web applications and services. It consists of an IDE, integration of the .NET Framework, and the
building of applications and services based on .NET Framework versions 2.0, 3.0, 3.5, and 4.
Visual Studio 2010 IDE consists of a common user interface (UI), and set of tools that you can use for all
the project types and programming languages that Visual Studio 2010 supports.

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

Describe the advantages of using Visual Studio 2010.

Identify the available project templates.

Describe the features of IDE.

Identify the elements of a Visual Studio 2010 Start page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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. IntelliSense–based 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 Framework–based programming languages. This support enables
you to work in your own preferred programming language, because you no longer have to learn a new
programming language for each new project. You can also use the IDE in the design and testing phase of
the development life cycle. For example, Visual Studio 2010 provides class diagrams and unit testing.

Multiple Programming Languages
Visual Studio 2010 natively supports the following programming languages:

Visual Basic

Visual C#

Visual C++

Visual F#

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

NET–Based Languages 2-15 Multiple Project Types Visual Studio 2010 supports the development of multiple project types. and the ability to step through the code. It provides an efficient way to test pages locally before you publish or deploy pages to a test. IIS is a Microsoft Web server that is bundled with both client and server implementations of the Windows operating system. Deployment can happen to the local file system. This support for multiple project types enables you to simultaneously work on several projects. and provided to you by QuickStart Intelligence. see Module 7. Integrated Browser Visual Studio 2010 contains a built-in browser that is based on Windows Internet Explorer®. staging.NET Web Applications.NET Web applications and XML Web services." Deployment Support After you have finished developing a Web site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. File Transfer Protocol (FTP) is a network protocol that is used to exchange and manipulate files over a network. Note: You must use IIS to host the deployed Web application. • Publish Web Site. which generally means you want to open the target Web site with the Web Development server. . you do not have to change development environments or learn new tool interfaces or languages.com or by calling +1 800-785-3448. or an FTP server. The Publish Web Site utility compiles a Web site into a set of executable files that can be copied to the target server. Debugging support includes breakpoints. The Licensed Content is licensed "as-is. The browser is integrated into IDE. "Troubleshooting Microsoft ASP. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. one statement or one procedure at a time. break expressions. This browser accessibility enables you to view your Web site during the development cycle.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .NET Development Server The ASP. 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. Visual Studio 2010 provides the following options for deploying a Web site: • Copy Web Site. or production server. an Internet Information Services (IIS)–based site. you can deploy it to a Web server. including ASP. ASP. Debugging Support Visual Studio 2010 supports debugging from your initial code.NET Web pages on the local computer. redistribute. watch expressions. The latter two can be local and remote. Note: For more information about debugging. The Copy Web Site tool copies the current Web site to a target server. guarantees or conditions. through to the application’s release. instead of having to use another program. and you can access it from multiple windows and menus.NET Development Server is built to run ASP. It is illegal to reprint. The Web server can be either a test server or a production server.

called a solution. Solutions and Projects When you create a project in Visual Studio 2010. A solution enables you to: • Work on multiple projects in the same instance of the IDE. which means the template automatically creates the folders and files that are required for the specific type of project. or resell this content. • Work on items. When you use these templates. These templates contain all the required files. and provided to you by QuickStart Intelligence. you also create a larger container. Please report any unauthorized use of this content to piracy@microsoft. settings. 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. and ensure that the IDE has the correct configuration for the selected project. and options that apply to a group of projects. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . It is illegal to reprint.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. Therefore. redistribute.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. you do not have to set up the infrastructure. This solution can contain multiple projects in the same manner that a project container can contain multiple pages." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. You can use the Solution Explorer—which provides a graphical view of your solution—to organize and manage all of your application projects and files. you can focus on adding functions to your projects. • Manage miscellaneous files that are outside the context of a solution or a project.

NET Web site Creates an ASP. Project template Description Class library Creates reusable classes and components that you can share with other projects. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. It is illegal to reprint.NET Web application with the basic server files that you require for your application. or resell this content.NET Web site with the basic server files that you require for LINQ To SQL Web site your Web site. ASP. guarantees or conditions. . you must first specify the language in which you want to work. along with support for Dynamic Data based on a LINQ To SQL Data Model. ASP. This template creates the necessary file structure that you require to store application information. along with support for Dynamic Data based on an Entity Data Model.NET server control Creates custom ASP. WCF services are components that are available over the Internet.NET Web site with the basic server files that you require for your Web site. 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. redistribute.NET Web application Creates an ASP. The following table lists some of the available Visual Basic and Visual C# project templates.NET Dynamic Data Creates an ASP. To select the correct template.NET server controls. You must manually add any references.NET–Based Languages 2-17 Project Templates Visual Studio 2010 includes multiple project templates that are sorted by language and type.NET Ajax server control Creates custom ASP.NET Web site with the basic server files that you require for Entities Web site your Web site.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . This template adds the necessary project items that you require to create the control. WCF service application Creates a WCF service that can be consumed by other WCF services or applications on a network. or components. and are designed to interact only with other Web applications.NET Ajax server controls. ASP. ASP. ASP. The Licensed Content is licensed "as-is. This template adds the necessary project items that you require to create the control. files.com or by calling +1 800-785-3448. ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Dynamic Data Creates an ASP. Empty project Creates your own project type.

It displays code for editing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. the editor is split into two windows: one window for the design surface of the Web page. The Editor Window The Editor window is the primary interface window in Visual Studio 2010. and the Source mode: • In the Design mode. and the Method Name list on the right. or resell this content. You can click the Auto Hide button to turn static windows into pull-out windows. The Class Name This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448. guarantees or conditions.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. two drop-down lists appear at the upper part of the window—the Class Name list on the left. and provides a graphical interface for control placement in the form of a what you see is what you get (WYSIWYG) interface. menus. You can then manage the logical design of your application by modifying the default Web control code. When you add a control to a Web page in Design mode. You can use drag-and-drop editing to create the visual design of your application. • In the Source mode. and provided to you by QuickStart Intelligence. and toolbars. redistribute. Visual Studio 2010 highlights your code so that the different elements—such as variable names and keywords—are instantly identifiable. you can use the editor to move controls and graphic elements around the window by using a drag-and-drop operation. Many of the features of Visual Studio 2010 are available from several of the IDE windows. • In the Split mode. It is illegal to reprint. Visual Studio 2010 adds the supporting code and default properties to the Web Form. You can move or hide IDE windows. the Split mode. and enables you to build functions by simply selecting from the list of available syntax. depending on your personal preference. . The IntelliSense feature provides you with auto-completion suggestions. The window options for the editor are the Design mode. You can then switch to the Source mode and edit that code. The Licensed Content is licensed "as-is. You can use the View menu to select the windows that you want to display. and the other window for the source code of the Web page. When you use the Editor window in the Source mode.

project. . or solution. It is illegal to reprint.NET–Based Languages 2-19 list shows all the controls on the associated form. the Method Name list shows all the events for that control. project-related folders. and sub-items This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . which lists a hierarchy of project files. From this pane. This feature enables you to change properties at the project level or page level. redistribute. If you click a control name in the list. and provided to you by QuickStart Intelligence. By using the Class Name and Method Name lists together. Events are actions that the control can perform and your application can interpret. Please report any unauthorized use of this content to piracy@microsoft. To view the available options—including adding." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. you can quickly locate and edit the code in your application.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. 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. or resell this content. building and editing pages—right-click the file. Solution Explorer Pane Clicking on the Solution Explorer tab displays the Solution Explorer pane. • Select an item in the Solution Explorer pane to view its properties in the Properties window. you can: • Use a drag-and-drop operation to rearrange items.

click Comments. The Licensed Content is licensed "as-is. guarantees or conditions. You can add TODO comments to your code for tasks that you must complete.com or by calling +1 800-785-3448. The Categories list displays user tasks and comments: • User Tasks. and provided to you by QuickStart Intelligence. To access this section of code. When you create or select an item. It is illegal to reprint. classes. Task List Window You can use the Task List window to track the status of tasks as you develop your application. in the Categories list. You can add tasks and set the description. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. click User Tasks. redistribute. and controls by using a single Properties window. . To add a task in the Categories list. and completion of the tasks. priority. • Comments.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. the Properties pane automatically displays the related properties." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and then click Create User Task. and then double-click the TODO comment.

Element-based style rules are organized the same way. but they appear under a separate heading titled.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . and as styles defined on the page. If the style rule is defined on the page.css file that contains the style. and create a new CSS style by opening the Styles dialog box and attaching an existing style sheet to the current page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET–Based Languages 2-21 Output Pane The Output pane displays status messages for various features in IDE. . You can also use the window to move the location of a style within the set of CSS style rules. It also lists style rules that are defined on the page. The Licensed Content is licensed "as-is. guarantees or conditions. or resell this content. Manage Styles Window The Manage Styles window lists all CSS style rules that are defined in the page's external CSS. it appears under Current Page. Contextual Selectors.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. but not as inline styles. both as inline styles. It is illegal to reprint. You can program your own applications to write diagnostic messages to the window at run time. Classbased and ID-based style rules appear under the name of the external . and to move from the style element on the page to an external style sheet. Please report any unauthorized use of this content to piracy@microsoft. This includes style rules that are defined in external style sheets. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. You can use the Manage Styles window to move styles from an external style sheet to the style element on the page. Apply Styles Window The Apply Styles window lists all the CSS style rules that are defined for a page.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and display only if they are available to use. Contains objects that allow your application to connect and access the data in Microsoft SQL Server® and other databases. The Licensed Content is licensed "as-is. Contains standard controls that you can use to build the UI for a Web page. and provided to you by QuickStart Intelligence. • Reporting. • Data. or resell this content. Contains Web Parts for a Web site. • Navigation. • WebParts. Contains navigational controls for a Web site. • HTML. Contains a set of server controls used for creating SQL Server reports. It is illegal to reprint. • Ajax Extensions. Contains a set of Hypertext Markup Language (HTML) controls that you can add to your Web page.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. • Validation. • Dynamic Data. redistribute. Contains controls for use with a Dynamic Data Web application. Common Web application categories include: • Standard. • Login. Please report any unauthorized use of this content to piracy@microsoft. Contains login controls for a Web site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Contains a set of server controls used for implementing Ajax functionality. .com or by calling +1 800-785-3448. guarantees or conditions. Contains a number of different validation controls that are used to validate user input in Web server controls. These controls can run on either the server side or the client side. The tools are grouped by category in the Toolbox pane.

." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. It is illegal to reprint. redistribute. and provided to you by QuickStart Intelligence.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . or resell this content. guarantees or conditions.NET–Based 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.

com or by calling +1 800-785-3448. You can change the default Visual Studio 2010 startup settings from the Options dialog box. • Show the Open Project dialog box. or resell this content. and provided to you by QuickStart Intelligence. In addition to the options mentioned above. or read the latest development articles. • Show an empty environment. You can also access it by clicking Start Page on the View menu. . which you can open or remove from the list by right-clicking the project. These check boxes are both selected by default." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. • Show the Start Page. • Show the New Project dialog box. to enable one of the following actions at startup: • Display the home page set in your browser. By default. guarantees or conditions. You can also open the folder in which the project is located. It is illegal to reprint. the Start Page displays when opening Visual Studio 2010. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or Show page on startup by selecting or clearing the corresponding check boxes located in the lower-left corner of the Start page. learn about upcoming product releases and conferences. Recent Projects Pane The Recent Projects pane in the Start Page displays a list of recently updated projects. from the context menu. there are also two options on the Start Page that affect how and when the Start Page opens and closes.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. You can choose whether or not to Close page after project load. Please report any unauthorized use of this content to piracy@microsoft. • Open the last loaded solution.

and other resources? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. On the Tools menu. 2. technical articles.com or by calling +1 800-785-3448. and then click OK. click Options. 3. but you can specify a custom RSS feed. and other resources that can help you increase your productivity and learn about features of the product. It includes categories for Development Process. Changing the Item Displayed at Development Environment Startup 1. and then click Startup. Web sites. the ASP. In addition." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and follows the same format as the Get Started tab.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . and provided to you by QuickStart Intelligence. In the bottom left corner of the Options dialog box. ensure the Show all settings option is selected. From the At startup drop-down list. technical articles. Question: Which area and tab of the Start Page displays a list of Help topics. guarantees or conditions. By default. Customizing the Start Page You can customize the news channel that the Start Page uses. and Additional Tools. MSDN Resources. Web sites.NET News RSS feed is used. and remove entries from the Recent Projects pane. . 4. you can stop the Start Page from appearing every time you start Visual Studio. 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. Expand Environment.NET–Based Languages 2-25 Get Started Tab The Get Started tab of the Content area displays a list of Help topics. redistribute. Please report any unauthorized use of this content to piracy@microsoft. Guidance and Resources Tab The Guidance and Resources tab of the Content area on the Start page provides general information on coding and development. or resell this content. choose one of the options. Your changes are implemented the next time you start Visual Studio. The Licensed Content is licensed "as-is. It is illegal to reprint.

NET Web application from start to finish.NET Web application pages. The Licensed Content is licensed "as-is. redistribute. In this lesson. Lesson Objectives After completing this lesson." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Choose between a Web site project and a Web application project. you will be able to: • Describe how to develop ASP. and view a simple ASP.NET Web application. .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. • Deploy a Web application. Visual Studio 2010 creates a number of files that support your development.NET Web application. • Describe Web application project files and folders in Visual Studio 2010. you will learn how to create. It is illegal to reprint. When you work with projects. build. • Describe Web site project files and folders in Visual Studio 2010. and view an ASP. • Identify Web application files. and provided to you by QuickStart Intelligence. • Explain how to create. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. build. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448. guarantees or conditions.

"Creating a Microsoft ASP. and write the code. guarantees or conditions. The design specification is the blueprint that you use to create a Web application. or by using code in the Editor window. you can design your application more efficiently if you have a clear understanding of user requirements and the feature set. Create a design specification.NET Web Form. or resell this content. When you select a new project template. To create an ASP. Create a new project. To create the interface for your Web application. and provided to you by QuickStart Intelligence.NET Web Form. Although Visual Studio 2010 provides tools to help you quickly develop a solution." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. and refactor current classes by using this visual design environment. This transfer enables you to track your development against the specification. As part of this initial project creation.NET–Based Languages 2-27 Web Application Development Process Key Points Visual Studio 2010 contains everything that you require to build your own ASP.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . By using a design specification.NET Web application or Web site from start to finish. You should take time to design your application before you write any code. you should transfer the main coding tasks from your design specification into the Visual Studio 2010 Task List. you can set their properties by using the table in the Properties window. As you add objects to a form. see Module 3. You can easily create new classes. you will also save time by minimizing the potential for rewriting unsuitable or redundant code. you must first place controls and objects on the Web pages by using the Editor window in the Design mode.NET Web application by using Visual Studio 2010. Visual Studio 2010 automatically creates the files and the default code that are required to support the project. Create the interface. Note: For more information about adding controls to an ASP. which enables you to visualize the structure of classes and their relationships. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. . Please report any unauthorized use of this content to piracy@microsoft. Visual Studio provides the Class Designer. 3." This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. you must perform the following steps: 1. 2.

"Adding Functionality to a Microsoft ASP. You usually build only your project or solution. and provided to you by QuickStart Intelligence. redistribute. see Module 14. or resell this content. you create a release build of the project." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note: For more information about debugging. Visual Studio builds all the code on the Web pages and other class files into a dynamic-link library (DLL). guarantees or conditions. you deploy the necessary files to a Web server." 6. When you are ready to release the project. called an assembly. Visual Studio deletes any intermediate and output files. • Build. from which you can build new instances of the intermediate and output files. but rather is iteratively done throughout the development process. You can build. Only the project and component files remain. see Module 4.NET Web Applications. . Build a project. Note: For more information about writing code in ASP. This means you really never have to clean your project or solution. or the entire solution. Please report any unauthorized use of this content to piracy@microsoft. Visual Studio 2010 offers numerous debugging tools that you can use to find and fix errors in your application.NET Web Application.NET Web Forms. see Module 7. rebuild. When you first develop a project. The Licensed Content is licensed "as-is. It is illegal to reprint. Note: For more information about deploying an ASP. you must run a debug build of the application to ensure that the code works as expected. Deploy. 5. When you build a project. Testing and debugging is not a one-time step." 4.com or by calling +1 800-785-3448.NET Web Form and its objects." 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. Visual Studio 2010 has two build options: debug and release.NET Web application. Visual Studio cleans the project or solution first. You may also have to write code to add business logic. • Clean. and you have built a release build. or clean an individual project. and to access data.NET Web Form. When your project is fully debugged.QuickStart Intelligence 2-28 Introduction to Web Development with Microsoft® Visual Studio® 2010 After you set the initial properties for the ASP. you build debug versions. Every time you make a major change to the application code. and then builds all project files and components. "Configuring and Deploying a Microsoft ASP. • Rebuild. Visual Studio compiles only those project files and components that have changed since the last build. "Troubleshooting Microsoft ASP. you can write the event procedures that will run when different actions are performed on a control or object. Test and debug. You must perform a rebuild when the project versions target out-of-sync components.

settings. including MDF files. Settings. Resources.vb. and Settings. Web Application Project Template Files When you create a Web application by using the ASP.Designer.vb. and it stores global information. including Application. redistribute.Designer. The file is a map of all of the various files that link one or more projects together.myapp.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Web application project offers tighter control than the Web Site project by explicitly defining resources.NET–Based Languages 2-29 Web Application Project Files and Folders Key Points In Visual Studio 2010. which contains general information—including assembly This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.vb file. Type Name Description Folders App_Data A folder that contains application data files. Obj A folder that contains subfolders for your build configurations.Designer.NET Web application project template. Bin A folder that contains the project assembly file. or resell this content.sln solution file. and provided to you by QuickStart Intelligence.vb.NET Web application project template. . and other data store files. It is illegal to reprint. The Licensed Content is licensed "as-is. Application. In addition. Resources.resx. guarantees or conditions. My Project A Visual Basic–specific folder that includes a number of autogenerated code and XML files to support the project infrastructure (settings and resources).QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . the folder contains the AssemblyInfo. The Solution folder also contains the subfolders and files that are listed in the following table. Visual Studio 2010 creates a Solution folder that contains the . you can create a Web application by using the ASP. XML files.

QuickStart Intelligence 2-30 Introduction to Web Development with Microsoft® Visual Studio® 2010 Type Name Description version and assembly attributes—about the assembly.config The Web configuration file that contains the configuration settings for the Web application.dll file that is created from all the code-behind pages that make up a Web application.csproj. A solution file. and a project typically contains multiple items.aspx.cs file. An assembly is one . . or resell this content.designer.vbproj. WebApplicationName.user The project settings for the user. followed by the . the solution file only contains information about the Web application project.csproj or WebApplicationName.vbproj The XML document that contains references to all project items—such as forms and classes—in addition to project references and compilation options.NET Web Form. without referencing any item in each individual project. This file has the same name as the project. or to multiple projects in the solution. It is illegal to reprint.NET Web application project. • Work on miscellaneous files that are independent from solutions or projects. data connections.cs or Default.vb The design-time partial class for the Web Form. while you focus on project development.aspx. Default.designer. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. folders. WebApplicationName.aspx. These containers enable you to utilize IDE in the following ways: • Manage settings for your entire solution. or for individual projects.aspx. Containers: Solutions and Projects Solutions and projects contain items that represent the references. . The Licensed Content is licensed "as-is. When you build an ASP.sln extension. This file contains general information about the assembly.vb The code-behind file for the Web Form. Web.use r Note: The Bin and Obj folders are hidden by default. guarantees or conditions. To open a previously created ASP. including the assembly version and assembly attributes.cs or Default. is also created. • Add items to the solution. redistribute. Default. Visual Studio 2010 creates an assembly in the Bin folder of the project. • Use Solution Explorer to manage the file management details. Files Properties A Visual C#–specific folder that includes the AssemblyInfo. or WebApplicationName. and it contains information about the projects and miscellaneous nonproject-specific files." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In Solution Explorer. open the solution file in Visual Studio 2010. use the Show All Files button to display the folders. A solution can contain multiple projects.com or by calling +1 800-785-3448.aspx The default ASP. and files that you need to create your application.NET Web application project. Default. Initially.sln. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

Please report any unauthorized use of this content to piracy@microsoft. redistribute. or resell this content. It is illegal to reprint. Solution items display in the Solution Items folder of Solution Explorer. References. or folders. items can be organized in the following ways: • As project items. The Licensed Content is licensed "as-is.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . guarantees or conditions.NET–Based Languages 2-31 Items: Files. source files. In Solution Explorer. and classes within a project in Solution Explorer. Project items include forms." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . and provided to you by QuickStart Intelligence. • As miscellaneous files that are not associated with either a project or a solution. such as references. and any modifications that you make. The project item organization and display depends on the project template that you select. • As solution items for files that are applicable to your solution as a whole. data connections. and Data Connections Items can be files or other parts of your project.com or by calling +1 800-785-3448. These files display in a Miscellaneous Files folder. which are items that compose your project. Question: What containers does Visual Studio provide? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

all relating to user authentication. or resell this content. This file stores some of the information contained in the project file. this file is by default stored in the Visual Studio 2010\Projects subfolder of the user’s Documents folder. Web Site Project Template Files When you create a Web site by using the ASP. The Web form displays an About this Web site message.aspx.NET Web site project template. About. redistribute. the .aspx.vb or About. However. guarantees or conditions. and provided to you by QuickStart Intelligence. App_Data This folder is for storing data files. but it can also be used for any type of script files.aspx." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and either About. you can create a Web site by using the ASP. This is necessary to identify the content of the Web site project. if you create a Web application project. unlike the Web application project Solution folder. Default. It is illegal to reprint. Scripts This folder contains jQuery script files. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and This is the Default Web Form and the corresponding code-behind file. Folder/file name Description Account This folder contains a number of files. Please report any unauthorized use of this content to piracy@microsoft. such as SQL Server 2008 Express edition database files.NET Web site project template.sln solution file is not contained in this folder.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.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. The Web site project model generally offers more features and additional flexibility in the management of Web applications. .cs This is the About Web Form and the corresponding code-behind file. The Web site project Solution folder contains the subfolders and files listed in the following table.aspx. Instead. Visual Studio 2010 creates a Solution folder for the project. than that of a Web application project model.

Visual Studio 2010 can create multiple assemblies for the Web site. Web Site menu command. Web. 2-33 When you publish a Web site project. To open a previously created ASP.master.com or by calling +1 800-785-3448.vb or Site.NET Web site project.master. The Licensed Content is licensed "as-is.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . Alternatively.aspx.aspx. Global. Open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .asax This is the Global Application File. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. open the Solution file in Visual Studio 2010.vb or Default.NET–Based Languages Folder/file name Description Default.config This is configuration file for the Web site. redistribute. which contains a number of methods relating to the Web Application or the current user session. Site.master. It is illegal to reprint. or resell this content.cs The Web Form is the home page for the Web site. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. you can open the file by using the File. and Site.cs This is the master page and the related code-behind file for the Web site. guarantees or conditions.

The ASP. the user control (. The assembly is the binary unit of deployment. or the ASP. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.aspx) files. all content in the main Web site project folder is automatically part of the project. and your preferred development workflow. Please report any unauthorized use of this content to piracy@microsoft.NET Web site project template creates a project that is folder-based—that is. The choice of a project template depends on your requirements. the Web form (. Some developers will find the Web site project model easy to use.NET Web application project template. redistribute. and provided to you by QuickStart Intelligence. It is illegal to reprint. you must add the new files to the project from within Visual Studio 2010.NET Web site project template. ASP. because resources are defined explicitly in the project file. whereas with a Web application project. you can create a Web application by using either the ASP. . which means that none of the code must be deployed. When building a Web site project. you compile the code to test it. you should deploy the actual source files and rely on ASP.ascx) files. except for code written in the markup files. because resources are defined implicitly by being in a folder. and other static content files. In addition. or resell this content. To deploy a Web site project. guarantees or conditions. This effectively means that you can drag and drop files into this folder.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET dynamic compilation to compile the pages and classes in the application. Other developers will prefer to use the Web application project model in which they have tighter control over their project. must be deployed. all class files included in the project are compiled into a single assembly that is placed in the Bin folder.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. When compiling and building a Web application project.NET Web application project template.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.

and provided to you by QuickStart Intelligence. or resell this content. It is illegal to reprint. Because of the use of dynamic compilation. build an individual page. you must build the entire project. user control files. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . Other reasons for using the Web site project template are that you want to generate one assembly for each page. However. reference pages and user control classes. whereas with a Web site project. the Web form files. there is a distinct advantage to using the Web site project if files that need compiling will be added after the initial deployment. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. which also means that you can have stand-alone classes. and other static content files. or if you need to add pre-build or post-build steps and have more control over the compilation. the reason for choosing the Web application project template is that you need to control the names of the output assemblies. The Licensed Content is licensed "as-is.NET–Based Languages 2-35 To run or debug any page in a Web application project. or not build at all. the Web application project template is the best choice if you need to build a Web application that contains multiple Web projects.com or by calling +1 800-785-3448. you should use the Web application project. if you are concerned about deploying the source code. redistribute. without creating a project file. Alternatively. . In addition. since only the assembly must be deployed with the markup files. you can configure the build options to build the site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or you want to open and edit any directory as a Web project.

aspx.asax is parsed and compiled as a dynamically generated .vb for a Visual Basic project. • Classes.vb.js). Class files use the Visual C# extension. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or Test. WCF services are based on contracts or interfaces and code-behind files (.NET Web Forms (. Web Application Files Visual Studio 2010 supports the following application file types and extensions: • ASP. (. For example.cs for a Visual C# project. It is illegal to reprint.NET Web Forms are supported by a code-behind file that is designated by either the extension WebForm. You can use ASP. You can use WCF services to create services that will be accessed only by other programs. These files are used for containing JavaScript scripts and methods used in your Web application. The Global. see Module 4. "Adding Functionality to a Microsoft ASP. redistribute.com or by calling +1 800-785-3448.asax file—also known as the ASP. .aspx. the full file name for a class file named Test is Test." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.cs). or Visual Basic extension (.vb). you can create different file types to support the development of your Web application. Please report any unauthorized use of this content to piracy@microsoft.vb or .NET Web Forms to build dynamic Web sites that users can access directly.NET Framework class that is derived from the HttpApplication base class. • JavaScript files (. or resell this content. guarantees or conditions.NET application file—is an optional file that contains code for responding to application-level events that are raised by ASP." • Global application classes (Global.cs. Global.asax). ASP.NET or by HttpModules.aspx). At run time. • WCF services (.NET Web Form.cs). and provided to you by QuickStart Intelligence.QuickStart Intelligence 2-36 Introduction to Web Development with Microsoft® Visual Studio® 2010 Web Application Files Key Points In Visual Studio 2010.svc). or the extension WebForm. Note: For more information about code-behind pages.

and spacing—to Web documents. Note: For more information about master pages. or as part of the UI. A single master page defines the look and feel. guarantees or conditions. The web. .sitemap file. • Web.resx).config file.css. • Styles. Styles. This file also contains settings that the application can read. A CSS is a simple mechanism for adding styles—such as fonts. and provided to you by QuickStart Intelligence. see Module 5." • Resource files (. A resource is any non-executable data that is logically deployed with an application. The Web. "Implementing Master Pages and User Controls.config file contains configuration settings that the CLR component reads.sitemap file contains XML elements. • Web. A resource can be displayed in an application as an error message. and persisted objects.master). or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. images. It is illegal to reprint.css is the default style sheet file for the Web application. and the global application classes that support a project. including strings. The Licensed Content is licensed "as-is. Storing your data in a resource file enables you to change the data without recompiling your entire application. or items that can be used to display a Menu or breadcrumb in your Web application. such as the assembly binding policy and WCF services.com or by calling +1 800-785-3448.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . redistribute. Resources can contain data in a number of forms. Master pages allow you to create a consistent layout for the pages in your application. Please report any unauthorized use of this content to piracy@microsoft. but will have their own extensions? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Question: What are examples of files that are not based on a programming language.NET–Based Languages • 2-37 Master page files (. colors. and standard behavior that you want for all of the pages (or a group of pages) in your application.

Demonstration Steps 1. • In the Default.aspx window. double-click the TextBox control. b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. c. click either Visual Basic or Visual C#. point to All Programs. and provided to you by QuickStart Intelligence. click ASP. in the left pane. and then double-click the Button control. Create a Web application project. Add code for the Click event handler of the Button control. guarantees or conditions. click Design. and then click Microsoft Visual Studio 2010. redistribute. In the Toolbox. and then click OK. In the New Project dialog box. expand Standard. and then add the following code to the Click event handler.NET Web Application. In the Start Page – Microsoft Visual Studio window. double-click the Button control. It is illegal to reprint. a. d. and then click ENTER.Text = "You clicked the button" [Visual C#] This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. c. • 2. or resell this content. b. Open Visual Studio 2010. In the Toolbox. In the middle pane. In the Default. click New Project. click p. 4. a. on the File menu.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. Please report any unauthorized use of this content to piracy@microsoft. 3.aspx window. In Design view. Add TextBox and Button controls to the Default Web Form. press the RIGHT ARROW key. . under Standard.com or by calling +1 800-785-3448. On the Start menu of 10267A-GEN-DEV. click Microsoft Visual Studio 2010. [Visual Basic] TextBox1. you will see how to create a Web application project. click the text You can also.

Text = "You clicked the button". and then click View Source to view the source in Internet Explorer. g. The Licensed Content is licensed "as-is.IsPostBack) { Response. Question: When you create a Web site.aspx window.Write("First time page is loaded") End If End Sub [Visual C#] protected void Page_Load(object sender. } } 6. Run the application in the debug mode. • Type the following code in the Page_Load event handler.IsPostBack Then Response." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. f. click the Close button.aspx. e. It is illegal to reprint. on the Debug menu. redistribute. Please report any unauthorized use of this content to piracy@microsoft.Load If Me. . In the Default.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. ByVal e As System. d. Click the Button to post back to the server. In the http://localhost:1186/Default. click Page on the toolbar.NET–Based Languages 2-39 TextBox1. step through the lines of code by pressing F10. [Visual Basic] Protected Sub Page_Load(ByVal sender As Object. Write code to catch PostBack in the Page_Load event handler.aspx-Original Source window.Write("Server roundtrip due to postback") Else Response. a. Note: If you see a Debugging Not Enabled message box.aspx. click the Close button. In the http://localhost:1186/Default.Write("Server roundtrip due to postback").Write("First time page is loaded"). click Start Debugging. c. click OK.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . or resell this content. } else { Response. 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. In the WebApplication1 – Microsoft Visual Studio (Administrator) window. Build and debug the solution. Place the breakpoint by clicking the mouse at the beginning of the code where you check for the PostBack. EventArgs e) { if (this. and step through the lines of code by pressing the F10 key.EventArgs) Handles Me. 5.vb or Default.cs code window. guarantees or conditions. b. When the browser opens after the first debugging session.

It is illegal to reprint. guarantees or conditions. IIS supports most Windows® operating system versions. The Licensed Content is licensed "as-is. all depending on the various test phases a Web application goes through. However. you deploy the Web application on the test server after you complete the development and personal testing. Windows Vista®. and many of the editions of Windows XP. you can deploy it to the production server.NET Web site or the ASP. There is often more than one test server. redistribute. . Servers In a development environment." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.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 application—whether based on the ASP. and Windows 7. Please report any unauthorized use of this content to piracy@microsoft.NET Web application template—you will need to build and deploy the Web application on a test or production server. IIS Microsoft provides an IIS Web server for hosting Web applications. these are covered in later modules. and provided to you by QuickStart Intelligence. Deployment Options There are a number of deployment options available with Visual Studio 2010. The application is then thoroughly tested.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. After the Web application has been fully tested and released. Visual Studio 2010 helps you build and deploy your Web application. and a user acceptance test (UAT). including an integration test. including all editions of Windows Server®.

Before you begin the lab. Build and deploy an ASP. Add a server control to a Web Form and configure its properties. 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. In addition. Create a simple ASP. you will use the available virtual machine environment.NET Web site. you will be able to: 1. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.com or by calling +1 800-785-3448.NET Web site project. The Licensed Content is licensed "as-is. you will create a simple ASP. Objectives After completing this lab.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . refer to the steps provided in Section 2 of the lab page.NET–Based Languages Note: You can perform tasks in this lab either by using the Visual Basic or Visual C# programming language. 2. If you are using Visual C# as your programming language. to a Web Form. or resell this content. redistribute. then add a server control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. If you are using Visual Basic as your programming language.NET Web site project. refer to the steps provided in Section 1 of the lab page. you will build and deploy an ASP.NET–Based Languages 2-41 Lab: Creating Web Applications by Using Microsoft Visual Studio 2010 and Microsoft . 3. you must: • Start the 10267A-GEN-DEV virtual machine. Introduction In this lab. It is illegal to reprint.NET Web site. Lab Setup For this lab. . and then configure its properties.

." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or resell this content.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.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. Please report any unauthorized use of this content to piracy@microsoft.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Your organization uses Microsoft . Ltd. and manage its customer information.NET–Based Languages 2-43 Lab Scenario You are a developer at Contoso.NET. your organization plans to create a Web site to manage customer data and services in ASP. You are assigned the task of creating the Web site by using the ASP.com or by calling +1 800-785-3448. In addition to external Customers Web site. customize.NET applications to create.NET Web site template. which is a large organization with a global customer base. . The Licensed Content is licensed "as-is. guarantees or conditions. Your organization decides to create a Web site for fast and easy interaction with its customers. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . It is illegal to reprint. and then deploying the Web site to an IIS virtual directory. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. redistribute.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.css file to the Styles folder.QuickStart Intelligence 2-44 Introduction to Web Development with Microsoft® Visual Studio® 2010 Section 1: Visual C# Exercise 1: Creating an ASP. by using the Add Existing Item dialog box.  Task 1: Create an empty ASP. click Solution 'CustomerManagement' (1 project).sln. Use a static port with the ASP. Styles. 4. Right-click the Web site in Solution Explorer. • In the Properties window. with the password. by using the Save As command on the File menu. • Create the empty CustomerManagement Web site with the following settings. • In the Properties window.com or by calling +1 800-785-3448. in the Port number box.NET Web site.NET Development server. The Licensed Content is licensed "as-is. 3. in the Use dynamic ports list.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET site. and added styles to the Web site. Add an existing CSS file to the Web site. Please report any unauthorized use of this content to piracy@microsoft. click False. • Open Microsoft Visual Studio 2010.NET Development server • In Solution Explorer. or resell this content. and provided to you by QuickStart Intelligence. by using the New Web Site dialog box: • Template: Empty ASP. It is illegal to reprint. guarantees or conditions. • Add the D:\Labfiles\Starter\M2\Styles\Site. redistribute.  Task 3: Save the Solution file • In Solution Explorer.NET Web Site The main tasks for this exercise are as follows: 1. 2. Note: It may take a few seconds before the Port number property is ready for editing after setting the Use dynamic ports property. you will have created a file system–based ASP. type 1110. and then press ENTER. Create an empty ASP. Save the Solution file.NET Web site • Log on to the 10267A-GEN-DEV virtual machine as Student. Pa$$w0rd. and then save the solution file as D:\Labfiles\Starter\M2\CS \CustomerManagement.  Task 4: Add an existing CSS file to the Web site • Create a folder named. Results: After completing this exercise. . and then click New Folder. in the CustomerManagement Web site. click D:\Labfiles\Starter\M2\CS \CustomerManagement.

by using the View in Browser context menu command.aspx window. Add the application title to the default Web Form.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft .  Task 1: Add a default Web Form to the Web site • Add the Default." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. by using the Open Project dialog box.com or by calling +1 800-785-3448. div. redistribute. and then view the source rendered to the browser. The Licensed Content is licensed "as-is. 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. 5. Add a default Web Form to the Web site. and set its Text attribute to Customer Management. • Add a Literal control from the Toolbox to the div element in the Default. and then save the changes. • Close Visual Studio 2010.NET–Based Languages 2-45 Exercise 2: Adding and Configuring Server Controls in Web Forms The main tasks for this exercise are as follows: 1.  Task 2: Close Visual Studio 2010 • Save modified files. • Save the changes.aspx Web Form to the CustomerManagement Web site by using the Add New Item dialog box. Apply the predefined style to the Web Form. guarantees or conditions. • Set the Visible property of the Literal control to False by using the Properties window. and view the default Web Form in a Web browser. • Close the open Internet Explorer windows. 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. • View the Web Form in the browser. and provided to you by QuickStart Intelligence. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M2\CS folder. • Set the Visible property of the Literal control to True. by using the Properties window. Close Visual Studio 2010. It is illegal to reprint.  Task 3: Add the application title to the default Web Form • Open Microsoft Visual Studio 2010 as an administrator. . are empty. and body. by using the Run as administrator command on the context menu. and ID property to AppTitleLiteral. 3. or resell this content. 4. 2. where you can see the elements such as form. Set the control properties of the default Web Form. Note: The Default Web Form displays in Source view. Set the Styles property of the div element by using the following properties in the Modify Style dialog box. Please report any unauthorized use of this content to piracy@microsoft. by using the Source command on the View menu of Internet Explorer.

.  Task 5: Apply the predefined style to the Web Form • View the changes in the Source view. guarantees or conditions. and provided to you by QuickStart Intelligence. next to the title element. and view the default Web Form in a Web browser. or resell this content. you will have designed the initial version of the default Web Form for your Web site. • Set the Class property of the div element to appTitle. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Save the changes. and then remove the specific styles applied for the Styles property. • Add a reference to the Site.com or by calling +1 800-785-3448. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.aspx window.css file to the Default. by using the Properties window. Note: You can now view the changes that you have made to the Literal control. redistribute.QuickStart Intelligence 2-46 Introduction to Web Development with Microsoft® Visual Studio® 2010 • • Font-size: 22 • Color: Gray Save the changes. Results: After completing this exercise. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and view the default Web Form in a Web browser.css file in the Styles folder from within the head element by dragging the Styles/Site.

 Task 2: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. guarantees or conditions. by selecting all files and folders in the left pane of the Copy Web Site tool. by selecting Default Web Site. It is illegal to reprint. and then clicking the Copy selected files from source to remote web site button.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . or resell this content. • Create a new virtual directory below the Default 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. Please report any unauthorized use of this content to piracy@microsoft.NET–Based Languages 2-47 Exercise 3: Building and Deploying an ASP. 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. and then clicking the Create New Virtual Directory button. and provided to you by QuickStart Intelligence. by selecting the Web site in Solution Explorer and then using the Web site menu." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Results: After completing this exercise. • Open the Copy Web Site tool. you will have built and deployed the CustomerManagement Web site to the local IIS.NET Web Application The main task for this exercise is to build and deploy the CustomerManagement Web site. . • Connect to local IIS in the Copy Web Site tool. • View the deployed Web site in Internet Explorer at the address http://localhost:1112/CustomerManagement. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. • Revert the changes made to the 10267A-GEN-DEV virtual machine. • Copy the CustomerManagement Web site to the new virtual directory on the local IIS.

The Licensed Content is licensed "as-is.css file to the Styles folder. you will have created a file system–based ASP. Add an existing CSS file to the Web site. and added styles to the Web site.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. Use a static port with the ASP. Pa$$w0rd. and then save the solution file as D:\Labfiles\Starter\M2\VB \CustomerManagement. . Save the Solution file. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Open Microsoft Visual Studio 2010.NET Web Site The main tasks for this exercise are as follows: 1. type 1111.NET Web site. 2. Create an empty ASP. • In the Properties window. Note: It may take a few seconds before the Port number property is ready for editing after setting the Use dynamic ports property. or resell this content.  Task 1: Create an empty ASP. redistribute. and then press ENTER. click D:\Labfiles\Starter\M2\VB \CustomerManagement. with the password. in the CustomerManagement Web site • Add the D:\Labfiles\Starter\M2\Styles\Site. by using the Save As command on the File menu. click Solution 'CustomerManagement' (1 project). 3. by using the New Web Site dialog box: • Template: Empty ASP. It is illegal to reprint.NET site. in the Use dynamic ports list.NET Development server.NET Web site • Log on to the 10267A-GEN-DEV virtual machine as Student.NET Development server • In Solution Explorer. click False. guarantees or conditions.  Task 4: Add an existing CSS file to the Web site • Create a folder named Styles. • Create the empty CustomerManagement Web site with the following settings. in the Port number box. and provided to you by QuickStart Intelligence. 4. • In the Properties window.  Task 3: Save the Solution file • In Solution Explorer. by using the Add Existing Item dialog box." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Results: After completing this exercise.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. Please report any unauthorized use of this content to piracy@microsoft.sln.

 Task 2: Close Visual Studio 2010 • Save modified files. and then view the source rendered to the browser. and provided to you by QuickStart Intelligence. • Close the open Internet Explorer windows. guarantees or conditions. by using the View in Browser context menu command.NET–Based Languages 2-49 Exercise 2: Adding and Configuring Server Controls in Web Forms The main tasks for this exercise are as follows: 1. are empty. 5. • View the Web Form in the browser. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. and then save the changes. by using the Properties window.aspx window. Note: You can now view the text that you have entered in the Literal control. • Save the changes. by using the Open Project dialog box. 2.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. Set the control properties of the default Web Form. • Set the Visible property of the Literal control to True." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . 4. where you can notice that the elements such as form. and ID property to AppTitleLiteral. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M2\VB folder.  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.com or by calling +1 800-785-3448.  Task 4: Set the control properties of the default Web Form • Open the default Web Form in Design view. redistribute. Apply the predefined style to the Web Form.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . div. Add a default Web Form to the Web site. and body. 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. • Set the Visible property of the Literal control to False by using the Properties window. and view the default Web Form in a Web browser. The Licensed Content is licensed "as-is. or resell this content. • Set the Styles property of the div element by using the following properties in the Modify Style dialog box. and set its Text attribute to Customer Management. by using the Source command on the View menu of Internet Explorer. Close Visual Studio 2010. 3. • Close Visual Studio 2010.  Task 1: Add a default Web Form to the Web site • Add the Default. Add the application title to the default Web Form. • Add a Literal control from the Toolbox to the div element in the Default.

you will have designed the initial version of the default Web Form for your Web site. Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Result: After completing this exercise. . The Licensed Content is licensed "as-is.aspx window. • Save the changes. Note: You can now view the changes that you have made to the Literal control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. and view the default Web Form in a Web browser.css file to the Default. • Add a reference to the Site. redistribute.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. or resell this content. and provided to you by QuickStart Intelligence. It is illegal to reprint.  Task 5: Apply the predefined style to the Web Form • View the changes in the Source view. next to the title element. by using the Properties window. and then remove the specific styles applied for the Styles property. and view the default Web Form in a Web browser.css file in the Styles folder from within the head element by dragging the Styles/Site. guarantees or conditions. • Set the Class property of the div element to appTitle.

NET Web Application The main task for this exercise is to build and deploy the CustomerManagement Web site. by selecting Default Web Site. It is illegal to reprint. or resell this content.  Task 2: Turn off the virtual machine and revert the changes. 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. by selecting all files and folders in the left pane of the Copy Web Site tool. . Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. and then clicking the Create New Virtual Directory button. • Revert the changes made to the 10267A-GEN-DEV virtual machine." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . Result: After completing this exercise. and provided to you by QuickStart Intelligence. and then clicking the Copy selected files from source to remote web site button. you will have built and deployed the CustomerManagement Web site to the local IIS. • 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. • View the deployed Web site in Internet Explorer at the address http://localhost:1112/CustomerManagement. • Copy the CustomerManagement Web site to the new virtual directory on the local IIS. redistribute. and then using the Website menu.  Task 1: Build and deploy the CustomerManagement Web site • Open the Copy Web Site tool by selecting the Web site in Solution Explorer. guarantees or conditions. • Create a new virtual directory below the Default Web Site. • Connect to local IIS in the Copy Web Site tool. The Licensed Content is licensed "as-is.NET–Based Languages 2-51 Exercise 3: Building and Deploying an ASP.

NET Web Form (. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 2-52 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Review 1. . It is illegal to reprint. or resell this content. 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. redistribute.aspx) has an associated code-behind file? 3.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Can you think of a reason why an ASP. The Licensed Content is licensed "as-is. guarantees or conditions. How did you create a Web site? 2.

guarantees or conditions. Why would you create a component for a Web application? Real-World Issues and Scenarios 1. You want to create a WCF service. 5. Visual Studio IDE This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence Creating Web Applications by Using Microsoft® Visual Studio® 2010 and Microsoft . Visual Studio IDE Solution Explorer Displays the hierarchy of project files. redistribute. Please report any unauthorized use of this content to piracy@microsoft. .NET Framework. You want to create a reusable component that you can share with other projects. What is the easiest way to implement this? Use the WCF Service Application project template. List some of the languages that are currently supported by the . How would you select a .com or by calling +1 800-785-3448. What role does common language runtime play in running an ASP.NET–Based Languages 2-53 Module Review and Takeaways Review Questions and Answers 1. It is illegal to reprint. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. 2. Tools Tool Function Where to find it Editor window Displays code for editing and a graphical interface for control placement." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and enables you to move and modify files. or resell this content. What is the easiest way to implement this? Use the Class Library project template. What is the role of the JIT compilation? 4.NET-based programming language to create a new Web application project? 2.NET page? 3.

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

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. It is illegal to reprint. guarantees or conditions. or resell this content.QuickStart Intelligence Creating a Microsoft® ASP.NET Web Form 3-1 Module 3 Creating a Microsoft® ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. Microsoft Visual Studio provides an intuitive drag-and-drop interface to help create the UI for your Web application.QuickStart Intelligence 3-2 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Overview Microsoft® ASP. redistribute. A Web Form presents information to the user in any type of browser. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Forms are the user interface (UI) elements that give your Web applications their look and feel. and it implements application logic by using server-side code. and provided to you by QuickStart Intelligence. guarantees or conditions. you will learn how to create Web Forms. In this module. . and populate them with server controls. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

NET Web Form. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Form. and provided to you by QuickStart Intelligence.NET Web Form 3-3 Lesson 1 Creating Web Forms Web Forms consist of a combination of markup. Lesson Objectives After completing this lesson. or . code." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx pages. You will also learn how to identify the key characteristics of Web Forms. Please report any unauthorized use of this content to piracy@microsoft. Web Forms are commonly referred to as ASP. You can create Web Forms by using Microsoft Visual Basic® or Microsoft Visual C#®. you will learn what a Web Form is. or resell this content. .NET pages. • Explain how to create an ASP. such as Internet Information Services (IIS). In this lesson. you will be able to: • Describe an ASP.com or by calling +1 800-785-3448. you can choose whether or not to place the code in a separate file. guarantees or conditions. and how to create a Web Form. It is illegal to reprint. and controls that run on a Web server. When creating Web Forms. redistribute. The Licensed Content is licensed "as-is.QuickStart Intelligence Creating a Microsoft® ASP.

com or by calling +1 800-785-3448. Page Directives. and provided to you by QuickStart Intelligence. • The FORM element and associated attributes define how groups of controls are processed. Please report any unauthorized use of this content to piracy@microsoft. By contrast. and often consist of two separate files: • The .aspx file that contains the UI for the Web Form. guarantees or conditions. and Elements Five levels of directives. Declarations. On a traditional Web page. redistribute.cs (Virtual C# code) file that contains the supporting code. • The BODY element and associated attributes defines and contains all the content a page. • The HTML element and associated attributes verify that the Web Form contains HTML elements. and elements define the functions of a Web Form: • The Page directive and associated attributes define global functions.aspx Extension • Web Forms have an . It is illegal to reprint. declarations. while the page processing remains on the server. However. This split between the client-side interface and the server-side code is a crucial difference between Web Forms and traditional Web pages. • The !DOCTYPE element and associated attributes specify the document type definition (DTD) to which the Web Form conforms. This split between the client-side interface and the server-side code increases the number of supported browsers. and send it to the browser. Web Forms generate Hypertext Markup Language (HTML). controls that run the UI remain on the Web server. or resell this content. Web Forms send only the markup and any client-side script to the browser.aspx. • The .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. This file is called the code-behind file. The Licensed Content is licensed "as-is. and enhances the security and functionality of the Web page. The .aspx. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. the browser on the client side processes the code. .aspx extension.vb (Virtual Basic code) or ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

guarantees or conditions. the default value is true. • Title. and it is not case sensitive when the page language is Visual Basic. This attribute is used with the CodeFile attribute. The AutoEventWireUp attribute is used to indicate if the event methods pagelevel events are automatically wired up. For Visual C#. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. handlers are automatically bound to events at run time.aspx. such as Load or Init. [Visual Basic] <%@ Page Title="" Language="VB" CodeFile="Default. The CodeBehind attribute specifies the name of the compiled file that contains the class associated with the page. is automatically wired up to be caught and handled—if you add the corresponding event handler and add some code to it—to the code-behind file. The Language attribute specifies the programming language in which the server-side code on the Web Form is written. The Inherits attribute is case sensitive when the page language is Visual C#.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. It is illegal to reprint.NET first checks for an overload that has the typical event-handler signature Object and EventArgs. When AutoEventWireup is true. However. This includes the code-behind file. 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.NET checks for an overload that has no parameters. which contains the path to the source file for the code-behind class. and on the tab if your browser session is tabbed. where there is no capitalized Default keyword. This attribute is used with Web application projects (WAPs). for instance. or resell this content. This attribute is used together with the inherits attribute to associate the code-behind file carrying the logic that supports the Web Form. The Title attribute specifies the title of the page. You must include only one page directive tag for each Web Form. ASP. • CodeBehind. which is case sensitive. However. the method names do not have to follow a pattern. This means that the Page_Load event. The following examples show the typical attributes for the page directive. • Inherits. the title attribute of the Page directive takes precedence. • Language." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. ASP. Please report any unauthorized use of this content to piracy@microsoft.NET does not require that you explicitly bind event handlers to page events. Some of the values for this attribute are Visual C# and Visual Basic. Instead. This is the same for Visual C#. and displays as the caption of the browser. The CodeFile attribute specifies the path to the referenced code-behind file for a page that uses the two-file configuration. remember that lowercase default is a keyword in Visual C#. Notice how the CodeFile attribute in the preceding examples specifies a file starting with Default.QuickStart Intelligence Creating a Microsoft® ASP. • CodeFile. The Licensed Content is licensed "as-is. The Inherits attribute defines the name of the code-behind class that the page inherits. but the value for the Inherits attribute is set to _Default.aspx. for a new Visual C# and Visual Basic Web Form. such as Page_Load or Page_Init. redistribute.NET Web Form 3-5 Page Directive and Attributes The page directive @ Page defines the page-specific attributes that are used by the ASP. you must explicitly bind event handlers to events. ASP. For each event. ASP.NET page parser and compiler.cs" Inherits="_Default" %> The attributes of a page directive include: • AutoEventWireUp. . If an event handler with this signature is not found. When AutoEventWireup is false. the default value is false.vb" Inherits="_Default" %> [Visual C#] <%@ Page Title="" Language="C#" AutoEventWireup="true" CodeFile="Default. and the values are used to indicate which compiler to use to parse and compile the page. the inline code.NET searches for a method that is named according to the pattern Page_eventname. but for Visual Basic. based on their name and signature. and code declaration blocks on the page. if both are specified. Setting this attribute has the same effect as adding a TITLE element within the HTML element. This attribute is used with Web Site projects (WSP). In that case.

CSS helps separate the markup from the presentation. The HTML Element and Attributes The HTML element and associated attributes identify that the Web Form contains HTML. fonts. the CodeFile and Inherits attributes are used in a two-file configuration.0 Transitional//EN" "http://www. • title. Both of these windows are accessible from the View menu. The Licensed Content is licensed "as-is. It is illegal to reprint. the body element represents the entire surface on which you can render content. In Visual Studio 2010. <body class="body" title="This page. This introduces reuse of styles across more than a single Web Form to cover an entire Web site. the HTML element represents the entire surface on which a document's content can be rendered.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 following is a typical !DOCTYPE element created by Visual Studio 2010. . borders. The HTML element also becomes the positioning container for positioned elements that do not have a positioned parent.. and you can use the Manage Styles window to manage and keep track of all the styles in your Web application."> </body> The attributes of a BODY element include: • class. This element is not rendered. different styles will generally be applied to different pages. for example. Although styles are reused. guarantees or conditions.w3.dtd"> The !DOCTYPE element is generally used to specify the HTML or Extensible HTML (XHTML) version that the Web Form complies with. or resell this content.. The following is a typical HTML element. Note: You can use CSS to describe the look and formatting of a Web Form. In the nonstandards-compliant mode. you can use the Apply Styles window to apply styles to a specific HTML element or Web server control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.org/TR/xhtml1/DTD/xhtml1-transitional. or to style HTML Web pages. a parent element or container that is positioned differently than the default behavior.. You can find more information about the !DOCTYPE declaration element in the Visual Studio 2010 Help. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The following is a typical body element. by specifying the colors. Singlefile Web Forms do not use these attributes. and typically does not contain any attributes.. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. <html> . </html> The BODY Element and Attributes The BODY element and attributes define how objects appear on the client's browser. and layout.com or by calling +1 800-785-3448. 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. redistribute. Please report any unauthorized use of this content to piracy@microsoft. !DOCTYPE Element and Attributes The !DOCTYPE element and associated attributes specify the DTD to which the Web Form conforms. and provided to you by QuickStart Intelligence. The class attribute determines the cascading style sheets (CSS) class that provides the style elements in the body of the Web Form. In the standards-compliant mode.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The method attribute identifies the method for sending control values back to the server. The runat="server" attribute causes the form to post control information back to the ASP. The Licensed Content is licensed "as-is. The following is a typical FORM element. . The <form> tag attributes define how groups of controls are processed. The runat="server" attribute indicates that the form should be processed on the server. This is the default value. Data is passed in name/value pairs in the body of the HTTP request. the form works as a regular HTML form.. or resell this content. 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. Although you can have many HTML forms on a page. Data is passed in a query string.NET page on the server on which the supporting code runs. If the runat attribute is not set to "server" or is omitted. Please report any unauthorized use of this content to piracy@microsoft.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. you can have only one server-side form on an .com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. This id attribute identifies the form server-side code when programmatic access is required.aspx page.QuickStart Intelligence Creating a Microsoft® ASP. <form id="form1" runat="server"> . </form> Attributes of a FORM element include: • id. The options for this attribute are: • • post.. runat. • method. redistribute. guarantees or conditions. It is illegal to reprint. • get.

click New Project. In the Location box. you can use Solution Explorer to add additional Web Forms. It is illegal to reprint. Visual Studio 2010 creates a new Web application. empty Web application or an empty Web site in Visual Studio 2010. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. click Empty ASP. Alternatively. and on the Website menu. right-click an existing Web application project name or Web site project name. In the middle pane. in the left pane. . In the Name and Location boxes.NET Web Application. 4. type the location for the Web site. only a web. 3. 3. In the New Project dialog box. 2. Visual Studio 2010 creates a new Web site. and then click OK. click Empty ASP. in the left pane.  Creating a New ASP. The Licensed Content is licensed "as-is. 4. type the name and location for the project.  Adding a Web Form to an Existing Web Application or Web Site If you are expanding an existing project. click New Web Site.config file is included. or resell this content. in Solution Explorer. 1.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. guarantees or conditions.  Creating a New ASP. and then click Add New Item.NET Web Application Project 1. click Add New Item. In Visual Studio 2010.NET Web Site Project 1. In the middle pane. redistribute. right-click an existing Web application project name or Web site project name.NET Web Site. click Visual Basic or Visual C#. on the File menu. In Visual Studio 2010. on the File menu.com or by calling +1 800-785-3448. In Solution Explorer. click either Visual Basic or Visual C#. and then click OK. 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. In the New Web Site dialog box. or press the CTRL+SHIFT+A keys. Please report any unauthorized use of this content to piracy@microsoft.

In the Name box. 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. . The Licensed Content is licensed "as-is. 4.QuickStart Intelligence Creating a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. in the middle pane. Visual Studio 2010 creates a new Web Form and adds it to the existing Web project or Web site. 3.com or by calling +1 800-785-3448. type the name of the Web Form. and then click Add. redistribute. select the Place code in separate file check box. It is illegal to reprint. and provided to you by QuickStart Intelligence.NET Web Form 3-9 2. In the Add New Item dialog box. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. To create a code-behind file for a Web site project. click the Web Form template.

• Add and configure Web server controls. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. text boxes. • Describe the types of server controls.NET server controls.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will learn how to use ASP. • Determine the appropriate server control for a Web Form. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. redistribute. and lists—are different from standard HTML controls in that the supporting logic runs on the server. These server controls—such as buttons. It is illegal to reprint. you will be able to: • Describe an ASP. and not in the user's browser.NET server controls run on the server and encapsulate UI and other related functionalities.NET server control. or resell this content. guarantees or conditions. • Add and configure HTML server controls. Lesson Objectives After completing this lesson. The Licensed Content is licensed "as-is. In this lesson. Please report any unauthorized use of this content to piracy@microsoft. . • Save the View state of server controls.

server controls require a client script to function correctly.NET Web Form code-behind classes. redistribute. You can use server controls in ASP. or resell this content. guarantees or conditions.com or by calling +1 800-785-3448. If a user has disabled scripting in the browser. the settings. Another feature of server controls is that the View state. The Licensed Content is licensed "as-is. It is illegal to reprint. .NET Web Form 3-11 What Is a Server Control? Key Points ASP. the controls might not function as you intend. see the “Saving View State" topic later in this lesson. <input type="text" value="Submit" runat="server" /> runat="server" Server controls have a runat attribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and the user input for the control are automatically saved when the page passes between the client and the server. However. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET server controls run on the server and encapsulate the UI. most of the intrinsic controls will work correctly with or without client-side scripting. and provided to you by QuickStart Intelligence.QuickStart Intelligence Creating a Microsoft® ASP. and use them to respond to events in ASP. which can only be set to the value of server. Note: In some situations. <asp:Button id="SubmitButton" runat="server" Text="Submit" /> The following is an example of an input HTML server control. The following is an example of a Button Web server control. Traditional HTML elements are stateless and revert to their default settings when the page returns from the server to the client. Please report any unauthorized use of this content to piracy@microsoft. Note: For more information about View state.NET Web Forms.

if the requesting browser supports client-side scripting such as Windows Internet Explorer® 8. <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 following is the XHTML script that you would write to create a text box with the default text “Enter your Username”. you need to determine the event handlers that will be implemented for each server control. and provided to you by QuickStart Intelligence. server controls use a common object model. you can write code for the newest browsers and not be concerned about browser errors. <input name="UsernameTextBox" type="text" value="Enter your Username" id="UsernameTextBox" style="height:25px.NET.width:238px. It is illegal to reprint. the common language runtime creates the following HTML element. For example. when you want to set the background color for a Web server control. However. you always use the same BackColor attribute. The following markup for a Web server control button shows some of the typical attributes of a server control. Your code will work even if users do not have the latest browser versions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.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. For example. 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. regardless of the control.com or by calling +1 800-785-3448. As a Web Form programmer. which is customized for Internet Explorer 8. the controls create server-side code and require more round trips to the server to obtain the same functionality. they share several attributes." /> Because the server control creates customized HTML for the features that are available in the client's browser. or resell this content. guarantees or conditions. Common Object Model In ASP. as a result. the Web server controls determine the type of browser that is requesting the page. . the controls create client-side script to implement their functionality. redistribute. <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. These processes are called event handlers. and then deliver the appropriate HTML. Please report any unauthorized use of this content to piracy@microsoft. if the requesting browser does not support client-side script.

It is illegal to reprint. guarantees or conditions.QuickStart Intelligence Creating a Microsoft® ASP. HTML Server Controls By default. The wide range of controls helps you customize your Web Form to match your application. HTML elements are treated as plain text that is passed through to the browser. Some server controls closely resemble traditional HTML elements.aspx" title="Go To Page 2.NET has many different available server controls. or resell this content. while other server controls are specific to ASP.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. <img src="/login. <br /> img A self-closing element that embeds an image on the page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.">Page 2</a> br A self-closing element that adds a line break to the page. Please report any unauthorized use of this content to piracy@microsoft.png" alt="Log in to web application. you can add the runat="server" attribute and value to convert HTML elements to HTML server controls." /> input Specifies different types of input elements. image. . <a href="/Page2. However. HTML elements on a Web Form are not available to the server. The Licensed Content is licensed "as-is. redistribute. This changes the HTML elements to elements that you can program by using server-side code. Element name Description Example a An anchor element that links to another page. 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.NET Web Form 3-13 Types of Server Controls Key Points ASP.NET. including <input type="text" This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or other resource.

lists. name="UserName"> select Creates a selection “menu” with at least one option. guarantees or conditions. .. Web server controls exist in the System. such as buttons. such as calendars... /> <input type="submit" /> Creates a button that sends a request to the server. You use these controls in the same manner that you use HTML server controls. Intrinsic standard Web server controls correspond to simple HTML elements. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Web server controls are more abstract than HTML server controls. • Intrinsic controls. Because Web server controls are based on a common object model. <title>Login Page</title> Web Server Controls Web server controls include form-type controls—such as buttons. Please report any unauthorized use of this content to piracy@microsoft.. It is illegal to reprint. and complex controls.QuickStart Intelligence 3-14 Introduction to Web Development with Microsoft® Visual Studio® 2010 Element name Description Example a submit button. Standard Web Server Controls Standard controls contain two groups of controls: intrinsic controls. and provided to you by QuickStart Intelligence. and text boxes.NET. and you can use them in any Web Form.Web. Web server controls are server controls that are created specifically for ASP. Web server controls are more flexible and powerful than HTML server controls. Web server controls will not function if the runat="server" attribute is missing. or controls that include multiple functions. which provides an appointment calendar that helps a user select a date in the correct format. • Complex controls. Complex controls can either be controls that work with static and dynamic data.WebControls namespace. Unlike HTML server controls.UI.com or by calling +1 800-785-3448. lists. redistribute. all controls share several attributes. Since the object model does not necessarily reflect the HTML syntax. Web server control HTML control equivalent Web server control function <asp:Button. controls that act as containers for other controls. including asp:ControlType and an id attribute. <asp:CheckBox. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. check box. text box. An example of a complex control is the Calendar control. and text boxes—and specialpurpose controls. file selection control. radio button. <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. and a hidden control. /> <input type="checkbox"> Creates a check box that the user can select. The following table describes some of the commonly used intrinsic Web server controls. Intrinsic controls match the simple HTML elements.

DataList Displays rows of database information in a customizable format.NET 4. /> <div> </div> Creates a borderless division on the form that serves as a container for other controls. <asp:ImageButton. <asp:TextBox.. Wizard Provides navigation and a UI to collect related data across multiple steps. Data-bound controls are used to display data from a data source.. Control Function AdRotator Displays a predefined or random sequence of images. • Data source controls. Data Controls Data controls contain two groups of controls: data-bound controls. The following table describes some of the complex controls..NET pages with simple. <asp:ListBox." The following table describes some of the most common data-bound controls. ..NET Web Form Web server control HTML control equivalent Web server control function <asp:HyperLink.. guarantees or conditions.. /> <img src="…" /> Creates an image. /> <input type="image" /> Creates a button that incorporates the display of an image.0 Web Application. It is illegal to reprint. 3-15 Complex standard controls insert complex functions into your Web Form.com or by calling +1 800-785-3448. <asp:Panel.. or resell this content. and provided to you by QuickStart Intelligence... <asp:Label. /> <table> </table> Creates a table. Note: For more information about data controls. <asp:Table. redistribute. Calendar Displays a graphic calendar on which users can select dates.QuickStart Intelligence Creating a Microsoft® ASP. and one or more data controls... Please report any unauthorized use of this content to piracy@microsoft.. /> <input type="radio"> Creates a single radio button control. /> <span> </span> Creates text that users cannot edit. /> <input type="text" /> Creates a text box control. /> <a href="…" /> Creates a hyperlink to an HTML anchor tag. <asp:Image.. The Licensed Content is licensed "as-is. instead of text. Data source controls are used as an intermediary control between a data source such as a database or an XML file. intuitive. and visually compelling charts for complex statistical or financial analysis.. Control Function Chart Enables you to create ASP. "Managing Data in a Microsoft ASP. /> <select size="5"> </select> Creates a list of choices. DetailsView Displays a single row of data from a data source by using a tabular layout. and data source controls: • Data-bound controls. see Module 8." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.. <asp:RadioButton. FileUpload Provides users with a way to upload a file from to the server.... where This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and enables multiple selections.

" This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Control Function AccessDataSource Connects to data from a Microsoft Access® database for use with data-bound controls. The control can be used to filter data in the markup of a Web page by using a declarative syntax. whether hierarchical or tabular.NET application. see Module 9. The Licensed Content is licensed "as-is. see Module 6. guarantees or conditions. SqlDataSource Connects to data that is located in a relational data base." Validation Controls Validation controls are hidden controls that validate user input against predetermined patterns. To test user input. SiteMapDataSource Exposes navigation data retrieved from a site map provider. and exposes language-integrated query (LINQ) to Web developers. or resell this content. LinqDataSource Connects to data from either a database or an in-memory data collection (such as an array). Please report any unauthorized use of this content to piracy@microsoft. redistribute. Note: For more information about validation controls. such as Microsoft SQL Server®. ListView Displays data in a format that you define by using templates and styles." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. XmlDataSource Connects to data in XML format. Validation controls incorporate logic that allows you to test user input. QueryExtender Used to create filters for data that is retrieved from a data source.com or by calling +1 800-785-3448. Insert. you can associate a validation control with the input control. an error message displays. Implicitly supports Edit. It is illegal to reprint. Repeater Displays information from a data set by using a set of HTML elements and controls that you specify. and then specify the conditions for valid user input. "Managing Data Access Tasks by Using LINQ. and provided to you by QuickStart Intelligence. FormView Displays a single row of data from a data source by using a layout defined by a template. The Repeater control repeats the element once for each record in the data set. GridView Displays tabular data in a grid. . and Delete operations. If the user input does not conform to the requirements. in addition to the sorting and paging functionality. Note: For more information about LINQ.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. EntityDataSource Represents an Entity Data Model (EDM) to data-bound controls in an ASP. "Validating User Input. The following table describes some of the commonly used data source controls. This is also true if the control is not bound to a data source.

redistribute. RegularExpressionValidator Requires that the input matches a specified format such as a U. including menus and breadcrumbs. "Securing a Microsoft ASP. The Licensed Content is licensed "as-is.NET Web Application. including user name and password text boxes. Navigation Controls Navigation controls are used to create navigational aids on ASP. PasswordRecovery Used to retrieve user passwords. or a strong password that consists of numbers and letters. telephone number. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. It is illegal to reprint. LoginStatus Displays a login link for users who log in.com or by calling +1 800-785-3448. LoginView Displays different information to anonymous users and logged-in users. or resell this content. CreateUserWizard Adds a new user to the Web site. . The following table describes the navigation controls. Login Displays a user interface for user authentication." The following table describes the Login controls. Login Controls Login controls work together to provide a robust login solution that requires very little code. and a logout link for logged-in users. Control Function Menu Supports displaying a main menu and submenus. Note: For more information about login controls. but also allows you to define dynamic menus.NET Web pages.S. RequiredFieldValidator Requires that the user enters some value before the control is processed. Control Function CompareValidator Requires that the input matches a second input or existing field. RangeValidator Requires that the input is within a specified range. Control Function ChangePassword Enables users to change the Web site password. if logged in. see Module 15.QuickStart Intelligence Creating a Microsoft® ASP.NET Web Form 3-17 The following table describes the validation controls. CustomValidator Requires that the input matches a condition such as prime or odd numbers. LoginName Displays a user's login name. ValidationSummary Collects all the validation control error messages for centralized display. and a Login button." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

and a Web server control button. All button controls appear identical on the user’s browser. an HTML server control button. and provided to you by QuickStart Intelligence. Note that in addition to the runat="server" attribute. Please report any unauthorized use of this content to piracy@microsoft. The following example is of an HTML server control button. redistribute. Example of Equivalent Controls The following example shows the HTML code for three button controls: an HTML button.com or by calling +1 800-785-3448. you must add an id attribute for the control to function as a server control. guarantees or conditions. . TreeView Displays hierarchical data in a tree structure. 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 Server Control" id="Button1" runat="server" /> The following example is of a Web server control button. The HTML button raises only client-side events. It is illegal to reprint.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. <asp:Button id="Button1" runat="server" Text="Web control" /> Question: Which types of server controls exist for ASP. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. <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.NET? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

but performance can suffer because of the increased HTML size. These values are then entered into the View state hidden field. The advantage of the View state process is that the programmer can focus on the page’s design. which records the state of the controls on the Web Form.NET Web Forms saves the state of controls by adding the hidden control __VIEWSTATE. redistribute. Because the state of the Web page is kept inside the server form.QuickStart Intelligence Creating a Microsoft® ASP. View state is only useful within the same Web Form as it travels back and forth between the client and server. As the page travels back and forth from the client to the server. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. You can use View state to persist application data that is specific to a single page. You can also use View state in other scenarios. 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. You cannot use View state between different Web Forms. and provided to you by QuickStart Intelligence. including a product ID or a user ID. Specifically. It is true for any HTTP-based technology that Web Forms are stateless by nature.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.NET page framework uses to preserve page and control values between round trips. or resell this content. When the HTML markup for the page is rendered. Web Forms adds __VIEWSTATE to the server-side form element. the current state of the page and values that must be retained during postback are serialized into base 64-encoded strings. Please report any unauthorized use of this content to piracy@microsoft. and only records the state of controls in this section. and does not have to keep returning to the same server. such as for statistical reasons if you want to know how many times a user postbacks the same page in sequence to the server. which means that it takes longer to render the page on the client. and does not have to build infrastructure to track Page state. The Licensed Content is licensed "as-is. This process makes it easier for server controls to automatically retain their values between server round-trips." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. View state is the method that the ASP. ASP.com or by calling +1 800-785-3448. which means that the server does not retain any information between client requests. View state lowers the server load. . without any coding. the Web page can be randomly routed in a Web server farm. guarantees or conditions. It is illegal to reprint.

and provided to you by QuickStart Intelligence. or resell this content. and create an event handler for the ValueChanged event. Controls can have both View state and control state. Keep in mind that if the EnableViewState attribute of the Page directive is set to false. Enabled Enables View state for this control even if the parent control has View state disabled. guarantees or conditions. and enable the View state only for selected controls. a Web Form saves the controls’ View state on the Web Form. you might want to disable the __VIEWSTATE attribute at the page level. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. You use the Value property to specify the value of the control.NET control state allows you to store information that is specific to the control and cannot be disabled. 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. and the control state to maintain the core behavior of the control. The following code illustrates this. or to disable View state for an individual control when View state is enabled for the page. you cannot override this for an individual control on that page. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448.. However. You use the View state to maintain the control's content. redistribute.QuickStart Intelligence 3-20 Introduction to Web Development with Microsoft® Visual Studio® 2010 Disabling and Enabling ViewState By default. . <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. set the EnableViewState attribute of the control to false. To maximize page performance. 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. This event is called each time the value of the control changes between posts to the server. set the EnableViewState attribute of the Page directive to false. for Web Forms with multiple controls. The Licensed Content is licensed "as-is. such as when View state is disabled for a page. <%@ Page EnableViewState="false" %> To disable the View state for a specific control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. To disable the View state at the Web page level.. the size of the __VIEWSTATE properties value field can slow the performance. The following code shows how to declare a HiddenField control with a value of 1. <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). Control State ASP. <%@ Page ViewStateMode="Disabled" %> . For controls that must repopulate their content each time the user requests a page—such as a control that displays a grid of data—you can disable the View state but not the control state. The following code illustrates this. Disabled Disables View state for this control even if the parent control has View state enabled.

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.com or by calling +1 800-785-3448. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. redistribute.QuickStart Intelligence Creating a Microsoft® ASP. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The Licensed Content is licensed "as-is. . and provided to you by QuickStart Intelligence.

You can then configure the controls by setting the properties in the Properties window. and provided to you by QuickStart Intelligence. This conversion allows you to use the controls to trigger events that are handled 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. but are processed on the server. The advantage of HTML server controls is that they help you quickly update existing pages to Web Forms. you can optimize the performance of a page by determining and adjusting the controls so that they work locally on the browser.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. <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. The Licensed Content is licensed "as-is. <input id="Text1" type="text" runat="server" /> This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. <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.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . In addition. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. redistribute. HTML server controls include the runat="server" attribute and must reside in a containing FORM element. you can expose them as elements to your server-side code. By converting HTML controls to HTML server controls.NET. The following code shows a simple HTML text box control that is processed by the client side browser. It is illegal to reprint.

and provided to you by QuickStart Intelligence. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. The Licensed Content is licensed "as-is.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. redistribute. . Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

click Design. 2. right-click the SampleWebSite web site project. and then double-click the TextBox control. 8. In the left pane. expand Standard. you need to perform the following steps: 1. and the value of the Text property to Sample. 10. click ASP. type Default. and then double-click the Calendar control.NET Empty Web Site. click Web Form. text. in the Name box. and then click Add New Item. expand Standard. In Solution Explorer. In Toolbox. in the middle pane. 7. 11.aspx window. . change the value of the (ID) property to SampleTextBox. 3. In the middle pane. type C:\WebSite1\SampleWebSite. redistribute. and then click Add. 12. click New Web Site. Open Visual Studio 2010.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. 6. In the Default.com or by calling +1 800-785-3448. In the Add New Item dialog box. click Visual Basic.aspx. In the Default. When rendered to the client. Please report any unauthorized use of this content to piracy@microsoft. the TextBox control looks like the following code example." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In Toolbox. 4. <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. click Toolbox. The Licensed Content is licensed "as-is. and on the File menu. In the Properties window. It is illegal to reprint. 9. In the Properties window. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. In the Web location list. change the value of the (ID) property to SampleCalendar. and provided to you by QuickStart Intelligence. and then click OK.aspx window. click File System. or resell this content. 5. guarantees or conditions. in the text box.

Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. It is illegal to reprint.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.QuickStart Intelligence Creating a Microsoft® ASP. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. guarantees or conditions. or resell this content.

NET page might include: an HTML span element that lists the local time. HTML server controls have almost the same HTML code as the basic HTML controls. Web server controls are more capable. HTML server controls. guarantees or conditions. and have a richer object model than HTML server controls.NET pages. Because HTML server controls map exactly to HTML elements. you do not have to replace controls and risk substitution errors or page formatting problems. instead of in the client browser. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and you want to add Web Form functionality quickly. You can mix these control types on the same page to quickly update an HTML page. and a Web server control text box that accesses data from the server. the best practice is to avoid HTML server controls. It is illegal to reprint. you can use HTML elements. • You might use HTML server controls in the following situations: • You prefer an HTML-like object model. The Licensed Content is licensed "as-is. your ASP. or Web server controls. there are times when HTML server controls must be used. redistribute.com or by calling +1 800-785-3448. and you must perform a large amount of client-side processing to reduce bandwidth usage.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. . However. • Bandwidth is limited. Additionally. HTML server controls are modified HTML elements that run on the server. As an example of mixing control types. • You want to work with existing HTML pages. an HTML server control button converted from an HTML element. HTML Server Controls While the best practice is to avoid using HTML server controls and use Web server controls instead. and provided to you by QuickStart Intelligence.NET Web server controls approximate HTML controls. they include a number of new controls that currently do not exist in HTML. Web Server Controls ASP.

guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. By using Web server controls. and easily separate the page logic from the UI. • Your bandwidth is not limited. you can also create applications with nested controls and catch events at the container level.com or by calling +1 800-785-3448. • You must create a Web page that might be viewed by using a variety of browsers.NET Web Form 3-27 You use Web server controls in the following situations: • You prefer an object-oriented programming model. The Licensed Content is licensed "as-is. identify controls by their ID attribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • You require specific functionality—such as a calendar or an advertisement—that is available only as a Web server control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. 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. redistribute. You can use object-oriented programming. and provided to you by QuickStart Intelligence. .QuickStart Intelligence Creating a Microsoft® ASP. 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. It is illegal to reprint. and the request-response cycles of Web server controls will not cause bandwidth problems.

NET Web Form Note: You can perform tasks in this lab either by using the Visual Basic or Visual C# programming language. refer to the steps provided in Section 1 of the lab page. you will use the available virtual machine environment. then add server controls to the Web Form.QuickStart Intelligence 3-28 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab: Creating a Microsoft ASP. If you are using Visual Basic as your programming language. 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.com or by calling +1 800-785-3448. you will be able to: • Create a new Web Form. Lab Setup For this lab. or resell this content. you will add a Web Form to an ASP. The Licensed Content is licensed "as-is. and then configure its properties. Before you begin the lab. Introduction In this lab. • Create a table-style layout in the Web Form. • Apply a style sheet to the Web Form." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Objectives After completing this lab. redistribute. . • Add a server control to the Web Form and configure its properties. • Apply styles to the HTML elements and server controls. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. you must: • Start the 10267A-GEN-DEV virtual machine. refer to the steps provided in Section 2 of the lab page. If you are using Visual C# as your programming language. It is illegal to reprint.NET Web application. and provided to you by QuickStart Intelligence.

or resell this content. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET applications to create. and the application requires updates based on the feedback from senior developers and other stakeholders. guarantees or conditions.com or by calling +1 800-785-3448. It is illegal to reprint.NET Web Form 3-29 Lab Scenario You are a developer at Contoso. The Licensed Content is licensed "as-is. redistribute. You need to customize the application to meet the specific requirements of the sales team. Your organization uses Microsoft . customize. . Ltd wants to create an application to maintain and update its customer information." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. Your organization has created a Web site to manage customer data and services in ASP.NET server controls. and provided to you by QuickStart Intelligence. and manage its customer information.QuickStart Intelligence Creating a Microsoft® ASP.NET. Contoso. which is a large organization with a global customer base. You must create an application and build a user interface that is easy to update and modify. You need to build a UI that meets the defined requirements. Updating the customer information is an ongoing process for the sales team. Ltd. by using ASP.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. by using the Add New Item dialog box.NET Web site. you will have opened the existing CustomerManagement Web site.  Task 2: Add a Web Form to the Web site • Add the InsertCustomer. Open an existing ASP. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M3\VB folder. It is illegal to reprint. and added the InsertCustomer Web Form.aspx Web Form to the CustomerManagement Web site. with the password. . Pa$$w0rd. The Licensed Content is licensed "as-is.NET Web site • Log on to 10267A-GEN-DEV as Student.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. 2. Results: After completing this exercise. guarantees or conditions. • Open Visual Studio 2010. Add a Web Form to the Web site. and provided to you by QuickStart Intelligence.  Task 1: Open an existing ASP.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. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.

• Add a new div element from the Toolbox to the existing div element. or resell this content. Set the non-trivial control properties. Add an existing style sheet to the Web Form. 3." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.customerTableRow by using the Selector box of the New Style dialog box.aspx window. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. . • Click the opening tag of the div element.aspx.  Task 2: Create a table-style layout in the Web Form • In the InsertCustomer.  Task 1: Add an existing style sheet to the Web Form • Reference the Styles/Site. 5. Apply a predefined style to the Web Form. 2. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. • Apply the style to the current document selection by using the Apply new style to document selection check box. • View the styles added in the style sheet by using the Manage Styles window. • Press CTRL+S to save InsertCustomer. Create a table-style layout in the Web Form.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. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Use the Apply Styles window to apply the customerTable style to the outermost div element. redistribute. Apply div. place the cursor between the opening and closing div tags.com or by calling +1 800-785-3448. It is illegal to reprint. <div> <div> </div> </div> • Add two new div elements from the Toolbox to the newly added div element. relative to the root folder.QuickStart Intelligence Creating a Microsoft® ASP. • Name the new style div.css file in the InsertCustomer Web Form. <div> <div> <div> </div> <div> </div> </div> </div> • Save the changes to the InsertCustomer Web Form.customerTable from the Contextual Selectors section of the Apply Styles window. Add the server controls to the Web Form and configure their basic properties. by using the New Style button. by using the Manage Styles window. Note: In this exercise. • Define the new style in the existing Styles/Site. 4. you are creating a two-column table using CSS for holding various controls used for displaying and managing Customer data.css CSS file. • Create new style in the Apply Styles window. which is a child element of the div element with a class attribute value of customerTable.

guarantees or conditions. on the File menu.com or by calling +1 800-785-3448. by using the display list of the Layout category. • Add 11 more table rows by copying the existing div element with a class attribute value of customerTableRow." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. • Add the Label control from the Toolbox to the first cell of the left column in the div element. and then close the New Style dialog box.. <div class="customerTable"> <div class="customerTableRow"> <div class="customerTableLeftCol"> </div> <div class="customerTableRightCol"> </div> </div> . change the (ID) property to CustomerFirstNameLabel.QuickStart Intelligence 3-32 Introduction to Web Development with Microsoft® Visual Studio® 2010 • Set the layout of the new style to table-row. <div> </div> </div> • View the InsertCustomer 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.. redistribute. <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. Note: Notice that two equal-sized columns are added to the div element. The Licensed Content is licensed "as-is. • In the CustomerManagement – Microsoft Visual Studio (Administrator) window. notice that nothing displays. click Save All. Note: Although you have styled the Web form by using the CSS file. or resell this content. • 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.css file. and then set the Text property to First Name:. . • View the InsertCustomer Web Form in a Web browser. placing the new div element immediately before the closing div tag of the customerTable div element. 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. • View the InsertCustomer Web Form in Source view. • Save the changes to the InsertCustomer Web Form and the Site. • 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. • 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.

QuickStart Intelligence Creating a Microsoft® ASP. and change the (ID) property to CustomerFirstNameTextBox. • Add the TextBox control from the Toolbox to the second cell of the right column in the div element. • Add the Label control from the Toolbox to the tenth cell of the left column in the div element. change the (ID) property to CustomerAddressLabel. change the (ID) property to CustomerLastNameLabel. • Add the TextBox control from the Toolbox to the fourth cell of the right column in the div element. and then set the Text property to Address:. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint. • Add the Label control from the Toolbox to the second cell of the left column in the div element. • Add the TextBox control from the Toolbox to the sixth cell of the right column in the div element. Please report any unauthorized use of this content to piracy@microsoft. and then set the Text property to Country:. and then set the Text property to Phone:. • Add the TextBox control from the Toolbox to the ninth cell of the right column in the div element. • Add the DropDownList control from the Toolbox to the seventh cell of the right column in the div element." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. change the (ID) property to CustomerEmailAddressLabel. change the (ID) property to CustomerCityLabel. and change the (ID) property to CustomerEmailAddressTextBox. and change the (ID) property to CustomerWebAddressTextBox. and change the (ID) property to CustomerPhoneTextBox. • Add the Label control from the Toolbox to the eleventh cell of the left column in the div element. and change the (ID) property to CustomerLastNameTextBox. and provided to you by QuickStart Intelligence. • Add the Label control from the Toolbox to the fifth cell of the left column in the div element. • Add the TextBox control from the Toolbox to the eighth cell of the right column in the div element. change the (ID) property to CustomerZipCodeLabel. • Add the Label control from the Toolbox to the seventh cell of the left column in the div element. and change the (ID) property to CustomerCityTextBox.com or by calling +1 800-785-3448. or resell this content. . • Add the Label control from the Toolbox to the eighth cell of the left column in the div element. and then set the Text property to Web Address:. and then set the Text property to Email Address:. change the (ID) property to CustomerStateLabel. and then set the Text property to Credit Limit:. change the (ID) property to CustomerWebAddressLabel. • Add the TextBox control from the Toolbox to the fifth cell of the right column in the div element. The Licensed Content is licensed "as-is. change the (ID) property to CustomerCreditLimitLabel. • Add the TextBox control from the Toolbox to the third cell of the right column in the div element. and then set the Text property to Zip Code:. • Add the Label control from the Toolbox to the fourth cell of the left column in the div element. and change the (ID) property to CustomerZipCodeTextBox. • Add the Label control from the Toolbox to the sixth cell of the left column in the div element. • Add the Label control from the Toolbox to the ninth cell of the left column in the div element. and then set the Text property to State:. and then set the Text property to City:. and then set the Text property to Last Name:.NET Web Form 3-33 • Add the TextBox control from the Toolbox to the first cell of the right column in the div element. change the (ID) property to CustomerPhoneLabel. redistribute. and change the (ID) property to CustomerCountryDropDownList. change the (ID) property to CustomerCountryLabel. • Add the Label control from the Toolbox to the third cell of the left column in the div element. guarantees or conditions. • 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 CustomerAddressTextBox. and change the (ID) property to CustomerStateTextBox.

and then set the Text property to News Subscriber:. and provided to you by QuickStart Intelligence. • Add the Button control from the Toolbox to the footer of the table in the div element. • Save the changes.com or by calling +1 800-785-3448. and view the InsertCustomer Web Form in a Web browser. change the (ID) property to CustomerCancelButton. and CustomerEmailAddressTextBox controls to 50. and change the (ID) property to CustomerNewsSubscriberCheckBox. • Add the Label control from the Toolbox to the twelfth cell of the left column in the div element. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. change the (ID) property to CustomerInsertButton.  Task 5: Apply a predefined style to the Web Form • • Apply the predefined template style to the body element of the InsertCustomer Web form. or resell this content. • Open the InsertCustomer Web Form in the Source view. and view the InsertCustomer Web Form in a Web browser. . It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. • Set the MaxLength property of the CustomerZipCodeTextBox and CustomerCreditLimitTextBox controls to 10. • Save the changes.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. CustomerAddressTextBox. • Add the CheckBox control from the Toolbox to the twelfth cell of the right column in the div element. Results: After completing this exercise. • Revert the changes made to the 10267A-GEN-DEV virtual machine. and CustomerPhoneTextBox controls to 30. CustomerStateTextBox. • 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. and view the InsertCustomer Web Form in a Web browser. • Set the MaxLength property of the CustomerLastNameTextBox. and change the (ID) property to CustomerCreditLimitTextBox. CustomerCityTextBox. The Licensed Content is licensed "as-is. and then set the Text property to Insert. change the (ID) property to CustomerNewsSubscriberLabel. • Set the MaxLength property of the CustomerWebAddressTextBox control to 80. • Save the changes. redistribute.  Task 4: Set the non-trivial control properties • Set the MaxLength property of the CustomerFirstNameTextBox. • Add the Button control from the Toolbox to the footer of the table in the div element." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will have designed the initial version of the InsertCustomer Web Form for your Web site. guarantees or conditions. and then set the Text property to Cancel.

com or by calling +1 800-785-3448. . you will have opened the existing CustomerManagement Web site. or resell this content.  Task 2: Add a Web Form to the Web site • Add the InsertCustomer. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M3\CS folder. Results: After completing this exercise.NET Web site • Log on to the 10267A-GEN-DEV virtual machine as Student. 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.  Task 1: Open an existing ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Open an existing ASP. Add a Web Form to the Web site. redistribute. Pa$$w0rd. and added the InsertCustomer Web Form. • Open Visual Studio 2010. It is illegal to reprint. with the password. guarantees or conditions.QuickStart Intelligence Creating a Microsoft® ASP.aspx Web Form to the CustomerManagement Web site by using the Add New Item dialog box.NET Web site. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.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.

<div> <div> </div> </div> • Add two new div elements from the Toolbox to the newly added div element.aspx window. Set the non-trivial control properties." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Add an existing style sheet to the Web Form. Create a table-style layout in the Web Form. Add the server controls to the Web Form and configure their basic properties. • Apply the style to the current document selection by using the Apply new style to document selection check box. 4. 3. by using the Manage Styles window.  Task 2: Create a table-style layout in the Web Form • In the InsertCustomer.customerTableRow by using the Selector box of the New Style dialog box. Apply div. Note: In this exercise.aspx. redistribute. • Press CTRL+S to save InsertCustomer. • Define the new style in the existing Styles/Site. • Use the Apply Styles window to apply the customerTable style to the outermost div element.css file in the InsertCustomer Web Form. and provided to you by QuickStart Intelligence. relative to the root folder.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. . • View the styles added in the style sheet by using the Manage Styles window. Please report any unauthorized use of this content to piracy@microsoft. • Name the new style div.com or by calling +1 800-785-3448.css CSS file. 5. Apply a predefined style to the Web Form. The Licensed Content is licensed "as-is. • Click the opening tag of the div element. • Create new style in the Apply Styles window. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. guarantees or conditions. It is illegal to reprint. or resell this content. 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. • Add a new div element from the Toolbox to the existing div element. <div> <div> <div> </div> <div> </div> </div> </div> • Save the changes to the InsertCustomer Web Form. which is a child element of the div element with a class attribute value of customerTable. 2.customerTable from the Contextual Selectors section of the Apply Styles window. by using the New Style button. place the cursor between the opening and closing div tags.

This is because the div elements are empty. . It is illegal to reprint. change the (ID) property to CustomerFirstNameLabel. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. • Add 11 more table rows by copying the existing div element with a class attribute value of customerTableRow. • Add the TextBox control from the Toolbox to the first cell of the right column in the div element. guarantees or conditions. and provided to you by QuickStart Intelligence.QuickStart Intelligence Creating a Microsoft® ASP.. • Save the changes to the InsertCustomer Web Form and the Site. • Add the Label control from the Toolbox to the first cell of the left column in the div element. and change the (ID) property to CustomerFirstNameTextBox.com or by calling +1 800-785-3448. and then close the New Style dialog box. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • 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. • View the InsertCustomer Web Form in Source view.. and then set the Text property to First Name:. • 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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • 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. • View the InsertCustomer Web Form in a Web browser. notice that nothing displays. redistribute.  Task 3: Add the server controls to the Web Form and configure their basic properties • View the InsertCustomer Web Form in Design view. 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. or resell this content. <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.css CSS style sheet file. Note: Notice that two equal-sized columns are added to the div element. by using the display list of the Layout category.NET Web Form 3-37 • Set the layout of the new style to table-row. Note: Although you have styled the Web form by using the CSS file.

change the (ID) property to CustomerCityLabel. and then set the Text property to State:. change the (ID) property to CustomerCountryLabel. • Add the Label control from the Toolbox to the tenth cell of the left column in the div element. change the (ID) property to CustomerCreditLimitLabel. • Add the Label control from the Toolbox to the eleventh cell of the left column in the div element. and change the (ID) property to CustomerAddressTextBox. and then set the Text property to Email Address:. • Add the Label control from the Toolbox to the ninth cell of the left column in the div element. change the (ID) property to CustomerZipCodeLabel. and change the (ID) property to CustomerZipCodeTextBox. and then set the Text property to Phone:. • Add the TextBox control from the Toolbox to the eleventh cell of the right column in the div element. change the (ID) property to CustomerLastNameLabel. redistribute.com or by calling +1 800-785-3448. • Add the TextBox control from the Toolbox to the eighth cell of the right column in the div element. • Add the Label control from the Toolbox to the sixth cell of the left column in the div element. and change the (ID) property to CustomerCityTextBox. and then set the Text property to Credit Limit:. change the (ID) property to CustomerPhoneLabel. The Licensed Content is licensed "as-is. 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. • Add the Label control from the Toolbox to the fifth cell of the left column in the div element. or resell this content. and change the (ID) property to CustomerEmailAddressTextBox. and change the (ID) property to CustomerCountryDropDownList. and change the (ID) property to CustomerStateTextBox. change the (ID) property to CustomerStateLabel. • Add the Label control from the Toolbox to the seventh cell of the left column in the div element.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. • 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 CustomerCreditLimitTextBox. and then set the Text property to Last Name:. guarantees or conditions. • Add the Label control from the Toolbox to the third cell of the left column in the div element. and change the (ID) property to CustomerWebAddressTextBox. and change the (ID) property to CustomerPhoneTextBox. Please report any unauthorized use of this content to piracy@microsoft. change the (ID) property to CustomerAddressLabel. change the (ID) property to CustomerWebAddressLabel. • 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 CustomerLastNameTextBox. • Add the Label control from the Toolbox to the fourth cell of the left column in the div element. and provided to you by QuickStart Intelligence. . • Add the TextBox control from the Toolbox to the sixth cell of the right column in the div element. • Add the TextBox control from the Toolbox to the tenth cell of the right column in the div element. and then set the Text property to Address:. • Add the DropDownList control from the Toolbox to the seventh cell of the right column in the div element. and then set the Text property to City:." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Add the TextBox control from the Toolbox to the fifth cell of the right column in the div element. • Add the TextBox control from the Toolbox to the third cell of the right column in the div element. and then set the Text property to Country:. and then set the Text property to Web Address:. change the (ID) property to CustomerEmailAddressLabel. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Add the Label control from the Toolbox to the eighth cell of the left column in the div element.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. • Set the MaxLength property of the CustomerZipCodeTextBox and CustomerCreditLimitTextBox controls to 10. • Add the Button control from the Toolbox to the footer of the table in the div element. and then set the Text property to Cancel. or resell this content. • Revert the changes made to the 10267A-GEN-DEV virtual machine. Please report any unauthorized use of this content to piracy@microsoft. and then set the Text property to Insert. • Save the changes. 3-39  Task 4: Set the non-trivial control properties • Set the MaxLength property of the CustomerFirstNameTextBox. and provided to you by QuickStart Intelligence.QuickStart Intelligence Creating a Microsoft® ASP. and then set the Text property to News Subscriber:. • Save the changes. and view the InsertCustomer Web Form in a Web browser. • Open the InsertCustomer Web Form in the Source view.com or by calling +1 800-785-3448.NET Web Form • Add the Label control from the Toolbox to the twelfth cell of the left column in the div element. and CustomerEmailAddressTextBox controls to 50. change the (ID) property to CustomerInsertButton. change the (ID) property to CustomerCancelButton. change the (ID) property to CustomerNewsSubscriberLabel. • Set the MaxLength property of the CustomerLastNameTextBox. • Add the CheckBox control from the Toolbox to the twelfth cell of the right column in the div element.  Task 6: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. • Save the changes. The Licensed Content is licensed "as-is. CustomerCityTextBox. and change the (ID) property to CustomerNewsSubscriberCheckBox. • Save the changes and view the InsertCustomer Web Form in a Web browser. CustomerStateTextBox. CustomerAddressTextBox. guarantees or conditions.  Task 5: Apply a predefined style to the Web Form • Apply the predefined template style to the body element of the InsertCustomer Web form. you will have designed the initial version of the InsertCustomer Web Form for your Web site. • Set the MaxLength property of the CustomerWebAddressTextBox control to 80. Results: After completing this exercise. • Add the Button control from the Toolbox to the footer of the table in the div element. and view the InsertCustomer Web Form in a Web browser. and CustomerPhoneTextBox controls to 30. and view the InsertCustomer Web Form in a Web browser.

com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. What are the advantages of Web Form controls? 2.QuickStart Intelligence 3-40 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Review 1. or resell this content. 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. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. The Licensed Content is licensed "as-is. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. .

and it is suffixed by the control type that is used. It is illegal to reprint.aspx extension contains intrinsic ASP. The Licensed Content is licensed "as-is. a naming convention consisting of what the control or element contains. What is the easiest way to implement this? You specify a value for the title attribute of the Page directive. How can you verify that a Web page with an . How can you verify that a Web page with an . Best Practices • Web Forms should expose a page title that displays as the browser caption. guarantees or conditions. . • Always use the appropriate Web server control for the task—such as using a Label control instead of a TextBox control—to display read-only text. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You want to add a page to your Web application that you can work with by using server-side code. You want to add a title to a Web Form.QuickStart Intelligence Creating a Microsoft® ASP. This way.NET Web site is a Web Form? 2. In general.NET Web server controls? 3. 2.aspx extension in an ASP. In this course. What type of markup or script does a Web server control generate on the client? A Web server control generates HTML and JavaScript. redistribute. 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. What is the easiest way to implement this? You add a new item by using the Web Form item template. • Follow a naming convention when naming your HTML elements and Web server controls. This makes it easier for users to identify a specific page. Please report any unauthorized use of this content to piracy@microsoft.NET Web Form 3-41 Module Review and Takeaways Review Questions and Answers 1. such as FirstNameTextBox for a TextBox control that exposes the first name of a person. and on the tab provided your browser session is tabbed.com or by calling +1 800-785-3448. if the Web server Real-World Issues and Scenarios 1. you can also have a FirstNameLabel Label control that indicates to the user what the TextBox control contains.

and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint. or from either client-side or server-side code.QuickStart Intelligence 3-42 Introduction to Web Development with Microsoft® Visual Studio® 2010 be given a name or id. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .com or by calling +1 800-785-3448. because you might need to refer to the controls from other controls. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. guarantees or conditions.

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

and provided to you by QuickStart Intelligence. event handlers. which is handled by the Page_Load event handler. This is also true. This is specifically true if you need to initialize controls. To create event handlers effectively. you will learn the various methods to add code to your ASP. populate control properties with View state data. redistribute. guarantees or conditions. and all the code processing happens before a requested page is returned to the client. you will learn how to use page events. You will also learn how to use Web server controls.QuickStart Intelligence 4-2 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Overview You can add code to your Microsoft® ASP. The code discussed in this module is entirely served-based code. such as when a page is loaded on the server or when a button is clicked. Event handlers are procedures that handle an event. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web application by using various methods that would be based on your requirements. Event handlers for Web server controls are usually triggered by user interaction.com or by calling +1 800-785-3448. you must understand the page life cycle. without a server round-trip." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Web application. You must also be familiar with the page life cycle if you develop custom controls. or resell this content. and then run any control behavior code. Finally. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. You can use inline code and mixed code. especially the OnLoad event. even when some server controls automatically emit client-side code so that a user can interact with the control on the client-side. In this module. and components. code-behind files. and provide the functionality for your application. but using code-behind files is the preferred method in Microsoft® Visual Studio® 2010 for adding code to Web Forms. This means the code runs on the server. It is illegal to reprint. .

Code-behind files contain the programming logic for a single Web page. redistribute. In this lesson. guarantees or conditions. You can also add code in the same file in a separate script section or in a separate file.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 will be able to: • Describe the methods for adding code. • Describe the difference between mixed code and inline code. It is illegal to reprint. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Lesson Objectives After completing this lesson. you will learn about three methods to add code using Visual Studio 2010. and provided to you by QuickStart Intelligence. . Inline code uses both HTML and code in separate sections of a single . Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. • Explain how to use code-behind files to add functionality for Web Forms. You will also learn about the differences between the methods.aspx file. • Describe code-behind files.

guarantees or conditions. The code is placed in one or more separate script elements of the same file as the markup content.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 Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. The code is placed in the same file as the Web content. intermingled with markup. The code file is called 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. the default method is to place all the code in a code-behind file. • Code-behind.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. . The code is placed in a separate file from the markup content. • Inline code. It is illegal to reprint. When you use Visual Studio 2010. redistribute.

the markup and code are in separate sections of a single .. and provided to you by QuickStart Intelligence. but this should be avoided because a mixed code file can be difficult to read and maintain. ByVal e As EventArgs) _ Handles Button1. redistribute. however. The Licensed Content is licensed "as-is.w3. the code and HTML can exist anywhere on the page. <asp:Button ID="Button1" runat="server" Text="Button" /> . guarantees or conditions. . Even if inline code does separate the code from the markup. [Visual Basic] <html xmlns="http://www... This separation is for clarity. It is illegal to reprint.. or resell this content.org/1999/xhtml"> .Click .org/1999/xhtml"> ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you may encounter pages that use inline code. Inline Code Although the default method for implementing server-side code in Visual Studio 2010 is to use a codebehind file. Some developers use mixed code.com or by calling +1 800-785-3448. The following are examples of inline code. End Sub </script> [Visual C#] <html xmlns="http://www..aspx file.. the code and markup are still mixed in the same file. Please report any unauthorized use of this content to piracy@microsoft.NET Web Form 4-5 Mixed Code and Inline Code Mixed Code Mixed code is also known as embedded code blocks.. Functionally. When you use inline code for a Web page.. </html> <script Language="VB" runat="server"> Sub Button1_Click(ByVal sender As Object.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. making it hard for two developers to work on markup and code at the same time.w3.

com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute..EventArgs e) { . . guarantees or conditions. </html> <script Language="C#" runat="server"> private void Button1_Click(object sender.QuickStart Intelligence 4-6 Introduction to Web Development with Microsoft® Visual Studio® 2010 <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> . and provided to you by QuickStart Intelligence. 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. It is illegal to reprint.. System.. Please report any unauthorized use of this content to piracy@microsoft.. } </script> Question: How can you use the same method in Visual Basic as in Visual C#. or resell this content.

Separating the logic from the design enables you to work on the code-behind file. the code-behind file has an . By default. or resell this content. depending on the language that is used in the code-behind file. Form1.com or by calling +1 800-785-3448. the Web Form. It is illegal to reprint. while user interface (UI) designers work on the ASP. The Licensed Content is licensed "as-is. The following code shows how you can use the Partial/partial keyword for working with partial classes. When you use code-behind files.cs.vb or . For example. you can mix Web Forms and files of different languages in the same Web site.aspx.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. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. it is also possible to implement a class in two or more separate code files by using the Partial/partial keyword.cs extension. With code-behind files.aspx.aspx. redistribute. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.vb. will have a Visual C# code-behind file named Form1.aspx. . However.NET page. [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.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. guarantees or conditions. Each Web Form in a Web application has its own code-behind file. the programming logic is kept in a separate file from the visual elements of the page. Code-behind files contain the programming logic for a single Web Form. a code-behind file has the same name as the Web Form with which it is associated. or a Visual Basic code-behind file named Form1. However.aspx. and provided to you by QuickStart Intelligence. You cannot mix Visual C# and Visual Basic in the same code-behind file.

using System. and not just the class definition. The Licensed Content is licensed "as-is. EventArgs e) { } } The entire content of the Default.com or by calling +1 800-785-3448. using System. It is illegal to reprint.WebControls. where the class is named _Default.Page End Class [Visual C#] using System. This event handler is used in most Web Forms.cs code-behind files have been shown.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. with the name of the Web Form used as the name of the class.UI.vb and Default. . because it is more difficult to add this code manually in Visual C# than in Visual Basic.UI.OnLoad event. public partial class _Default : System. using System. [Visual Basic] Partial Class _Default Inherits System.aspx). However. The following code shows the Default Web Form (Default. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Generic.UI.Linq." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.Page { protected void Page_Load(object sender. guarantees or conditions. or resell this content. A code-behind file generally contains a single class. Visual Basic does not add the namespaces used for a Web Form. Visual C# also adds the event handler method for the Page. Please report any unauthorized use of this content to piracy@microsoft.Web.UI.Web.Collections.aspx.Web. because they are automatically referenced or imported through the project settings. redistribute.NET Web Forms.Web. It is also the preferred method for many (if not most) developers.Web. using System.aspx. there is a difference in the generated code for Visual Basic and Visual C#. using System.

This can be any class derived from the Page class. and the code-behind file—that form a single unit when the Web application is run. The Licensed Content is licensed "as-is. To accomplish this. . or resell this content.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. It is illegal to reprint. The Inherits attribute defines a code-behind class for the page to inherit.aspx file must be associated with the code-behind file. and case insensitive in Visual Basic. redistribute. Each Web Form page consists of two separate files—the . and provided to you by QuickStart Intelligence. or compiled just in time (JIT) when a user accesses the page for the first time.aspx page: • CodeBehind. This attribute allows the .aspx page.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.aspx page must be associated with a code-behind file. guarantees or conditions. CodeBehind is used with Web Forms in a Web application project (WAP). In addition to the three attributes mentioned. • CodeFile. each . This attribute specifies the name of the compiled file that contains the class associated with the page. This attribute specifies a path to the referenced code-behind file for a Web Form page. CodeFile is used with Web Forms in a Web Site project (WSP). Linking . 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 that code-behind file must be compiled before the information is returned to a requesting client browser.aspx page to inherit from a class in the code-behind file. This attribute is used with the CodeFile attribute. • Inherits. The code-behind Web Form can either be precompiled by Visual Studio 2010 when you build the Web application project.aspx and Code-Behind Files The . Visual Studio 2010 adds the following three attributes to the Page directive of the . Note: The Inherits attribute is case sensitive in Visual C#. Please report any unauthorized use of this content to piracy@microsoft. This attribute is used together with the Inherits attribute to associate a code-behind source file with a Web page. which contains the path to the source file for the code-behind class.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

vb" Inherits="_Default" %> [Visual C#] <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default. It is illegal to reprint. the code is compiled into Microsoft intermediate language (MSIL) and is contained in a single assembly.NET Web Application. [Visual Basic] <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx. where it is JIT compiled into binary code that the operating system can run." This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The designer performs this event binding by using the Handles statement in the declaration of the event-handler method. You can do this by using the Publish Web Site option on the Build menu.NET Web site project into one or more assemblies that can be deployed. the AutoEventWireUp attribute is set to true by default. and provided to you by QuickStart Intelligence. and then clicking Publish Web Site. The following code shows the Page directive for a Web Form named Default.NET Web site is convenient. This is also known as in-place compilation. The application is compiled into one or more assemblies in the temporary ASP. see Module 14. and deploy the Web Form to the server without compiling the source code. ASP. this attribute is set to false by default. Both offer different types of compilation.aspx.NET Web site is not precompiled. "Configuring and Deploying a Microsoft ASP. • WAP. Precompilation You can precompile an ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or by right-clicking the Web site in Solution Explorer.NET files folder. the compiled assembly is copied to the temporary ASP. instead of deploying the actual source code. Upon first application request. When building your project. guarantees or conditions. In Visual Basic. Deploying an ASP. Please report any unauthorized use of this content to piracy@microsoft. redistribute.NET compiles your Web site the first time a page is requested. This causes a slight delay in responding to the first request. The designer automatically generates code to bind events to their event-handler methods. or resell this content.NET files folder upon first request.com or by calling +1 800-785-3448. which is usually placed in the Bin subfolder of the project folder. an ASP. because it allows you to make modifications to a Web Form or code-behind file. The Licensed Content is licensed "as-is.aspx. • WSP. . By default.cs" Inherits="_Default" %> Compilation and Deployment Visual Studio 2010 supports two types of Web application projects: WAP and WSP. when compared with subsequent requests.QuickStart Intelligence 4-10 Introduction to Web Development with Microsoft® Visual Studio® 2010 Note: In Visual C#. For more information about Web site deployment. This allows you to easily deploy just the markup and the compiled assembly. Instead.

guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. and are generally more powerful than client-side event handlers. The Licensed Content is licensed "as-is. To do this. • Describe server-side event handlers. so that you can determine the appropriate event type for your ASP.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. you need to use client-side and server-side event handlers appropriately. you will be able to: • Describe event handlers. especially when it comes to accessing server-side resources. When you develop your ASP. . You also need to know how to add event handlers to Web server controls. Lesson Objectives After completing this lesson.NET applications. 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 provided to you by QuickStart Intelligence. • Describe client-side event handlers." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. such as a database.NET Web Form 4-11 Lesson 2 Handling Server Control Events Event handlers help you handle user interactions on a Web Form. you must know the advantages and disadvantages of using client-side and server-side event handlers. • Describe the process of creating server-side event handlers.com or by calling +1 800-785-3448. There are two types of event handlers: client-side. It is illegal to reprint. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Work with Web server controls by using event handlers. • Explain how client-side and server-side event handlers are processed.NET applications. and server-side. or resell this content. • Explain how to create server-side event handlers.

and then click a Submit button. These events are triggered when a user starts or closes the application. </form> This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. When an event is raised. upload a file to the Web server. or places the pointer over a link in the application. Events help you separate tasks.. you must write the code to handle the event. because events do not occur in the order expected for linear event processing... Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.NET is an object-oriented development platform. the application can catch a cancel event that instructs the sorting process to stop. <body> <form runat="server"> . and provided to you by QuickStart Intelligence. to do this. you can make the application perform a sorting task separately from the main application. which generates an event. it does not automatically trigger an action in the application. and objects most often expose events. The Licensed Content is licensed "as-is. You can use event handlers to handle those events that are triggered by user interaction on a Web Form. or simply redirect the user to a different page. The following are examples of event handler code. clicks a button." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . ASP.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. [Visual Basic] <html> . For example. <asp:Button ID="Button1" Text="Home" runat="server"/> . Examples of an Event Handler Many Web Forms allow the user to enter information. An event handler written for this click event may send the user information to a Microsoft SQL Server® database. redistribute.com or by calling +1 800-785-3448. or resell this content. 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. You need to design the Web application to perform appropriate tasks when an event is raised.. A user interacting with a Web Form raises an event. guarantees or conditions.. If a user cancels the sorting task.

..NET? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. <body> <form runat="server"> . <asp:Button ID="Button1" Text="Home" OnClick="Button1_Click" runat="server"/> . ByVal e As System.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. or resell this content. Please report any unauthorized use of this content to piracy@microsoft..aspx") End Sub [Visual C#] <html> .QuickStart Intelligence Adding Functionality to a Microsoft® ASP.Redirect("~/Default.aspx"). and provided to you by QuickStart Intelligence. guarantees or conditions.Redirect("~/Default." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Click ' Redirect to home page Response. </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. redistribute. } Question: How are types of events classified for ASP. It is illegal to reprint..com or by calling +1 800-785-3448.EventArgs) Handles Button1. The Licensed Content is licensed "as-is..

or resell this content.style. which is always one or more HTML elements. Client-side event handlers are events that are handled on the client computer that is requesting the Web Form. You can attach client-side event handlers directly to a Web Server control by specifying it in the event attribute.event. <script type="text/javascript"> function changeColor() { window.") [Visual C#] Button1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b."). . It is illegal to reprint. such as the onmouseover event as shown in the following code.com or by calling +1 800-785-3448. as shown in the following code. redistribute.color = "#FF0000". and server-side.srcElement.. guarantees or conditions. [Visual Basic] Button1.. } </script> . instead. You can also have client-side events for server controls. <asp:Button id="Button1" runat="server" text="Button1" onmouseover="changeColor(). . Please report any unauthorized use of this content to piracy@microsoft. the client browser interprets the code and performs the action.Add("onmouseover". "changeColor(). When an event is triggered. "changeColor(). but only for the portion of the server control that is rendered. The Licensed Content is licensed "as-is. Client-side event handlers can only be used with HTML elements.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 provided to you by QuickStart Intelligence. information is not sent to the server..Attributes.Attributes.." /> You can also assign an event handler programmatically by using the Add method of the Attributes property.Add("onmouseover".

True) [Visual C#] ClientScriptManager buttonClientScriptManager = this. The Licensed Content is licensed "as-is. or resell this content.GetType().srcElement. redistribute. which is placed in the Page Load event handler.RegisterClientScriptBlock method. You can retrieve a reference to the ClientScriptManager class from the ClientScript property of the Page object. }". This means that it is not necessary to send information to the Web server and wait for a response. Use the ClientScriptManager. and provided to you by QuickStart Intelligence.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.event. The JavaScript can also be located in an externally linked file. For example.GetType(). Client-side event handlers never have direct access to server resources.ClientScript buttonClientScriptManager. It is illegal to reprint. true)." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.style. Uses of Client-Side Event Handlers Client-side event handlers are useful for events that you want to generate immediately.color = '#FF0000'. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.RegisterClientScriptBlock(Button1.ClientScript. guarantees or conditions.style. 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 event handlers do not require a round trip to the Web server. buttonClientScriptManager.com or by calling +1 800-785-3448. Client-side script can be used to improve user experience with richer and more responsive Web pages that perform almost like traditional client applications. as shown in the following code. Please report any unauthorized use of this content to piracy@microsoft. "changeColorScript". [Visual Basic] Dim buttonClientScriptManager As ClientScriptManager = Me.RegisterClientScriptBlock(Button1.event. This can be either explicit—as shown in the preceding example—or it can be done by registering it as a server-side script.color = '#FF0000'.srcElement. "function changeColor() { window. you cannot use a client-side script to directly access a SQL Server database. "changeColorScript". you may want to validate information in a text box before it is submitted to the server. For example.NET Web Form 4-15 The code requires that the JavaScript function be part of the markup. "function changeColor() { window.

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. such as a database. or resell this content. they cannot support events that occur frequently.</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. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This would severely hamper Web page performance.</script> [Visual C#] <script type="text/C#" runat="server">. With client-side event handlers.. Although server-side event handlers support click events and a special version of the onChange event. Server-Side Event Handlers Server-side event handlers consist of compiled code that resides on the Web server. especially when it comes to directly accessing server-side resources. Server-side event handlers have access to server resources that are usually unavailable to client-side event handlers.. redistribute. The Licensed Content is licensed "as-is.. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The following examples specify a server-side event handler by using the runat="server" attribute in the opening <script> tag. You can use serverside event handlers to handle events that are generated from both Web and HTML server controls. such as mouse-key events. and provided to you by QuickStart Intelligence. It is illegal to reprint.com or by calling +1 800-785-3448. you can include code to process mouse-key events and onChange events. guarantees or conditions. and essentially render an application useless.. server-side event handlers require information to be sent to the Web server for processing. [Visual Basic] <script type="text/VB" runat="server">. server-side event handlers are generally more powerful than client-side event handlers. Although there is a performance penalty for using server-side event handlers because of the server round-trip.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Form 4-17 The following table shows some of the differences between client-side and server-side event handlers. 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. Please report any unauthorized use of this content to piracy@microsoft. it is still the only cross-browser compatible programming language. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.NET Framework–based language. you can also use Microsoft Visual Basic Scripting Edition (VBScript) for creating your clientside code and event handlers." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. It is illegal to reprint.com or by calling +1 800-785-3448. . If you use Windows® Internet Explorer® exclusively for accessing an intranet portal.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. Client-side Server-side Programming language JavaScript Any . redistribute. guarantees or conditions.

Please report any unauthorized use of this content to piracy@microsoft. 6. The Licensed Content is licensed "as-is. or resell this content. 3. and provided to you by QuickStart Intelligence. Client-side processing reduces network traffic and improves response times. The client requests an ASP. The user corrects the information in the text box. Server-side resources can be used for other data processing. It is illegal to reprint. and then clicks the Submit button. The page also contains client-side script that validates the contents of the text box. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .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. 5. The server repeats the validation. because no information has been sent to the server. 1. guarantees or conditions. 2. For example. The server returns a page containing markup and script to the client. 7. where server-side processing takes place. The information is validated on the client side. you will see how client-side and server-side event handlers are processed both on the client and on the server. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. this page includes a TextBox control and a Submit button. The user enters invalid information in the text box. 4.com or by calling +1 800-785-3448. and the client-side script generates a message box. because the client-side script does not directly access server resources. and stores the information from the text box in a database. and then sent to the server.NET Web Forms page from the Web 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.NET event handlers. Provide the code for the event handler in the code-behind file that handles the event. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Link the event handler to the control event. and provided to you by QuickStart Intelligence. Visual Studio 2010 also adds the Handles keyword. When you use Visual Basic. the runat="server" attribute and the Handles statement are used to create ASP. 2.NET Web Form 4-19 Creating Server-Side Event Handlers Key Points To create a server-side event handler in Visual Studio 2010. guarantees or conditions. The Licensed Content is licensed "as-is. Visual Studio creates an empty event handler. depending on how you prefer to work. These steps can occur in any order. The Handles keyword allows you to create multiple event handlers for a single event. and the runat="server" attribute indicates that the Click event for the button will be handled on the server. which links the event handler to the control events." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 3. or a single event handler for multiple events. or resell this content.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. Creating a Server-Side Event Handler in Visual Basic In Visual Basic. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. the Handles keyword indicates that the event handler runs in response to the Click event of the Button1 control. It is illegal to reprint. redistribute. The following HTML code shows a Web Form that has a button with the ID attribute Button1. Creating a Server-Side Event Handler When you double-click a control in Visual Studio 2010. Create the control that generates the event on the Web Form. you must perform three steps: 1.

and the click event for the button that will be handled on the server.EventArgs e) { . [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. End Sub Creating a Server-Side Event Handler in Visual C# In Visual C#. you can manually create the link setting as follows. you can create multiple event handlers for a single event. .Click += new EventHandler(Button1_Click). guarantees or conditions. _ ByVal e As System. Using this method. or resell this content.. The following HTML code shows a Web Form that has a button with the ID attribute Button1. you add the event handler to the event property of the control.. [Visual C#] Button1.com or by calling +1 800-785-3448. In the code-behind file. redistribute. The Licensed Content is licensed "as-is..Click . or a single event handler for multiple events.EventArgs) Handles Button1. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence 4-20 Introduction to Web Development with Microsoft® Visual Studio® 2010 [Visual Basic] Protected Sub Button1_Click(ByVal sender As System.. } If you want more control over the manner in which event handlers are linked to control events. System.Object. and provided to you by QuickStart Intelligence. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. [Visual C#] protected void Button1_Click(object sender. Please report any unauthorized use of this content to piracy@microsoft. the Click property of the Button1 variable is handled as follows.

and then click Add New Item. expand Standard. • In the Start Page – Microsoft Visual Studio window. and then click Microsoft Visual Studio 2010. • In the New Web Site dialog box. in the Name box. You can perform this demonstration by using either Visual C# or Visual Basic. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • In the Default. in the middle pane. guarantees or conditions. Demonstration Steps 1. right-click the Web site. and then point to Toolbox. in the middle pane. on the File menu. ensure that Web Form is selected. redistribute.aspx. Add a new Web Form named Default. 4. Pa$$w0rd. • On the Start menu of 10267A-GEN-DEV. • 2. Please report any unauthorized use of this content to piracy@microsoft. • In Solution Explorer. click Microsoft Visual Studio 2010. and then click Add. 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.aspx to the Web site.NET Empty Web Site is selected. To log on 10267A-GEN-DEV.com or by calling +1 800-785-3448. use the following user credentials: • User name: Student • Password: Pa$$w0rd Create a Web Site by using Visual Studio 2010. type Default. and provided to you by QuickStart Intelligence.aspx window. Log on to 10267A-GEN-DEV as Student. or resell this content. in the left pane. click either Visual Basic or Visual C#. and then click OK. with the password. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and then double-click the Button control. The Licensed Content is licensed "as-is. click Design.NET Web Form 4-21 Demonstration: How to Create Server-Side Event Handlers Key Points In this demonstration. click New Web Site. ensure that ASP. Add the Button and Label controls to the Web Form. 3. • In Toolbox. point to All Programs. • In the Add New Item dialog box.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. .

You can view the following code from the Source view of the Default...aspx . • In the http://localhost:49157/WebSite1/Default. End Sub [Visual C#] protected void Button1_Click(object sender. or resell this content. • Press the CTRL+SHIFT+S keys. under Standard. click the Button control on the Web Form. right-click the Default. [Visual C#] .aspx . view the empty event handler created by Visual Studio 2010..Click . click the Close button. and provided to you by QuickStart Intelligence. double-click the Label control. redistribute.Text = "You clicked the button". } 6.aspx Web Form.QuickStart Intelligence 4-22 Introduction to Web Development with Microsoft® Visual Studio® 2010 • 5. View the default Click event handler code. 7. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. notice the Handles statement in the Button1_Click event handler. . [Visual Basic] Protected Sub Button1_Click(ByVal sender As Object. • In the Default. In Toolbox.EventArgs e) { ..Internet Explorer window.Internet Explorer window.EventArgs) Handles Button1.. double-click the Button control to open the code-behind file. • In the http://localhost:49157/WebSite1/Default. View the event handler wiring up. Please report any unauthorized use of this content to piracy@microsoft.Click • In the Visual C# programming language.. System. Note: Open the rendered source by clicking View Source on the Page menu. guarantees or conditions. and then click View in Browser.aspx. and view the Web Form in the browser. It is illegal to reprint. • In the Visual Basic programming language. 8. <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/> .aspx.. and notice that the event handler code is not rendered to the client. ByVal e As System.vb or Default.EventArgs) Handles Button1. Trigger the event handler by using the Button control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.Text = "You clicked the button" [Visual C#] Label1. The Licensed Content is licensed "as-is. 9. [Visual Basic] Label1. [Visual Basic] Protected Sub Button1_Click(ByVal sender As Object. Add the following code in the Click event handler of the Button control.aspx Web Form.aspx window. • In the Default.cs window. the procedure is bound to the event handler by adding the attribute onclick to the markup. Notice that the text of the label changes. • In Solution Explorer. Save the changes. ByVal e As System..

• In the http://localhost:49157/WebSite1/Default. 10.cs. Trigger the event handler by using the Button control. • In the Properties window of the Button control. change the ID property of the Button control to SubmitButton. right-click the Default. click the Close button. notice that the new button name has been changed in the markup.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.com or by calling +1 800-785-3448. and then click View in Browser.NET Web Form 4-23 • In Visual Studio 2010. click the Default. Note: In the Visual Basic programming language. in the code-behind file.aspx. The event handler name has not been changed.Internet Explorer window. • In the http://localhost:49157/WebSite1/Default. Visual Studio does not change the event binding to the procedure. or resell this content. notice that the Handles keyword was updated to reflect the new object name. • In the Default. redistribute. Note: Notice that the Click event handler still triggers when you use the new name of the control.aspx . Notice that Button1 has been changed to SubmitButton in the code-behind file. SubmitButton.aspx . double-click the Button control to open the code-behind file. . 11.aspx window. • In the Default.Internet Explorer window. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. click the Button control on the Web Form. Save and view the Web Form in the browser • On the File menu. This maintains the binding to the correct event handler. It is illegal to reprint. and provided to you by QuickStart Intelligence. click the Close button.vb or Save Default. in the code-behind file. click the Button control.Click. guarantees or conditions.aspx window. but only the ID property of the control. and then click Design.aspx. • In Solution Explorer. The onclick attribute remains set to Button1_Click.aspx Web Form. click either Save Default. • In the WebSite1 .Microsoft Visual Studio window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the Visual C# programming language. and remains as Button1_Click.aspx window. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.

Reading Properties from a Web Server Control In a server-side event handler. The following code contains a form with a Textbox and a Button control. guarantees or conditions. You can do this by using server-side event handlers. The text typed in the NameTextBox control is retrieved by assigning it to the greetingString variable. if a user types the text “Shannon” in the NameTextBox control. Please report any unauthorized use of this content to piracy@microsoft. you need to write code to both read from controls on a form. the text that the user typed into the text box displays.com or by calling +1 800-785-3448. and write to controls on the same form. or resell this content. and provided to you by QuickStart Intelligence.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. then the greetingString variable would contain the text string “Hello Shannon”. . The Licensed Content is licensed "as-is. For example.Text. and the text in the NameTextBox text box. The following code assigns the string variable greetingString to a concatenation of the text “Hello”. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. [Visual Basic] Dim greetingString As String = "Hello " & NameTextBox. you can read information from a server 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. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute.Text [Visual C#] string greetingString = "Hello " + NameTextBox.

Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. In most cases. and provided to you by QuickStart Intelligence.Text = "new text". guarantees or conditions. The Licensed Content is licensed "as-is. you may have a Label Web server control on the ASP. 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. . 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. redistribute.Text = "new text" [Visual C#] GreetingLabel. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. Otherwise.com or by calling +1 800-785-3448. For example. [Visual Basic] GreetingLabel. It is illegal to reprint. <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.NET page as follows. clientside interaction might be a better option." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Web Form 4-25 Setting Web Server Control Properties You can output information directly to a Web server control by using the control’s properties.

and classes. . Please report any unauthorized use of this content to piracy@microsoft. which you can then use in other applications. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Add member variables and constants to a class. and then use that component in other applications. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Lesson Objectives After completing this lesson. or resell this content. you can use existing types and components. The Licensed Content is licensed "as-is. you will be able to: • Describe types. It is illegal to reprint. you will learn about classes and components.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. • Explain how to create a class in Visual Studio 2010. • Create a component. • Add properties and methods to a class. • Access components in an ASP. guarantees or conditions. In this lesson. components.com or by calling +1 800-785-3448. • Add class constructors. You can also use Visual Studio 2010 to create a component. and provided to you by QuickStart Intelligence. You will also learn how to create a component by using Visual Studio 2010.NET Web Form.

For example. The Licensed Content is licensed "as-is. Type and Component Sharing If you build a type that calculates the salary increase that an employee receives. Because the component is a unit of deployment. In general. In addition. and usually is a single file. you can use existing types and components. this calculation is based on numerous formulas that are specific to your organization. and tenure at the company.com or by calling +1 800-785-3448. you can reuse it in different parts of an application or even in different applications. You can use types to organize functions.String and System. Using properties. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and classes. you can set the characteristics of a type. It is illegal to reprint. You can reference a component from an application and access the component's types.NET Web Form 4-27 What Are Types. Components. performance rating. whereas by using methods." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. By contrast. redistribute. and time-consuming to develop. When you want to use a type and its methods. the. Types can be grouped into two distinct categories—structures. A structure is a value type that is saved to the stack or in-line. including current base salary. value types are cheaper to allocate and de-allocate. Please report any unauthorized use of this content to piracy@microsoft. Type Definition Types are groups of code statements that have no user interface. and it is de-allocated when it goes out of scope. or resell this content. Types provide functionality in an application. guarantees or conditions. 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.Object. you must instantiate an instance of the type. Types also have properties and methods. The calculations are very complex.NET Framework class library consists of many types. and Classes? Key Points When you use an object-oriented language such as Visual Basic or Visual C# to develop an application. and give them a single name by which they are referenced. such as System. you can invoke the actions of a type. the company frequently changes the formula by which salary increases are calculated. Component Definition Components consist of one or more types that are compiled into a dynamic-link library (DLL) assembly.

and provided to you by QuickStart Intelligence. If you create a class in an existing project. guarantees or conditions. Class In object-oriented languages. object. property. Please report any unauthorized use of this content to piracy@microsoft. method. which by default contains only a single class and its methods. Question: What are the differences between a structure. This template defines attributes for storing data. and functions that serve a common purpose are grouped together. all applications can use the algorithm. Abstraction is a form of organization in which methods. A class also defines a set of restrictions that you can use to allow or deny access to its attributes and operations. data. and defines operations for manipulating that data. the concept of abstraction is important. Therefore.com or by calling +1 800-785-3448. A class is a template for an object. and component? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence 4-28 Introduction to Web Development with Microsoft® Visual Studio® 2010 After you create the type. If you create a new class library. you may have a Windows-based application that the Human Resources department uses to determine an employee's new salary for the next paycheck. For instance. or resell this content. in this scenario. By using a type to handle the calculations. However. only the type needs to be updated. the class exists in the project namespace. When you create a class in a project. . After that. redistribute. it is very unlikely that your organization will share your source code with other organizations. class. and then places the new class in that namespace. you need to create the complicated algorithm only once. You can also build a Web application that uses the same type to allow employees to determine their new salary. these changes are not automatically shared with other groups of developers. you create a component that you can reuse. reusing the class creates a problem. It is illegal to reprint. You can create a class in any Visual Studio 2010 project. If you create a component that holds the type. You can also create a new class library. you need to create a component that holds the type." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. If you create a class library. when changes occur. You may also have a Windows Communication Foundation (WCF) service that uses the same type. The Licensed Content is licensed "as-is. Visual Studio 2010 creates a default namespace. because you also need to manage the changes to the class. you can use the type with other applications by including it in a project. you do not have to update the applications that use the type. but no UI. the class file is compiled into the application assembly and cannot be reused by other applications. If one group makes changes to the class in the application that they are using. A fundamental component of abstraction is the creation and use of classes. In addition.

You can also use the Namespace keyword in Visual Basic as follows.VisualBasic or System. set the Root namespace to the new name for your component.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. In the middle pane. in the left pane. 4. type the name of the class library. Namespaces provide a logical grouping of classes that all . 5. and then click Properties. or resell this content. a default namespace for the class is created with the same name as the project. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. In the Name box. In Solution Explorer. click New Project. On the Application tab. which helps reduce naming conflicts and increases the reusability of code.NET-compatible development languages can use. click Build Solution to create the component for the new class. . It is illegal to reprint. and you can change it by editing the file. Changing the Namespace In Visual C#.NET Web Form 4-29 Creating a Component  To create a component 1. such as Microsoft. In Visual Studio 2010. The Licensed Content is licensed "as-is. 2. In the New Project dialog box. redistribute.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. and then click OK. 3. The namespaces are arranged hierarchically. On the Build menu.Web." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the namespace is by default contained in the class file. 2. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. right-click the project. In Visual Basic. Each namespace contains types that you can use in your application. [Visual Basic] Namespace YourComponentNamespace Public Class Class1 End Class End Namespace  To change the project namespace name in Visual Basic 1. on the File menu. All namespaces provided by Microsoft begin with either Microsoft or System. click either Visual Basic or Visual C#. click Class Library.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. and provided to you by QuickStart Intelligence. they provide the storage for the properties." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.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.com or by calling +1 800-785-3448. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . It is illegal to reprint. • Backing Fields: Also known as member variables. guarantees or conditions. The Licensed Content is licensed "as-is. • Methods: Used to perform actions upon the data in the contained type.

or resell this content.com or by calling +1 800-785-3448. click File System. In the Add New Project dialog box. b.cs. It is illegal to reprint. point to All Programs. c. and then click New Project. d.cs. and then click OK. In the New Web Site box. In Solution Explorer.vb or Class1. click Class Library. click either Visual Basic or Visual C#. e. in the Web location list. 3. click New Web Site. is created in Solution Explorer and opens in the Code editor window.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. click Rename. and then click OK. change the text to Hello. and then click Microsoft Visual Studio 2010. On the File menu of Visual Studio 2010. click Yes." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a. and then call it from a Web application. b. ensure that ASP. In Solution Explorer. and provided to you by QuickStart Intelligence. you will see how to create a class library.vb or Class1.NET Web Form 4-31 Demonstration: How to Create a Class in Visual Studio 2010 Key Points In this demonstration. point to Add.cs file as Hello. right-click Solution ‘WebSite1’ (1 Project). in the Name box. . In the Microsoft Visual Studio message box.cs. guarantees or conditions. 2. Please report any unauthorized use of this content to piracy@microsoft. a. Create a Class Library project named HelloWorld in the Visual Studio 2010 solution. in the left pane click either Visual Basic or Visual C#. The Licensed Content is licensed "as-is. On the Start menu of 10267A-GEN-DEV. Rename the Class1. in the text box. redistribute. type C:\WebSite1. in the left pane. right-click either Class1.vb or Hello. type HelloWorld. Demonstration Steps 1. Note: Notice that a default class (either Class1.vb or Class1.vb or Hello. and then press ENTER.cs). Create a method that returns a string on the Class file. click Microsoft Visual Studio 2010. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. in the middle pane.NET Empty Web Site is selected. in the middle pane.

. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. in the Bin folder. click the Close button. click Yes. Please report any unauthorized use of this content to piracy@microsoft. click Build Solution.". Add a reference to the HelloWorld Class Library project. [Visual Basic] Function SayHello() As String Return "Hi from Visual Basic component. under ProjectName. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. and then click OK.. verify that the HelloWorld. In the WebSite1 . redistribute. • 5. d. guarantees or conditions. . In the Microsoft Visual Studio message box. In Solution Explorer. } 4." End Function [Visual C#] public string SayHello() { return "Hi from C# component." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. c.dll assembly has been copied. ensure that HelloWorld is selected.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. In Solution Explorer. Build the Class Library project.\WebSite1\. a. e. It is illegal to reprint. right-click C:\. On the Projects tab of the Add Reference dialog box. On the Build menu of Visual Studio 2010. add then click Add Reference.com or by calling +1 800-785-3448. b.Microsoft Visual Studio window.

and not just the way that they are listed in this topic. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Remember that adding member variables and constants is an ongoing process. [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. The Licensed Content is licensed "as-is. constructors. // Current customer name private string customerName = null. properties. methods. guarantees or conditions. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.NET Web Form 4-33 Adding Member Variables and Constants to a Class Key Points After you create the class. because they store the values that a property sets or gets. redistribute. as you develop your class. The member variables are often used as backing fields for public properties." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. // Current customer ID (nullable) private Guid? customerID = null. you add the member variables and constants.com or by calling +1 800-785-3448. } Note: Adding member variables and constants. . It is illegal to reprint. which are typically private to the class. However. and provided to you by QuickStart Intelligence. The namespace has been omitted. The following examples show the Customer class that contains three private member variables and constants.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. and methods to a class can be done in any order. constructors.

Remember that this is an ongoing and iterative process. . but it is also nullable. You create a region by using the keywords Region/region followed by End Region/endregion. which is denoted by using the ? suffix. The customerID backing field is a globally unique identifier (GUID) type. To create a constant that is available throughout an application. This can make it easy to determine if a variable of a nullable type has an initial value assigned. and provided to you by QuickStart Intelligence. you can improve the readability of your code and make it easier to maintain by using constants. remain constant throughout the execution of an application. Please report any unauthorized use of this content to piracy@microsoft. which can be collapsed and expanded as necessary. Constants store values. or they can be user-defined. especially for larger classes where you may not be clear about the data and operations to add. A constant's scope is the same as that of a variable declared in the same location. as shown in the following example. in which case. if Option Strict is On. Note: A data type is a value type if it holds the data within its own memory allocation on the stack.. as you can to variables.. It is illegal to reprint. You declare a constant with the Const/const statement by using the same guidelines you would for creating a variable name. A GUID is a value type. Although constants resemble variables. In Visual Basic. declare it inside that procedure. which means it always holds a value. or resell this content. #End Region [Visual C#] #region Member fields // The default credit limit private const int creditLimit = 50000. A reference type contains a pointer on the stack to another memory location on the heap that holds the actual data.QuickStart Intelligence 4-34 Introduction to Web Development with Microsoft® Visual Studio® 2010 and properties often reference the member variables. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. In such cases. you cannot modify them or assign new values to them.com or by calling +1 800-785-3448. you must explicitly declare the constant type. [Visual Basic] #Region "Member fields" ' The default credit limit Private Const creditLimit As Integer = 50000 . 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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. #endregion Code often contains constant values that are used throughout a type.. so it makes sense to start with the member variables. The constants that you use in your code can be intrinsic to the object model for controls or components that you work with. When adding groups of code to a class—especially if a group or block of code is long—often it is preferred to enclose it in a region. You need to prefix the region with a hash-sign (#). A constant is a meaningful name that takes the place of a number or string that does not change. just like reference types.. declare it by using the Public keyword in the declarations section of the class. To create a constant that exists within the scope of a particular procedure. This is in contrast to reference types that can be set to null (Nothing in Visual Basic). they are set to contain nothing–they have no value. . which. as the name implies. redistribute. value types can be made nullable. However. which means they can be set to null or Nothing. The Licensed Content is licensed "as-is. guarantees or conditions.

. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. redistribute. or resell this content. guarantees or conditions. It is illegal to reprint.

It is illegal to reprint. . you can add the properties for public or private access to those member variables. The Licensed Content is licensed "as-is.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. or resell this content. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The following examples show two properties for the Customer class.customerID End Get Private Set(ByVal value As Guid?) Me. redistribute. [Visual Basic] ''' <summary> ''' The unique customer ID ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property ID() As Guid? Get Return Me. Please report any unauthorized use of this content to piracy@microsoft.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.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. guarantees or conditions.

Substring(0.Length > 50) Then Me. } } The two read-write properties. . are public to any user of the class. so the property access modifier public.customerName = value.customerID.com or by calling +1 800-785-3448. redistribute. ID and Name. else // Only get the first 50 characters if (value.customerName = value.Length > 50) this. This helps ensure that the ID is not changed after the class has been instantiated. The Licensed Content is licensed "as-is. For the Name property. no access modifier has been specified for the getter or setter. and provided to you by QuickStart Intelligence. else this.customerName = value. } } /// <summary> /// The full customer name /// </summary> public string Name { get { return this. 50) Else Me. Notice that the setters and getters—which are used to set and get the value of the property or the property-backing field—can have a different access modifier than the property itself. Because the setter is private. for the ID property. only the getter inherits the access modifier from the property.customerName = "". This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. guarantees or conditions.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. 50).customerID = value. } set { // Null value? if (value == null) this. you can only set the property from within the class. } private set { this.customerName = "" Else ' Only get the first 50 characters If (value. However.NET Web Form 4-37 Me.customerName.customerName = value End If End If End Set End Property [Visual C#] /// <summary> /// The unique customer ID /// </summary> public Guid? ID { get { return this. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. It is illegal to reprint. whereas the setter is private.Substring(0. is applied.

Please report any unauthorized use of this content to piracy@microsoft. If you do not need to control either the naming of the backing field. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. but that is neither the intent nor a best practice. and make your code easier to read. The following examples show a single method for the Customer class." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and should be reflected in how they are named. guarantees or conditions. .GetOrderTotal(ID.GetOrderTotal(ID. The distinction between properties and methods is important. you can use auto-implemented properties. or how the value is assigned to a backing through a property. passing the ID of the customer and the starting date from which to accumulate the order amount. [Visual Basic] Public Property Name() As String [Visual C#] public string Name { get. set. The following is an example of an auto-implemented property.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.com or by calling +1 800-785-3448. } When the compiler sees the code. it will automatically generate the code for the backing field and the getters and setters. such as Name for property. 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. } The dbObject is a private object that accesses the Customers table in a database. 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. Auto-implemented properties help you write your code more quickly. and GetName for a method. startDate). redistribute. It is illegal to reprint. and then returning the total order amount for the customer. You can use the properties for this. or resell this content. [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.

NewGuid().NET Web Form 4-39 Adding Class Constructors Key Points Any class—unless it is made abstract—needs at least one constructor for instantiating an instance of the class.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.ID = id End Sub [Visual C#] /// <summary> /// Default parameterless constructor /// </summary> public Customer() { // Initialize member backing fields with default values this. The following examples show two constructors for the Customer class. guarantees or conditions. } 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.NewGuid() End Sub Public Sub New(ByVal id As Guid?) ' Initialize member backing fields with passed values Me. [Visual Basic] ''' <summary> ''' Default parameterless constructor ''' </summary> ''' <remarks></remarks> Public Sub New() ' Initialize member backing fields with default values Me." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Abstract classes cannot be instantiated.ID = Guid. . The Licensed Content is licensed "as-is. or resell this content. A constructor is used to instantiate and initialize the class. and are primarily created as a generic type from which you must derive or inherit your own classes.ID = Guid. redistribute.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . redistribute.com or by calling +1 800-785-3448. This is a best practice to follow. Please report any unauthorized use of this content to piracy@microsoft. You can add the same logic to the constructors. and provided to you by QuickStart Intelligence. and does not assign values directly. Notice how the constructors assign values to the backing fields through the properties. The Licensed Content is licensed "as-is.ID = id. A code snippet is available from within the Text Editors and Code Editors within Visual Studio at the appropriate location. it is often a good idea to create and distribute a code snippet. or resell this content. If the same type of code—and potentially large chunks of code (such as generic constructors)—is used by several developers. because the properties can contain any logic to restrict values that can be assigned to the backing fields." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence 4-40 Introduction to Web Development with Microsoft® Visual Studio® 2010 } // Initialize member backing fields with passed values this. guarantees or conditions. but that would duplicate the code. It is illegal to reprint.

sln.NET Web Form 4-41 Accessing Components in an ASP.com or by calling +1 800-785-3448. (The component does not necessarily have to be a . to access the methods in the class. To do this. Please report any unauthorized use of this content to piracy@microsoft. and then click Add Reference.  To add a reference to the component project If your solution contains both the Web application and the component project. On the File menu. you must instantiate the class object by referencing its namespace and class name. guarantees or conditions. you can make those components available to other programs. 3. Then. in the Name box. and then click OK. 1. In the Add Reference dialog box. 4. it can be another project in your solution. In the Open Project dialog box. In Solution Explorer. you must first add a reference to the component project. right-click D:\Labfiles\Starter\M4\VB \CustomerManagement. you must first reference the DLL component. or resell this content.NET Framework component. redistribute. Open Visual Studio 2010. or a Component Object Model DLL (COM DLL)). This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 5. double-click the required class library project." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . 2.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. The Licensed Content is licensed "as-is. you can add a reference to the project. click Open Project. type D:\Labfiles\Starter\M4\VB\CustomerManagement. The reference makes the namespace of the component accessible to the application. The component is added to the References folder in Solution Explorer. Referencing the DLL Before you can use the types in a component. and provided to you by QuickStart Intelligence. on the Projects tab.NET Web Form Key Points Once you create public types in a component. It is illegal to reprint.

Customer currentCustomer = new ComponentNamespace. The following code lines declare a new variable named currentCustomer.  To add a reference to the component DLL 1. In the Add Reference dialog box.. Customer currentCustomer = new Customer().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. you can instantiate the class object. Accessing the Object After the object is instantiated. Please report any unauthorized use of this content to piracy@microsoft.. and then click Add Reference. Displays components that are part of both the . guarantees or conditions. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Displays COM DLLs that have been registered on your computer.. It is illegal to reprint.com or by calling +1 800-785-3448. Open your project in Visual Studio 2010. and provided to you by QuickStart Intelligence. [Visual Basic] Dim currentCustomer As New ComponentNamespace. • Browse. and then click OK. • Recent. Dim currentCustomer As New Customer [Visual C#] using ComponentNamespace. For example. • Project.NET or COM component. in the ComponentNamespace namespace. or resell this content. 3. 2. and then instantiate the class directly. right-click the project. The following examples illustrate this. If a component has not been registered as a .Customer(). of the class Customer. view the following tabs: 4. The Licensed Content is licensed "as-is. you can browse to where the component is located. • . any changes that you make to the component are automatically reflected by the reference. you can use it like any other object in your project. the following code passes one This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Instantiating the Object After you add a reference to the component. [Visual Basic] Imports ComponentNamespace .Customer [Visual C#] ComponentNamespace.NET Framework class library and other registered components.NET. Displays a list of all reusable components that were created from local projects.. Displays a list of components recently added to projects on your computer. redistribute. • COM. You can also use the using (Visual C#) statement or Imports (Visual Basic) statement to import the namespace. In Solution Explorer. The reference makes the namespace of the component accessible to the application. The component is added to the References folder (WAP) or Bin folder (WSP) in Solution Explorer. All of the public properties and methods in the class are available for use. Select the required component. .

com or by calling +1 800-785-3448.NET Web Form 4-43 parameter to the GetTotalOrderAmount function of the Customer class. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.GetTotalOrderAmount(startDate) [Visual C#] double total = currentCustomer. or resell this content. . redistribute. [Visual Basic] Dim total as Double = currentCustomer.GetTotalOrderAmount(startDate).QuickStart Intelligence Adding Functionality to a Microsoft® ASP. The Licensed Content is licensed "as-is. and assigns the returned value to the total variable. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.

the page goes through a life cycle in which it performs a series of processing steps. instantiating controls.com or by calling +1 800-785-3448. guarantees or conditions.QuickStart Intelligence 4-44 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lesson 4 Handling Page Events When an ASP. and the postback process and event order. . The Licensed Content is licensed "as-is. 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. • Explain how to handle page events. You will also learn how to use the Page. populate control properties with View state data. In this lesson. you must know the page life cycle to correctly initialize controls. and run any control behavior code. if you develop custom controls. Please report any unauthorized use of this content to piracy@microsoft. These include initializing the page and controls. you will learn how to use page event handlers. or resell this content. It is illegal to reprint. You will learn about the page event life cycle. • Handle postbacks. and rendering.IsPostBack property to control code execution when the page is initially requested. redistribute.NET page runs. you will be able to: • Describe a page event life cycle. and provided to you by QuickStart Intelligence. running the event handler code. • Describe the postback process. Lesson Objectives After completing this lesson. restoring and maintaining the state. Additionally. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

and provided to you by QuickStart Intelligence. Occurs when the page is closed or when the control is passed to another page. guarantees or conditions. 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. Most control events do not occur until the Web Form is posted back to the server. 4." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Click events can cause the form to be sent to the server immediately. Please report any unauthorized use of this content to piracy@microsoft. You can use this event to refer to values or assign values to all controls. These events always occur in the same order. Page_Unload.NET Web Form 4-45 Page Event Life Cycle Key Points When an ASP. Page_Init. or resell this content.com or by calling +1 800-785-3448. The end of the page event life cycle disposes of the page from memory.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. Conversely.NET page is requested. For example. For example. 5. Consist of change events (for example. if a user enters text into a number of controls on a form and then clicks a Submit button. Control events. Page_LoadComplete. Occurs after all the controls on the page have been loaded. Textbox1_Changed) and action events (for example. Occurs after all controls have been initialized. Change events are handled in a random order on the server after the form is posted. 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. 3. Occurs after the initialization of the controls and loading of all controls. It is illegal to reprint. Button1_Click). Page_Load. which is referred to as the page event life cycle. The Licensed Content is licensed "as-is. Page Event Life Cycle The page event life cycle includes the following page events. redistribute. which occur in the following order: 1. 2. . there are a series of page events that occur.

The user views the same page.com or by calling +1 800-785-3448. Therefore. • With the AutoPostBack property set to True. the list box event handler changes the label to reflect the new list box selection. • The server can determine that this is a page that is being posted back to itself. and provided to you by QuickStart Intelligence. and you do not want to wait for the user to click the Submit button. how the code in the Page_Load event handler can be made to run only the first time a page is displayed. the test for Page. guarantees or conditions. • The server then returns the updated information to the client. • The first time that a user requests a page from the server. and then sends the updated information back to the client. the event handlers for the controls on the form (the list box and the button) run. • If you want the new value of the list box to be sent to the server immediately. as soon as the user changes the selection in the list box. • When the user changes the selection in the list box. the information is sent back to the server.NET.IsPostBack in the Page_Load event fails. • The server updates the label to reflect the change.QuickStart Intelligence 4-46 Introduction to Web Development with Microsoft® Visual Studio® 2010 The PostBack Process Key Points To understand the postback process. but the label has now changed to reflect the list box selection. Question: Which property can be used in all events. The Licensed Content is licensed "as-is. the information is sent to the server. or resell this content.IsPostBack in the Page_Load event succeeds and the code in the block runs. and how controls can be made to post back to the server immediately. • Instead. In this scenario. It is illegal to reprint. you can set the list box control’s AutoPostBack property to True. . and then clicks the Submit button. and the code in the block does not run. redistribute. you need to know how forms work in ASP. Please report any unauthorized use of this content to piracy@microsoft. and not just the Load event? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. the test for Page. • The server then returns the page to the user." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

.IsPostBack Property Because the Page_Load event runs with every request for a page.NET Web Form 4-47 Handling Postbacks Key Points The Page_Load event runs on every request for a page.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.IsPostBack) { // Executes only on initial page load. if you use postback events. Please report any unauthorized use of this content to piracy@microsoft. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. } // This code executes on every request. _ ByVal e As System. [Visual Basic] Protected Sub Page_Load(ByVal sender As Object. The Licensed Content is licensed "as-is.EventArgs) Handles Me.. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.IsPostBack Then ' Executes only on initial page load. or resell this content. EventArgs e) { if (!Page. redistribute. all the code need not run again.Load If Not Page. End If ' This code executes on every request. or a postback. However. The Page. You can use the Page. and provided to you by QuickStart Intelligence. The following examples illustrate this. End Sub [Visual C#] protected void Page_Load(object sender. all the code in the Page_Load event will run each time the page is requested. whether it is the first request for the page..IsPostBack property to ensure that the code runs only when the page is initially requested. It is illegal to reprint.

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

including the event handlers and the page output. and check the Postback event. point to All Programs. In this next demonstration. or resell this content. Demonstration Steps  To view the simple code and event handler 1. Switch to Visual Studio 2010. you will be shown the order of the page events. It is important to understand the order in which events are triggered.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • On the Start menu of 10267A-GEN-DEV.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. and when you need to distinguish between a postback and a non-postback of a page. guarantees or conditions. and provided to you by QuickStart Intelligence. • On the File menu of Visual Studio 2010. click Microsoft Visual Studio 2010. Note: The EventOrder. including the event handlers and the page output." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . You can perform these tasks by using either Visual Basic or Visual C#. click Open Project.sln solution file in the D:\Demofiles\M4\CS or D:\Demofiles\M4\VB folder contains a complete solution for this demonstration. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. 4. Switch to Internet Explorer.  To view the order of page events 1. Open the EventOrder solution from the D:\Demofiles\M4\VB or D:\Demofiles\M4\CS folder.NET Web Form 4-49 Demonstration: How to Handle Page Events Key Points In this demonstration. and then click Microsoft Visual Studio 2010. It is illegal to reprint. Run the Web application. you will view the order of the page events. 3. 2. and view the simple code and the Page_Unload event handler. redistribute. Open the EventOrder solution from the D:\Demofiles\M4\VB or D:\Demofiles\M4\CS folder.

• In the Default. In the http://localhost:49241/EventOrder/default.vb or Default. • In Solution Explorer.vb or Default. b.QuickStart Intelligence 4-50 Introduction to Web Development with Microsoft® Visual Studio® 2010 • 2.aspx.com or by calling +1 800-785-3448. redistribute.sln or D:\Demofiles\M4\VB\EventOrder. guarantees or conditions. type either D:\Demofiles\M4\CS\EventOrder. click the Postback button. In the Open Project dialog box. notice that all the events have output to the label on the left. show the simple code and the Page_Unload event handler. and then click Open. but is not shown on the rendered page because the output rendering is completed at this stage. .Microsoft Visual Studio window. } 4. EventArgs e) { if (!this. else PostBackEventLabel.aspx. • Switch to the Visual Studio 2010 window by clicking the Visual Studio taskbar button in the taskbar. which also outputs to the label.aspx. and then click Open. [Visual Basic] Protected Sub Page_Unload(ByVal sender As Object. 3. c. Click the Internet Explorer taskbar button in the taskbar.Text += "Unload event". or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. expand Default.cs window. click the Close button.Internet Explorer window. It is illegal to reprint. • On the Debug menu of Visual Studio 2010. The Licensed Content is licensed "as-is.Text &= "Unload event<br />" End If End Sub [Visual C#] protected void Page_Unload(object sender. click the Close button.Text += "Unload event".aspx .IsPostBack Then NonPostBackEventLabel. d.Text &= "Unload event<br />" Else PostBackEventLabel. and view the simple code and the Page_Unload event handler.Unload If Not Me. right-click either Default. a. in the File name. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and check the Postback event. click Start Without Debugging. Switch to Internet Explorer.aspx. In the EventOrder . In the http://localhost:49241/EventOrder/ .Internet Explorer window.EventArgs) Handles Me.aspx.IsPostBack) NonPostBackEventLabel. Run the Web application. Question: Describe the use of the Events button in the Properties window.sln.Internet Explorer window.cs. and provided to you by QuickStart Intelligence. Note: In the http://localhost:49241/EventOrder/ . ByVal e As System. Switch to Visual Studio 2010. Please report any unauthorized use of this content to piracy@microsoft.

The Licensed Content is licensed "as-is.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. 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. redistribute. refer to the steps provided in Section 2 of the lab document. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. If you are using Visual Basic as your programming language. Please report any unauthorized use of this content to piracy@microsoft. • Handle page and server control events. and provided to you by QuickStart Intelligence. Objectives After completing this lab. which you will reference from the Web application. guarantees or conditions. and then create a component. Before you begin the lab.NET Web site. • Create event procedures. you will implement the code and the event procedures on an ASP. you must: • Start the 10267A-GEN-DEV virtual machine. . you will implement page and server control events on the Web site. and then reference it from a Web application.NET Web Form 4-51 Lab: Adding Functionality to a Microsoft ASP. Lab Setup For this lab. • Create an entity component. you will use the available virtual machine environment. refer to the steps provided in Section 1 of the lab document.com or by calling +1 800-785-3448. you will be able to: • Implement code in a Web application. Introduction In this lab.NET Web Form Note: You can perform the tasks in this lab either by using the Visual Basic or the Visual C# programming language. In addition. or resell this content. If you are using Visual C# as your programming language.

com or by calling +1 800-785-3448. Your organization is using a separate Web site for fast and easy interaction with its customers. or resell this content. and provided to you by QuickStart Intelligence. The organization wants to make its Web site dynamic to enable users to enter and save customer details with minimum turnaround time. 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.NET applications to create. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. The Licensed Content is licensed "as-is. Your organization uses Microsoft . customize. To do this. which is a large organization with a global customer base. thus saving considerable processing. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . and manage its customer information. In addition. Ltd. Please report any unauthorized use of this content to piracy@microsoft. you need to attach the required code to the UI that enables the application to respond to user actions and other events.QuickStart Intelligence 4-52 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Scenario You are a developer at Contoso. redistribute.

with the password Pa$$w0rd.com or by calling +1 800-785-3448.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. It is illegal to reprint. Open an existing ASP. • Open Visual Studio 2010. The Licensed Content is licensed "as-is. Results: After completing this exercise. redistribute.  Task 1: Open an existing Web site • Log on to 10267A-GEN-DEV virtual machine as Student. Open the code-behind file for an existing Web Form. and provided to you by QuickStart Intelligence. by using the View Code context menu command. you will have opened the existing CustomerManagement Web site. 2.  Task 2: Open the code-behind file for an existing Web Form • Open the code-behind file of the InsertCustomer Web Form. guarantees or conditions.NET Web site. Please report any unauthorized use of this content to piracy@microsoft.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. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. . and the InsertCustomer Web Form code-behind file. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M4\VB folder.

Unload End Sub Results: After completing this exercise. and create an event procedure for the Click event of the Insert button. by double-clicking the box next to the Click event in the Properties window. Please report any unauthorized use of this content to piracy@microsoft. Protected Sub Page_Unload(ByVal sender As Object. ByVal e As System. 5.EventArgs) Handles Me. It is illegal to reprint. ByVal e As System. 2. by double-clicking the Button control.EventArgs) Handles Me. The Licensed Content is licensed "as-is. guarantees or conditions. Protected Sub Page_LoadComplete(ByVal sender As Object.  Task 3: Create an event procedure for the Page_Load event • Create an event procedure for the Page_Load event. redistribute. Create an event procedure for the Click event of the Cancel button. Note: Notice that the initial event procedure for the Click event of the CustomerInsertButton control is added in the code window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. Page_Load event. ByVal e As System.LoadComplete End Sub  Task 5: Create an event procedure for the Page_Unload event • Create an event procedure for the Page_Unload event. and Page_Unload event.  Task 2: Create an event procedure for the Click event of the Cancel button • Open the InsertCustomer Web Form in the Design view. or resell this content. Create an event procedure for the Page_Load event. and create an event procedure for the Click event of the Cancel button. and provided to you by QuickStart Intelligence. with the Button control selected in the Designer. . 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. Create an event procedure for the Page_LoadComplete event. Protected Sub Page_Load(ByVal sender As Object.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. 4.Load End Sub  Task 4: Create an event procedure for the Page_LoadComplete event • Create an event procedure for the Page_LoadComplete event. you will have created event procedures for button controls.EventArgs) Handles Me. Create an event procedure for the Click event of the Insert button. Page_LoadComplete event. 3. Note: Notice that the initial event procedure for the Click event of the CustomerCancelButton is added to the class in the code window. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

within the Class member fields region. of type String.  Task 2: Add the class member fields • In the Customer class. The code snippet has been supplied by the senior developer. Create an entity component. The Licensed Content is licensed "as-is. add a private member field for the first name of the customer named customerFirstName. Private customerFirstName As String = Nothing • In the Customer class. guarantees or conditions. or resell this content. Add the class member fields 3.  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. Add the properties. of type String.com or by calling +1 800-785-3448. of type String. • Rename the default class file Class1. 5. 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.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. add a private member field for the address of the customer named customerAddress. Add a customer member declaration. add a region named Class member fields. . and provided to you by QuickStart Intelligence. add a private member field for the last name of the customer named customerLastName. 2. and insert the snippet by clicking Insert Snippet. Place the cursor on and right-click the line following the declaration of the customerAddress backing field. #Region "Class member fields" #End Region • In the Customer class. It is illegal to reprint. 6.vb.NET Web Form 4-55 Exercise 3: Creating an Entity Component The main tasks for this exercise are as follows: 1. Private customerAddress As String = Nothing • Append the remaining backing fields by using a code snippet named Customer class backing fields. and is placed in the My Code Snippets folder. and initialize to Nothing. Add the constructors. 4. 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. and initialize to Nothing. within the Class member fields region. Please report any unauthorized use of this content to piracy@microsoft. just below the class declaration.vb. and initialize to Nothing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. within the Class member fields region. to Customer. Private customerLastName As String = Nothing • In the Customer class. redistribute. Reference CustomerManagementEntities project from CustomerManagement project.

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. of nullable type Guid. guarantees or conditions.customerFirstName = value End If End If End Set End Property • In the Customer class. add a region named Properties. add a public property named FirstName. and provided to you by QuickStart Intelligence. that sets and gets the private member backing field named customerLastName. within the Properties region.Substring(0. #Region "Properties" #End Region • In the Customer class.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. ''' <summary> ''' The customer first name ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property FirstName As String Get Return Me. Please report any unauthorized use of this content to piracy@microsoft. within the Properties region.customerFirstName = String. append an auto-implemented public property named ID.customerFirstName End Get Set(ByVal value As String) ' Null value? If Value Is Nothing Then Me. below the Class member fields region. of type String. add a public property named LastName. within the Properties region. and ensure that the length is no longer than 50 characters by using the following lines of code. The Licensed Content is licensed "as-is. It is illegal to reprint.customerFirstName = value.com or by calling +1 800-785-3448. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Empty Else ' Only get the first 50 characters If (Value. . redistribute. that sets and gets the private member backing field named customerFirstName. of type String. and ensure that the length is no longer than 30 characters by using the following lines of code. ''' <summary> ''' The unique customer ID ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property ID() As Guid? • In the Customer class.Length > 50) Then Me. ''' <summary> ''' The customer last name ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property LastName As String Get Return Me. 50) Else Me.

customerAddress End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me.customerAddress = value End If End If End Set End Property • Append the remaining properties within the Properties region. including street name. of type String. and provided to you by QuickStart Intelligence. It is illegal to reprint. ''' <summary> ''' The customer address. and insert the snippet by clicking Insert Snippet.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.customerLastName = value End If End If End Set End Property • In the Customer class. or resell this content.Substring(0. ''' <summary> ''' The customer zip code or postal code ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property ZipCode() As String Get Return Me.NET Web Form 4-57 ' Null value? If value Is Nothing Then Me.customerZipCode End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me.Empty Else ' Only get the first 50 characters If (value. add a public property named Address.Length > 50) Then Me. by using a code snippet named Customer class properties. house number and floor ''' </summary> ''' <value></value> ''' <returns></returns> ''' <remarks></remarks> Public Property Address As String Get Return Me. Place the cursor on and right-click the line following the declaration of the Address property.Substring(0.Empty Else ' Only get the first 30 characters If (value.customerLastName = value. within the Properties region. redistribute. The Licensed Content is licensed "as-is. The code snippet has been supplied by the senior developer. Please report any unauthorized use of this content to piracy@microsoft.Length > 30) 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 ensure that the length is no longer than 50 characters by using the following lines of code. and is placed in the My Code Snippets folder.customerAddress = value.com or by calling +1 800-785-3448. 50) Else Me. that sets and gets the private member backing field named customerAddress.customerLastName = String. 30) Else Me. .customerAddress = String. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

Substring(0.customerCity = value. 30) Else Me. redistribute. guarantees or conditions.com or by calling +1 800-785-3448. or resell this content.customerState = value.Length > 30) Then Me.Length > 10) Then Me." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.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 = "" Else ' Only get the first 30 characters If (value.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.customerZipCode = value. Please report any unauthorized use of this content to piracy@microsoft.Length > 30) Then Me.QuickStart Intelligence 4-58 Introduction to Web Development with Microsoft® Visual Studio® 2010 If (value. 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. It is illegal to reprint. 10) Else Me.customerCity End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me.customerState End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me.Substring(0. The Licensed Content is licensed "as-is.customerState = "" Else ' Only get the first 30 characters If (value. and provided to you by QuickStart Intelligence.Substring(0.

Substring(0. 30) Else Me. guarantees or conditions.customerPhone = "" Else ' Only get the first 30 characters If (value. and provided to you by QuickStart Intelligence. .com or by calling +1 800-785-3448.NET Web Form 4-59 ''' <remarks></remarks> Public Property CountryID() As Guid? Get Return 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.Length > 50) Then Me.Substring(0.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.customerCountryID End Get Set(ByVal value As Guid?) Me.Length > 30) Then Me. The Licensed Content is licensed "as-is.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. 50) Else Me. It is illegal to reprint.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. or resell this content.customerEmailAddress End Get Set(ByVal value As String) If (value Is Nothing) Then Me." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute.customerPhone = value.customerEmailAddress = "" Else ' Only get the first 50 characters If (value. Please report any unauthorized use of this content to piracy@microsoft.customerEmailAddress = value.customerPhone End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me.

and provided to you by QuickStart Intelligence. It is illegal to reprint.customerWebAddress End Get Set(ByVal value As String) If (value Is Nothing) 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.customerCreditLimit End Get Set(ByVal value As Integer) ' Negative value? If value < 0 Then Me.QuickStart Intelligence 4-60 Introduction to Web Development with Microsoft® Visual Studio® 2010 ''' <remarks></remarks> Public Property WebAddress() As String Get Return Me. redistribute.customerCreatedDate End Get This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. 80) Else Me.customerWebAddress = "" Else ' Only get the first 80 characters If (value.Substring(0. or resell this content.Length > 80) Then Me. The Licensed Content is licensed "as-is. .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.customerWebAddress = value. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

or resell this content.Now) Then Me.customerCreatedBy = "" Else ' Only get the first 15 characters If (value. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.customerCreatedBy = value.com or by calling +1 800-785-3448.customerCreatedDate = DateTime.Length > 15) Then Me.customerModifiedDate End Get Set(ByVal value As DateTime?) ' Date in the past? If value < DateTime.customerCreatedBy End Get Set(ByVal value As String) ' Null value? If value Is Nothing Then Me." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.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.Substring(0. It is illegal to reprint.Now Then Me.customerModifiedDate = DateTime. .QuickStart Intelligence Adding Functionality to a Microsoft® ASP.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.Now Else Me.NET Web Form 4-61 Private Set(ByVal value As DateTime?) ' Date in the past? If (value < DateTime.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. The Licensed Content is licensed "as-is.customerModifiedBy This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 15) Else Me. redistribute.

customerModifiedBy = "" Else ' Only get the first 15 characters If (value. . and provided to you by QuickStart Intelligence. #Region "Constructors" #End Region • In the Customer class. Please report any unauthorized use of this content to piracy@microsoft. ''' <summary> ''' Default parameterless constructor ''' </summary> ''' <remarks></remarks> Public Sub New() ' Initialize backing fields with default values Me.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.com or by calling +1 800-785-3448. 15) Else Me. redistribute. ''' <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. Place the cursor on and right-click the line following the default parameterless constructor. and insert the snippet by clicking Insert Snippet.Substring(0.customerModifiedBy = value End If End If End Set End Property  Task 4: Add the constructors • In the Customer class. by using the public properties.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. The code snippet has been supplied by the senior developer.CreatedDate = DateTime." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.ID = id Me. within the Constructors region. or resell this content.CreatedDate = DateTime.Now End Sub • Append the remaining properties within the Constructors region by using a code snippet named Customer class constructors. It is illegal to reprint. and is placed in the My Code Snippets folder.customerModifiedBy = value.Length > 15) Then Me. add a region named Constructors below the Properties region. add the default public parameterless constructor that initializes the customerID and customerCreatedDate member fields. The Licensed Content is licensed "as-is.ID = Guid. guarantees or conditions.NewGuid() Me.

Address = address Me.NewsSubscriber = newsSubscriber If Not createdDate Is Nothing Then Me. and initialize to Nothing. ByVal city As String. ByVal firstName As String.City = city Me.vb code window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.WebAddress = webAddress Me.ModifiedBy = modifiedBy End Sub • Save the changes to Customer.EmailAddress = emailAddress Me.vb. ByVal createdBy As String.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.vb file.CreatedDate = createdDate Else Me. Please report any unauthorized use of this content to piracy@microsoft. .aspx. • In the InsertCustomer. ByVal modifiedBy As String) ' Initialize member backing fields with passed values Me. ByVal modifiedDate As DateTime?.ZipCode = zipCode Me. ByVal createdDate As DateTime?. ByVal phone As String.aspx. ByVal webAddress As String. ByVal lastName As String. ByVal state As String. ByVal newsSubscriber As Boolean. Reference the CustomerManagementEntities project from the CustomerManagement project. ByVal countryID As Guid?.ID = id Me.CreatedBy = createdBy Me. add a private class member declaration of the Customer class in the CustomerManagementEntities namespace.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?. redistribute. and fix any errors.Now End If Me.FirstName = firstName Me. ByVal creditLimit As Integer.LastName = lastName Me.CreatedDate = DateTime.com or by calling +1 800-785-3448. ByVal emailAddress As String. or resell this content.CountryID = countryID Me.CreditLimit = creditLimit Me. guarantees or conditions. named currentCustomer. The Licensed Content is licensed "as-is.Phone = phone Me.ModifiedDate = modifiedDate Me. • Build the component.  Task 5: Reference CustomerManagementEntities project from CustomerManagement project • Add a reference to the CustomerManagement project by using the Add 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.  Task 6: Add a customer member declaration • Open the InsertCustomer. It is illegal to reprint. ByVal address As String.State = state Me. ByVal zipCode As String.

and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. redistribute. Please report any unauthorized use of this content to piracy@microsoft. 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.Customer = Nothing Results: After completing this exercise. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. . The Licensed Content is licensed "as-is. guarantees or conditions.QuickStart Intelligence 4-64 Introduction to Web Development with Microsoft® Visual Studio® 2010 Private currentCustomer As CustomerManagementEntities. added a reference to the component project from the Web site. you will have created a new component by using the Class Library project.

Text.LoadComplete This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Handle the user cancellation. Destroy the objects." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. CustomerNewsSubscriberCheckBox. ''' <summary> ''' Populates UI controls ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub Page_LoadComplete(ByVal sender As Object. . "") End If End Sub  Task 2: Populate the UI controls • In the InsertCustomer class. CustomerPhoneTextBox.Load ' Instantiate Customer instantiateCustomerObject() End Sub • Appending the following code to the InsertCustomer class. It is illegal to reprint.Text. ByVal e As System.IsPostBack Then ' Instantiate new Customer object currentCustomer = New CustomerManagementEntities. Nothing. CustomerFirstNameTextBox. Instantiate the Customer object.Text. ''' <summary> ''' Instantiates Customer object ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub Page_Load(ByVal sender As Object. ''' <summary> ''' Instantiates and populates the Customer member object ''' </summary> ''' <remarks></remarks> Private Sub instantiateCustomerObject() ' First time loading page? If Not Me. 4. 2.EventArgs) Handles Me. Nothing. CustomerZipCodeTextBox.Text.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. populate the server controls in the UI by using the values from the private Customer object currentCustomer. DateTime.  Task 1: Instantiate the Customer object • Instantiate the Customer object by using the following code.EventArgs) Handles Me. 3. Populate the UI controls. CustomerWebAddressTextBox.Text.NET Web Form 4-65 Exercise 4: Handling Page and Control Events The main tasks for this exercise are as follows: 1.Text. CustomerStateTextBox. ByVal e As System. -1. _ "".Customer( Nothing. guarantees or conditions. or resell this content. The Licensed Content is licensed "as-is.Text.Text.Now. Save the customer information. CustomerCityTextBox. 5. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.Text. redistribute.Customer() Else ' Instantiate new Customer object with user input currentCustomer = New CustomerManagementEntities. CustomerLastNameTextBox.Checked. CustomerEmailAddressTextBox. CustomerAddressTextBox.

LastName CustomerAddressTextBox. or resell this content.Text = currentCustomer. ''' <summary> ''' Destroys objects ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub Page_Unload(ByVal sender As Object. The Licensed Content is licensed "as-is.Text = currentCustomer. ByVal e As System. .State If currentCustomer.Text = currentCustomer. and provided to you by QuickStart Intelligence.SelectedValue = currentCustomer.EmailAddress CustomerWebAddressTextBox." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.WebAddress CustomerCreditLimitTextBox.FirstName CustomerLastNameTextBox.Text = currentCustomer. handle user cancellation by redirecting to the home page.City CustomerStateTextBox.Click ' Redirect to home page Response.Text = currentCustomer.Redirect("~/Default.EventArgs) Handles CustomerCancelButton.Unload ' Destroy Customer object currentCustomer = Nothing End Sub  Task 4: Handle the user cancellation • In the InsertCustomer class.CreditLimit.Text = currentCustomer.Text = currentCustomer.EventArgs) Handles Me.ZipCode CustomerCityTextBox.Text = currentCustomer.aspx") End Sub This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Text = currentCustomer.Phone CustomerEmailAddressTextBox.NewsSubscriber End Sub  Task 3: Destroy the objects • In the InsertCustomer class. redistribute.Value. ByVal e As System. guarantees or conditions.ToString() Else CustomerCountryDropDownList. Please report any unauthorized use of this content to piracy@microsoft.SelectedIndex = -1 End If CustomerPhoneTextBox.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.CountryID.HasValue Then CustomerCountryDropDownList.Address CustomerZipCodeTextBox.ToString() CustomerNewsSubscriberCheckBox.Text = currentCustomer.com or by calling +1 800-785-3448.CountryID. ''' <summary> ''' Redirects to home page ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub CustomerCancelButton_Click(ByVal sender As Object. destroy the objects used in the class that are not automatically handled by the garbage collector. It is illegal to reprint.Checked = currentCustomer.

Note: The initial code for saving the customer information is created here.Name ' Add the user credit limit currentCustomer. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will have added code to handle the Page. Note: Notice that the validation successfully completes.LoadComplete.QuickStart Intelligence Adding Functionality to a Microsoft® ASP.vb. • Build the solution and fix any errors.CreatedBy = Context.User. However. It is illegal to reprint. • Revert the changes made to the 10267A-GEN-DEV virtual machine. and added code to handle the Click event for the Insert and Cancel button controls. Results: After completing this exercise.Load.com or by calling +1 800-785-3448.Click ' Add the current user name currentCustomer. Note: The answers to the exercises are on the Course Companion CD. ''' <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. or resell this content. the final code for saving to the database will be created in Module 8. .CreditLimit = 50000 End Sub • Save the changes to InsertCustomer. and Page.Unload events for the InsertCustomer Web Form. Please report any unauthorized use of this content to piracy@microsoft.EventArgs) Handles customerInsertButton. prepare for saving the customer input information to persistent storage when the user clicks the Insert button. redistribute.  Task 6: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. • Close Visual Studio 2010. The Licensed Content is licensed "as-is.Identity.NET Web Form 4-67  Task 5: Save the customer information • In the InsertCustomer class. guarantees or conditions. ByVal e As System.aspx. Page.

 Task 1: Open an existing Web site • Log on to 10267A-GEN-DEV as Student. and provided to you by QuickStart Intelligence. you will have opened the existing CustomerManagement Web site and the InsertCustomer Web Form code-behind file. or resell this content. Open the code-behind file for an existing Web Form.com or by calling +1 800-785-3448. 2.  Task 2: Open the code-behind file for an existing Web Form • Open the code-behind file of the InsertCustomer Web Form.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. by using the View Code context menu command." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Results: After completing this exercise. • Open Microsoft Visual Studio 2010. Open an existing ASP. guarantees or conditions. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web site. . Pa$$w0rd. The Licensed Content is licensed "as-is. redistribute. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M4\CS folder. with the password.

and create an event procedure for the Click event of the Insert button. guarantees or conditions. and provided to you by QuickStart Intelligence.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will have created event procedures for button controls Page_LoadComplete event.NET Web Form 4-69 Exercise 2: Creating Event Procedures The main tasks for this exercise are as follows: 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. by double-clicking the Button control. The Licensed Content is licensed "as-is. and Page_Unload event. by double-clicking the box next to the Click event in the Properties window.com or by calling +1 800-785-3448. redistribute. 3. EventArgs e) { } Results: After completing this exercise.  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. Note: Notice that the initial event procedure for the Click event of the CustomerInsertButton control is added in the code window. Note: Notice that the initial event procedure for the Click event of the CustomerCancelButton is added to the class in the code window. Please report any unauthorized use of this content to piracy@microsoft. 2. Create an event procedure for the Page_LoadComplete event.  Task 2: Create an event procedure for the Click event of the Cancel button • Open the InsertCustomer Web Form in the Design view. 4. Create an event procedure for the Click event of the Cancel button. or resell this content. and create an event procedure for the Click event of the Cancel button.  Task 1: Create an event procedure for the Click event of the Insert button • Open the InsertCustomer Web Form in the Design view. with the Button control selected in the Designer. Create an event procedure for the Page_Unload event. . It is illegal to reprint. Create an event procedure for the Click event of the Insert button.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. string customerPhone = null. DateTime? customerCreatedDate = null. 5.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. Add a customer member declaration. DateTime? customerModifiedDate = null. string customerState = null. and initialize to null. • Rename the default class. Add the properties. string customerEmailAddress = null. Add the constructors.com or by calling +1 800-785-3448. Create an entity component. add a private member field for the last name of the customer named customerLastName. private string customerFirstName = null. The Licensed Content is licensed "as-is. string customerCreatedBy = null. #region Class member fields #endregion • In the Customer class. of type string. within the Class member fields region. Please report any unauthorized use of this content to piracy@microsoft. 2. within the Class member fields region.  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. redistribute. and is placed in the My Code Snippets folder.cs. add a region named Class member fields. add a private member field for the address of the customer named customerAddress. int customerCreditLimit = 0.cs. private string customerAddress = null. file as Customer. add a private member field for the first name of the customer named customerFirstName. • In the Customer class. and provided to you by QuickStart Intelligence. Reference CustomerManagementEntities project from CustomerManagement project. within the Class member fields region. The code snippet has been supplied by the senior developer. Guid? customerCountryID = null. bool customerNewsSubscriber = false. Class1. • In the Customer class. Place the new project in the D:\Labfiles\Starter\M4\CS folder. of type string. and initialize to null. 4. and initialize to null. 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. or resell this content. guarantees or conditions. private private private private private private private private private private private private string customerZipCode = null. string customerWebAddress = null. • Append the remaining backing fields by using a code snippet named Customer class backing fields.  Task 2: Add the class member fields • In the Customer class. Add the class member fields. just below the class declaration. 6. private string customerLastName = null. of type string. . 3. string customerCity = null. Note: Notice that the CustomerManagementEntities class library project is added to the solution. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

com or by calling +1 800-785-3448. else this. 50). } • In the Customer class." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Ensure that the length is no longer than 50 characters.Length > 50) this. #region Properties #endregion • In the Customer class. and provided to you by QuickStart Intelligence. within the Properties region.customerLastName = value. else // Only get the first 30 characters if (value.customerFirstName = value.NET Web Form 4-71 private string customerModifiedBy = null. by using the following lines of code. } set { // Null value? if (value == null) this.customerLastName. add a region named Properties. /// <summary> /// The customer last name /// </summary> public string LastName { get { return this. } set { // Null value? if (value == null) this.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft.customerFirstName. add a public property named LastName. /// <summary> /// The customer first name /// </summary> public string FirstName { get { return this.customerLastName = "".Substring(0. or resell this content. that sets and gets the private member backing field named customerFirstName. of type string. by using the following lines of code. within the Properties region. of type string. below the Class member fields region. It is illegal to reprint. add a public property named FirstName. else // Only get the first 50 characters if (value. append an auto-implemented public property named ID. . redistribute. of nullable type Guid. } } • In the Customer class.customerFirstName = value.Length > 30) this. The Licensed Content is licensed "as-is. 30).  Task 3: Add the properties • In the Customer class.customerFirstName = "". within the Properties region. guarantees or conditions.Substring(0. Ensure that the length is no longer than 30 characters. set. that sets and gets the private member backing field named customerLastName. /// <summary> /// The unique customer ID /// </summary> public Guid? ID { get. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

within the Properties region.com or by calling +1 800-785-3448.customerZipCode = value. else // Only get the first 50 characters if (value.customerAddress.customerZipCode. by using a code snippet named Customer class properties. else this. Place the cursor on and right-click the line following the declaration of the Address property.QuickStart Intelligence 4-72 Introduction to Web Development with Microsoft® Visual Studio® 2010 } • } else this. Please report any unauthorized use of this content to piracy@microsoft.customerAddress = value. . /// <summary> /// The customer address. The code snippet has been supplied by the senior developer. including street name.customerZipCode = value.customerZipCode = "". or resell this content. 50). } } /// <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.Length > 10) this. In the Customer class.Substring(0." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. add a public property named Address. of type string. The Licensed Content is licensed "as-is. guarantees or conditions. 10). } } • Append the remaining properties within the Properties region. house number and floor /// </summary> public string Address { get { return this. and insert the snippet by clicking Insert Snippet. Ensure that the length is no longer than 50 characters. else this.Substring(0. that sets and gets the private member backing field named customerAddress.customerAddress = value. else // Only get the first 10 characters if (value.customerLastName = value. /// <summary> /// The customer zip code or postal code /// </summary> public string ZipCode { get { return this.customerAddress = "". } set { // Null value? if (value == null) this. It is illegal to reprint. redistribute. and is placed in the My Code Snippets folder.Length > 50) this. and provided to you by QuickStart Intelligence. by using the following lines of code. } set { // Null value? if (value == null) this.

The Licensed Content is licensed "as-is.customerCountryID." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.customerCountryID = value. } set { // Null value? if (value == null) this. .NET Web Form get { } set { } } 4-73 return this.customerState = value.customerPhone.Substring(0.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. // Null value? if (value == null) this.com or by calling +1 800-785-3448. else this. /// <summary> /// The name of the state or region in which the customer lives /// </summary> public string State { get { return this. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.customerState = value. or resell this content.customerCity.customerState. } } /// <summary> /// The customer phone number /// </summary> public string Phone { get { return this.Length > 30) this.customerCity = "". This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Substring(0. } } /// <summary> /// The ID of the country in which the customer lives /// </summary> public Guid? CountryID { get { return this. and provided to you by QuickStart Intelligence. else // Only get the first 30 characters if (value.customerCity = value. else // Only get the first 30 characters if (value.customerCity = value.customerState = "".Length > 30) this. 30). else this. 30). It is illegal to reprint. redistribute. } set { this.

redistribute.Length > 50) this. } set { // Null value? if (value == null) this." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.customerPhone = "". else this.Substring(0. 30).Length > 80) this. 80). } set { // Null value? if (value == null) this.customerEmailAddress = "".customerWebAddress = value.Substring(0. It is illegal to reprint. } } /// <summary> /// The customer Web address /// </summary> public string WebAddress { get { return this. else // Only get the first 30 characters if (value. 50).customerEmailAddress = value.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. /// <summary> /// The customer e-mail address /// </summary> public string EmailAddress { get { return this.customerWebAddress.customerPhone = value.customerWebAddress = value.customerWebAddress = "".customerEmailAddress.customerPhone = value.Substring(0. else this. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 4-74 Introduction to Web Development with Microsoft® Visual Studio® 2010 } set { } } // Null value? if (value == null) this.Length > 30) this. . else // Only get the first 80 characters if (value. or resell this content.customerEmailAddress = value. and provided to you by QuickStart Intelligence. guarantees or conditions. else this. else // Only get the first 50 characters if (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.

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

else // Only get the first 15 characters if (value. } set { // Date in the past? if (value < DateTime. /// <summary> /// Default parameterless constructor This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.customerCreatedBy = value. or resell this content. and provided to you by QuickStart Intelligence. else this. . below the Properties region. within the Constructors region.Length > 15) this. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. 15). else // Only get the first 15 characters if (value. } } /// <summary> /// The name of the user who last modified the customer /// </summary> public string ModifiedBy { get { return this.QuickStart Intelligence 4-76 Introduction to Web Development with Microsoft® Visual Studio® 2010 } } this.customerCreatedBy = value. 15).Length > 15) this.Now) this.Substring(0.customerModifiedDate = value. } set { // Null value? if (value == null) this.customerModifiedBy.customerModifiedDate. It is illegal to reprint. add the default public parameterless constructor that initializes the customerID and customerCreatedDate member fields by using the public properties.customerModifiedBy = value. } }  Task 4: Add the constructors • In the Customer class. redistribute.customerModifiedBy = value. /// <summary> /// The date the customer was last modified in the system /// </summary> public DateTime? ModifiedDate { get { return this.customerCreatedBy = "".customerModifiedBy = "". else this." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. add a region named Constructors.Now.customerModifiedDate = DateTime.Substring(0.com or by calling +1 800-785-3448. #region Constructors #endregion • In the Customer class. guarantees or conditions. else this.

ID = id. bool newsSubscriber. guarantees or conditions. string lastName.NewsSubscriber = newsSubscriber. string webAddress. The Licensed Content is licensed "as-is. string firstName. DateTime? createdDate.LastName = lastName. int creditLimit. this.WebAddress = webAddress. } /// <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.com or by calling +1 800-785-3448.ID = id." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. /// <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. this. this.City = city. or resell this content.CreditLimit = creditLimit. this. string city. and insert the snippet by clicking Insert Snippet.State = state. this. this. DateTime? modifiedDate. and is placed in the My Code Snippets folder.FirstName = firstName. this. string phone. The code snippet has been supplied by the senior developer.NET Web Form 4-77 /// </summary> public Customer() { // Initialize backing fields with default values this. string emailAddress.Now.Address = address.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft.EmailAddress = emailAddress. this.CountryID = countryID. string modifiedBy) { // Initialize member backing fields with passed values this. Guid? countryID.Phone = phone. this. Place the cursor on and right-click the line following the default parameterless constructor. this. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.ID = Guid. this. . this. string zipCode. and provided to you by QuickStart Intelligence. It is illegal to reprint. string address. this.NewGuid(). } • Append the remaining properties within the Constructors region by using a code snippet named Customer class constructors. string createdBy.Now.ZipCode = zipCode.CreatedDate = DateTime. string state.CreatedDate = DateTime. this.

and added a member variable of type Customer. and provided to you by QuickStart Intelligence. and initialize to null.CreatedBy = createdBy.QuickStart Intelligence 4-78 Introduction to Web Development with Microsoft® Visual Studio® 2010 if (createdDate != null) this. Results: After completing this exercise." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Reference the CustomerManagementEntities project from the CustomerManagement project.  Task 5: Reference CustomerManagementEntities project from CustomerManagement project • Add a reference to the CustomerManagement project by using the Add Reference dialog box.aspx.ModifiedDate = modifiedDate.cs. this. added a reference to the component project from the Web site. you will have created a new component by using the Class Library project. . add a private class member declaration of the Customer class in the CustomerManagementEntities namespace named currentCustomer.CreatedDate = DateTime. and fix any errors.Now.CreatedDate = createdDate. • In the InsertCustomer.aspx. } this. or resell this content. this. else this.cs file. • Save the changes to Customer. The Licensed Content is licensed "as-is.  Task 6: Add a customer member declaration • Open the InsertCustomer. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Customer currentCustomer = null. Please report any unauthorized use of this content to piracy@microsoft. private CustomerManagementEntities. • Build the component.ModifiedBy = modifiedBy. It is illegal to reprint.com or by calling +1 800-785-3448.cs code window. guarantees or conditions. redistribute.

Text. -1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. CustomerCityTextBox. guarantees or conditions. Handle the user cancellation. CustomerPhoneTextBox.NET Web Form 4-79 Exercise 4: Handling Page and Control Events The main tasks for this exercise are as follows: 1. } • Append the following code to the InsertCustomer class.Customer( null.Text. Destroy the objects. The Licensed Content is licensed "as-is. null. Instantiate the Customer object. /// <summary> /// Populates UI controls /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_LoadComplete(object sender.Text.Text. CustomerEmailAddressTextBox. EventArgs e) { // Populate the UI controls populateUI().Text.Checked. 3. . /// <summary> /// Instantiates and populates the Customer member object /// </summary> private void instantiateCustomerObject() { // First time loading page? if (!this.Now. DateTime.IsPostBack) // Instantiate new Customer object currentCustomer = new CustomerManagementEntities. and provided to you by QuickStart Intelligence. CustomerNewsSubscriberCheckBox. populate the server controls in the UI by using the values from the private Customer object. CustomerLastNameTextBox.Text. }  Task 2: Populate the UI controls • In the InsertCustomer class. CustomerFirstNameTextBox.Text. Save the customer information. CustomerWebAddressTextBox.com or by calling +1 800-785-3448.Text. currentCustomer. or resell this content. 5. EventArgs e) { // Instantiate Customer instantiateCustomerObject(). Please report any unauthorized use of this content to piracy@microsoft. "").  Task 1: Instantiate the Customer object • Instantiate the Customer object by using the following code. "". 4. CustomerStateTextBox. Populate the UI controls. null.Text. CustomerZipCodeTextBox. CustomerAddressTextBox. redistribute. 2. It is illegal to reprint. /// <summary> /// Instantiates Customer object /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. } /// <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.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.Value. }  Task 5: Save the customer information • In the InsertCustomer class.ToString().Address.CountryID.Text = currentCustomer. Please report any unauthorized use of this content to piracy@microsoft.WebAddress.Text = currentCustomer. CustomerEmailAddressTextBox.Text = currentCustomer.Text = currentCustomer. CustomerWebAddressTextBox. CustomerCreditLimitTextBox. handle user cancellation by redirecting to the home page. The Licensed Content is licensed "as-is.LastName. prepare to save the customer input information to persistent storage when the user clicks the Insert button.SelectedIndex = -1. CustomerLastNameTextBox.Text = currentCustomer. redistribute. destroy the objects used in the class that are not automatically handled by the garbage collector.Redirect("~/Default.FirstName.NewsSubscriber. guarantees or conditions. CustomerStateTextBox. EventArgs e) { // Redirect to home page Response.HasValue) CustomerCountryDropDownList.Phone. It is illegal to reprint.Checked = currentCustomer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Text = currentCustomer. }  Task 4: Handle the user cancellation • In the InsertCustomer class.CreditLimit. CustomerCityTextBox. /// <summary> /// Redirects to home page /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CustomerCancelButton_Click(object sender. if (currentCustomer. CustomerAddressTextBox. else CustomerCountryDropDownList.ZipCode.CountryID. or resell this content. } CustomerPhoneTextBox.Text = currentCustomer.State. CustomerNewsSubscriberCheckBox.aspx").  Task 3: Destroy the objects • In the InsertCustomer class. EventArgs e) { // Destroy Customer object currentCustomer = null. .City.Text = currentCustomer.SelectedValue = currentCustomer.ToString().Text = currentCustomer. EventArgs e) This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Text = currentCustomer.EmailAddress. /// <summary> /// Destroys objects /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Unload(object sender. /// <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. CustomerZipCodeTextBox.

However. • Build the solution. It is illegal to reprint. // Add the user credit limit currentCustomer. and fix any errors. Please report any unauthorized use of this content to piracy@microsoft.User. • Revert the changes made to the 10267A-GEN-DEV virtual machine. Note: Notice that the validation successfully completed.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. redistribute. you will have added code to handle the Page.com or by calling +1 800-785-3448. guarantees or conditions. . Page. • Close Visual Studio 2010. Results: After completing this exercise.Identity.CreatedBy = Context.NET Web Form { } 4-81 // Add the current user name currentCustomer. • Save the changes to InsertCustomer. 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. and added code to handle the Click event for the Insert and Cancel button controls.LoadComplete. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and Page.Name." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.Load.CreditLimit = 50000.cs. The Licensed Content is licensed "as-is. Note: The initial code for saving the customer information is created here.Unload events for the InsertCustomer Web Form.aspx. Note: The answers to the exercises are on the Course Companion CD.

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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. What is the default event procedure for common controls? 3. The Licensed Content is licensed "as-is. or resell this content. . It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.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.com or by calling +1 800-785-3448. redistribute. and provided to you by QuickStart Intelligence. guarantees or conditions.

but you do not want to manually have to wire up the event handlers. and is suffixed by the data type when appropriate. How can you use a component in your Visual Studio 2010 project? Real-World Issues and Scenarios 1. or resell this content. 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.com or by calling +1 800-785-3448. redistribute. and the name is CustomerManagement. The latter is close to Pascal Casing." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. The casing differs between Pascal Casing and Camel Casing. and Length. In this course. • If you are naming a variable of a specific object type. Examples are FirstName. such as “firstName”. You want to add page events to a code-behind file. whereas Camel Casing is used This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. such as CustomerManagementDataSet. guarantees or conditions. a naming convention consisting of what the variable contains. What is the advantage of code-behind files when you add functionality to a Web Form? 2. Best Practices • Follow a naming and casing convention when naming your variables. LastName. Age. always use the object type name as the suffix. 2. and provided to you by QuickStart Intelligence. If a variable contains one of the simple data types—such as Integer or String—it is most often not necessary to suffix with the data type. What is the easiest way to implement this? Specify a value of true for the AutoEventWireUp attribute of the Page directive. How is an event procedure associated with the event of a server control? 3. where the data type is DataSet. It is illegal to reprint. Name. but always uses an initial lower-case letter. such as “FirstName”. is used. Please report any unauthorized use of this content to piracy@microsoft. where the former capitalizes the first character of each word—including acronyms over two letters in length. Pascal Casing is generally used for public variables.NET Web Form 4-83 Module Review and Takeaways Review Questions and Answers 1.QuickStart Intelligence Adding Functionality to a Microsoft® ASP. . What is the easiest way to implement this? Use a Web Form with a code-behind file.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a naming convention consisting of what the method does. See the next best practice regarding public variables. or resell this content. as well as method parameters. because that can corrupt the state of an object. guarantees or conditions. • Member variables—also known as backing fields—as a general rule should never be made public. Casing uses the same rules as for variables—public methods use Pascal Casing. whereas non-public properties use Camel Casing. Instead. Please report any unauthorized use of this content to piracy@microsoft. whereas non-public methods use Camel Casing. such a GetUserID or SaveID.QuickStart Intelligence 4-84 Introduction to Web Development with Microsoft® Visual Studio® 2010 for local and private variables. make a member variable private. • Follow a naming and casing convention when naming your methods. • Follow a naming and casing convention when naming your properties. . and expose the value through a property with which you can check when a user of the object sets the value of the property. but always with the first word of the name being a verb. Casing uses the same rules as for variables and methods—public properties use Pascal Casing. the naming convention used describes the data it makes available—such as FirstName—but never with the first word of the name being a verb—such as used for method names (GetFirstName). In this course. redistribute. It is illegal to reprint. and provided to you by QuickStart Intelligence. In this course. There are exceptions to this rule. but that is beyond the scope of this module. such as some instances of when an object needs to be serialized. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is.

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.com or by calling +1 800-785-3448. It is illegal to reprint. redistribute. guarantees or conditions. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .

and how to implement user controls in a Web application. you need to add one or more Microsoft® ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web pages. user controls help you reuse UI components in a custom manner. you will learn how to create and implement master pages. redistribute. While master pages help you provide a consistent look to your Web application. guarantees or conditions. controls to view and edit order information. You can add existing Web server controls and markup to a user control.QuickStart Intelligence 5-2 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Overview When you design your Web application. Please report any unauthorized use of this content to piracy@microsoft. You may use the same combination of controls on different pages—for example. You can then embed them in ASP. and define properties and methods for the control.com or by calling +1 800-785-3448. . where they can function as a unit. and provided to you by QuickStart Intelligence. or resell this content. The Licensed Content is licensed "as-is. Quite often. It is illegal to reprint. In this module.NET Web Forms to your project. You can use master pages to apply a consistent design to your Web site without having to duplicate the design on multiple Web Forms. you have to apply a consistent design to the user interface (UI). User controls provide an easy way to reuse common UI components and code across a Web application.

• Describe nested master pages.master file. Master pages provide several benefits. or resell this content. You can edit the master page elements of a Web application from one location. and provide a good user experience. Please report any unauthorized use of this content to piracy@microsoft. • Create a content page. guarantees or conditions. It is illegal to reprint. • Describe content pages. You can make design changes on a master page that will immediately be reflected on all of the pages that use that master page.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. • Add a master page to an existing Web application project. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Describe the runtime behavior of master pages. without having to customize all the pages that use the common elements. you will learn how to create a master page. Lesson Objectives After completing this lesson. In this lesson. and then create a Web Form that uses the master page. . redistribute. The Licensed Content is licensed "as-is. • Create a master page. • Describe the advantages of master pages. and provided to you by QuickStart Intelligence. You can easily create a Web application with a consistent look and feel.com or by calling +1 800-785-3448.NET application from a single location—the . You then reuse the layout in all the content pages that are derived from that master page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will be able to: • Describe master pages.

redistribute. and you can include files and user controls. you can include several master pages in your project. you can use a master page to create a predefined layout.master.aspx to . A single master page defines the look and feel.NET master pages allow you to create a consistent layout for the pages in your application. and it is identified by a special Master directive that replaces the Page directive that is used for ordinary Web Form pages. you can create the functionality that was previously provided by using framesets. MasterPage.NET file with the extension . Please report any unauthorized use of this content to piracy@microsoft.NET Web Forms. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.master. and another section for anonymous users. . If you want the different sections of your Web application to have different layouts.QuickStart Intelligence 5-4 Introduction to Web Development with Microsoft® Visual Studio® 2010 What Are Master Pages? Key Points ASP. as follows. the header that you want to display on multiple pages of a Web site. The Master directive is used instead of the Page directive. guarantees or conditions. The master page is an ASP. Therefore. For example. you may have one section of your Web application for authenticated users. By using master pages. which can include static text. It is illegal to reprint.aspx—for example.master.com or by calling +1 800-785-3448. [Visual Basic] <%@ Master Language="VB" AutoEventWireup="false" CodeFile="MasterPage.master. Master Page Features The file extension for a master page is changed from . and server controls. and standard behavior that you want for all the pages or a group of pages in your application. You can place common Web site content on a master page—for example. You can then create individual content pages that contain the content that you want to display. Master pages can contain the same types of controls and code as standard ASP. HTML elements.vb" Inherits="MasterPage" %> [Visual C#] This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

.master file extension from being viewed in a Web browser. <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.com or by calling +1 800-785-3448. ContentPlaceHolder controls define the areas where replaceable content can appear. an img element for the company logo. or within the form element.. guarantees or conditions. It is illegal to reprint. or resell this content. The Licensed Content is licensed "as-is. on a master page. then the default content from the ContentPlaceHolder control on the master page is shown on the rendered page. and server controls for site navigation.cs" Inherits="MasterPage" %> Note: By default.master. However.QuickStart Intelligence Implementing Master Pages and User Controls 5-5 <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage. You must place the ContentPlaceHolder controls within the head element. A master page is almost like a standard Web Form. redistribute. the replaceable content is defined in content pages. and provided to you by QuickStart Intelligence.. <html> <head runat="server"> <title>General Application Title</title> <asp:ContentPlaceHolder id="HeadContentPlaceHolder" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> . This security measure ensures that you do not view the master page as a stand-alone ASP. </form> </body> If a content page that is linked with the master page does not include a Content control that references the ContentPlaceHolder control.0 prevents files with the ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. because it can contain standard content. In turn.. static text for the copyright notice. For example. what differentiates a master page from a standard Web Form is the inclusion of one or more ContentPlaceHolder controls.. .. you might use an HTML table for the layout or a combination of div elements to display the elements on the page. body. a Web server such as Internet Information Services (IIS) 7. and form. Please report any unauthorized use of this content to piracy@microsoft. head. as follows.NET page. including the top-level HTML elements for a page such as html. <! Standard content > <div class="top"> <asp:ContentPlaceHolder id="MainContentPlaceHolder" runat="server" /> . which is as follows. <! 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> .

f. you will use a table to help you position elements on the page. The Licensed Content is licensed "as-is. click Visual Basic or Visual C#. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Click Add.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. right-click the project. 2. e. . if you want to use a code-behind file. and then click Add New Item. In the middle pane box. In the Add New Item dialog box: a. In this example. A master page also contains one or more content placeholders that designate where dynamic content will appear when pages are displayed. Select the Place code in a separate file check box. In the left pane. Switch to Design view. In Solution Explorer. and provided to you by QuickStart Intelligence. if you want to nest the master page. Select the Select master page check box." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. You will start by creating a layout table to hold the master page elements. It is illegal to reprint. or resell this content. In the Name box. Please report any unauthorized use of this content to piracy@microsoft. d. you need to perform the following steps: 1. You will then position the content placeholder control that is already on the page. It can contain any combination of static text and controls. Setting the Layout of a Master Page The master page defines how the pages in your site look. type a name for the master page. b. perform the following steps: 1. redistribute. click Master Page.  Create a layout table for the master page To create a layout table for the master page. c. guarantees or conditions.

and then set valign to top. The color you select is not important. 7. The template defines the arrangement of rows and cells in the table. and set its Height to 48. Click the page where you want to place the layout table. The template that you have selected creates three rows. 6. and provided to you by QuickStart Intelligence.QuickStart Intelligence Implementing Master Pages and User Controls 5-7 2. and then click OK. and two cells/columns. In the Insert Table dialog box. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. redistribute.com or by calling +1 800-785-3448. On the Table menu. From the drop-down list at the top of the Properties window. 3. • Click the bottom row. If you have a logo graphic available. you can add that also. . and set its Width to 48. apply the following settings: • In the middle row. click a background distinctive color in the BgColor box. click the leftmost column." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. set BgColor to a different color other than the background color. click Insert Table. such as in a div element. you can add content to the master page that will appear on all pages. 4. and then in the DOCUMENT list. The Licensed Content is licensed "as-is. type 3. • Click the top row. It is illegal to reprint. You can add a copyright message as a footer. Select all cells in the table. 5. In the Properties window. 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. in the Rows box. and set its Height to 48. and then add a menu. guarantees or conditions. select DOCUMENT. After setting the layout of the table.

A content page is an ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is.NET pages (. you can add new content pages. and provided to you by QuickStart Intelligence. When you specify a reference to a master page at the page level. You can also specify a master page at the application level in the web. Content Page Features You can reference a master page by using the MasterPageFile attribute in the Page directive of the content page.config file. if you reference a non-existing ContentPlaceHolder control.vb" Inherits="ContentPage" %> [Visual C#] <%@ Page Language="C#" MasterPageFile="~/MasterPage. as follows.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. <pages masterPageFile="MasterPage. When you have one or more master pages in your project.com or by calling +1 800-785-3448. or resell this content. or convert your existing Web Forms to content pages.aspx. guarantees or conditions.master" AutoEventWireup="true" CodeFile="ContentPage. as indicated in the follow examples.NET Web Form that references a specific master page.aspx.aspx files) in the application should automatically bind to the specified master page.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. [Visual Basic] <%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="ContentPage. . redistribute.master" /> You can specify that all ASP. Please report any unauthorized use of this content to piracy@microsoft. By using content pages. you will This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. if the page contains one or more Content controls. It is illegal to reprint. you can create additional content that merges at run time with the generic content from the master page.

Content pages must contain at least one Content control that references a ContentPlaceHolder control on the referenced master page. and provided to you by QuickStart Intelligence. You can perform any tasks on a content page that you would do on an ASP. redistribute. If you specify a reference to a master page in the web. The MasterPageFile attribute of the Page directive overrides any master page setting specified in the web. anything that is not inside the Content controls—except script blocks for server code—results in a compile-time error. [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. and if you reference a non-existent file. . The Licensed Content is licensed "as-is. On a content page. The Content controls on the content page link directly to the ContentPlaceHolder controls on the master page. you will receive a runtime error.config file. you can generate content for a Content control by using server controls. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.NET page.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You cannot add a Content control that does not reference an existing ContentPlaceHolder control in the referenced master page. For example.config file. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence Implementing Master Pages and User Controls 5-9 receive a compile-time error. guarantees or conditions. or run database queries. as indicated in the following examples. It is illegal to reprint. you can add text and controls to them.

In the Add New Item dialog box. and then select the Place code in a separate file check box. The Licensed Content is licensed "as-is.master" AutoEventWireup="true" CodeFile="ContentPage. Please report any unauthorized use of this content to piracy@microsoft.master" AutoEventWireup="false" CodeFile="ContentPage. It is illegal to reprint. 3. and provided to you by QuickStart Intelligence. as follows.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.com or by calling +1 800-785-3448.aspx. redistribute. 7.sln file from the D:\Labfiles\Starter\M5\VB folder. and then click Add. or resell this content. In the Select a Master Page dialog box. In Solution Explorer. In the Name box. In the middle pane. Select the Select master page check box." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The ContentPlaceHolder controls on the specified master page are automatically referenced by using the Content controls on the new content page. and then click Add New Item. click either Visual Basic or Visual C#. to use a code-behind file. 6. 4.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.aspx. [Visual Basic] <%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage. Open the CustomerManagement. . in the left pane. click the master page. guarantees or conditions. 5. and then click OK. 2. click Web Form. type a name for the content page. right-click D:\Labfiles\Starter\M5\VB \CustomerManagement.vb" Inherits="ContentPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" Runat="Server"> </asp:Content> [Visual C#] <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.

Nested master pages are covered in the next topic.com or by calling +1 800-785-3448. you cannot specify a new ContentPlaceHolder control in a content page. but essentially. Otherwise. because the head element is not available for processing at the server-side. redistribute. It is illegal to reprint. and provided to you by QuickStart Intelligence. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Implementing Master Pages and User Controls 5-11 </asp:Content> Unlike nested master pages. if the head element on the master page has the runat attribute set to server. 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. the setting on the content page is ignored. The title attribute of the Page directive on a content page is also merged with the master page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Question: When you design a Web application by using master pages. a nested master page is when one master page is based on another master page. the content—if any—that is located in the Content control referencing the ContentPlaceHolder control. or resell this content. If a ContentPlaceHolder control is referenced on the content page. the default content—if any—that is specified on the master page is rendered. If a ContentPlaceHolder control is not referenced on the content page. is rendered. Merging Content You can reference a master page and one or more of the ContentPlaceHolder controls on a content page. at the time of merging. by using Content controls. . The Licensed Content is licensed "as-is.

or resell this content. The Licensed Content is licensed "as-is.master.master" CodeFile="ChildMasterPage. and provided to you by QuickStart Intelligence. The parent master page can define the overall layout of the Web site. . [Visual Basic] <%@ Master Language="VB" AutoEventWireup="false" CodeFile="ParentMasterPage.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.com or by calling +1 800-785-3448.master.vb" Inherits="ChildMasterPage" %> This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute.vb" Inherits="ParentMasterPage" %> [Visual C#] <%@ Master Language="C#" AutoEventWireup="true" CodeFile="ParentMasterPage. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Nested master pages reference the parent master by using the MasterPageFile attribute as part of the Master directive. Partners of the large site can then define their child master pages that reference the site master. guarantees or conditions. For example. Please report any unauthorized use of this content to piracy@microsoft.cs" Inherits="ParentMasterPage" %> The following examples show the Master directive for a child master page. a large site can contain an overall master page that defines the look and feel of the site. [Visual Basic] <%@ Master Language="VB" AutoEventWireup="false" MasterPageFile="~/ParentMasterPage. which defines the look and feel for the partner's content. and the child master pages can further define the layout of specific areas of the site.master. Nesting Master Pages You can create nested master pages to create parent master pages and child master pages. The following examples show the Master directive for a parent master page. with one master page referencing another as its master.

When designing a portal or a Web site with many different areas or sections.org/TR/xhtml11/DTD/xhtml11. and then have two or more nested or child master pages that define the layout for specific areas or sections.master.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.master.vb" Inherits="ParentMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.w3. redistribute.cs" Inherits="ChildMasterPage" %> A child master page has the file name extension .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. It is illegal to reprint.1//EN" "http://www. [Visual Basic] <% @ Master Language="VB" AutoEventWireup="false" CodeFile="ParentMasterPage.master. . In addition.</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. guarantees or conditions.org/TR/xhtml11/DTD/xhtml11. The child master page contains content controls that link to content placeholders on the parent master page.QuickStart Intelligence Implementing Master Pages and User Controls 5-13 [Visual C#] <%@ Master Language="C#" AutoEventWireup="true" MasterPageFile="~/ParentMasterPage.master" CodeFile="ChildMasterPage.w3. These placeholders display the content that is supplied by the content pages of the child master pages.1//EN" "http://www. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.cs" Inherits="ParentMasterPage" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. This first two examples display the parent master files. best practice is to have an overall master page that only defines the overall layout.</p> <asp:ContentPlaceHolder ID="MainContent" runat="server" /> </div> </form> </body> </html> [Visual C#] <% @ Master Language="C#" AutoEventWireup="true" CodeFile="ParentMasterPage. Nested Master Page Examples The following examples show a simple nested master page configuration.master. the child master page has its own content placeholders. similar to any master page. The Licensed Content is licensed "as-is.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. or resell this content.

It is illegal to reprint.</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.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. redistribute.</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.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.</p> <asp:ContentPlaceHolder ID="ChildContent1" runat="server" /> </asp:Panel> <asp:Panel runat="server" id="Panel2" backcolor="pink"> <p>This is child master content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is.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. [Visual Basic] <%@ Master Language="VB" MasterPageFile="~/ParentMasterPage. . [Visual Basic] <%@ Page Language="VB" MasterPageFile="~/Child. 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. or resell this content. guarantees or conditions.</p> <asp:ContentPlaceHolder ID="ChildContent1" runat="server" /> </asp:Panel> <asp:Panel runat="server" id="Panel2" backcolor="pink"> <p>This is childmaster content.

. This way you avoid the need to duplicate the code for saving the object on the content pages. discrete page. The content of the individual Content controls is merged into the corresponding ContentPlaceHolder controls on the master page. or resell this content. However. If the Page directive or the pages element contains a MasterPageFile attribute. such as the Init or Load events.NET checks the Page directive and fetches the master page. ASP. by default. both master pages and content pages can use the same set of events. 5. The content page acts as a container for the master page. the content page and master page are compiled. ASP. the two pages act as separate containers for their respective controls. The Licensed Content is licensed "as-is. ASP. Note: Session state will be covered in Module 13.com or by calling +1 800-785-3448. the user request is not directed to the master page. Please report any unauthorized use of this content to piracy@microsoft.NET renders the final merged page to the browser. the master and content pages are combined into a single. The user requests a page by typing the URL of the content page. as the Web server disallows access to .config file. When a user requests a Web page (.NET retrieves the master page. 2. redistribute. It is illegal to reprint.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. ASP. “Managing State in Web Applications. When the two pages are requested for the first time. guarantees or conditions. you can save a specific object to Session state and make it available to all content pages by using a public property. From a programming perspective. and provided to you by QuickStart Intelligence. For example. 4. but you can reference the public members of the master page from the code on the content page. From the user's perspective.aspx).NET reads the Page directive of the content page and the pages element of the web." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You must know the event order to use master pages effectively. The process is as follows: 1. if one is referenced.NET merges the master page content into the control tree of the content page. 3.” This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.master files. The URL of the page is that of the content page. ASP.

or resell this content. a Menu control.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. in that the master page is the container for all server controls rendered to the browser. . depending on the user input on the content page.NET Web Form. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. Note: User controls are covered in the next lesson.QuickStart Intelligence 5-16 Introduction to Web Development with Microsoft® Visual Studio® 2010 You may need to access some controls programmatically from the content page—for example.” 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 also as a container within the content page. Similar to a user control. or an expression. the master page functions as a child element of the content page. This could be a checked menu item that you want to select or clear. and provided to you by QuickStart Intelligence. or a Login control. redistribute. It is illegal to reprint. guarantees or conditions. “Adding User Controls to an ASP. There is one difference though. a SiteMapPath control.

. • Move the existing controls to the Content controls. It is illegal to reprint. if so. and reference the required master page. or resell this content. including html. Your Web Form is now considered a content page. and form. • Lay out the server controls in the Content controls. • Add the MasterPageFile attribute to the Page directive. and provided to you by QuickStart Intelligence. You can use the following tasks to convert a Web Form to a content page: • Create a master page. you can add new pages as content pages. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Remove all of the top-level HTML elements from the Web Form. head. After adding a master page. or add an existing master page. Because Web Forms are similar to the combination of a master page and a content page. ensure that the head element on the master page contains the runat attribute set to server. • Consider moving any existing styles—whether inline or stored in a cascading style sheet (CSS) file—to the master page. you can still add one or more master pages to your Web application at a later stage. The Licensed Content is licensed "as-is. determine if that title should be moved to the master page.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. guarantees or conditions. or convert an existing Web Form in the Web application project to a content page. you will still have full control over how they are laid out within the Content controls. While you cannot place the server controls outside the Content controls. or to the CSS file used by the master page. • Add the required number of Content controls to the content page by referencing the ContentPlaceHolder controls on the referenced master page. it is easy to convert a Web Form into a content page. you need add at least one content page. body. Please report any unauthorized use of this content to piracy@microsoft. redistribute. If you have a title element in the head element.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. To add and use a master page in an existing Web application project.

• Implement an object model that helps you access elements of the master page from content pages that reference the master page. which is helpful when managing large applications that contain thousands of pages. It is illegal to reprint. • Obtain fine-grained control over the layout of a Web page. By using master pages. you can: • Improve the maintenance of Web sites.com or by calling +1 800-785-3448. • Define a portion of a page separately. The content pages are constrained to add or modify content in the allowed placeholders. • Easily create a shared header or footer. because you can control how the content is rendered. • Share the master pages across Web application projects. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.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. and provided to you by QuickStart Intelligence. • Make the same change to every page of your application by changing a single file. all based on an overall layout. which allows you fine-grained control over the layout of each content page. guarantees or conditions. or resell this content. • Optionally override or keep default content from master pages. because you can apply updates in one location that affect all of the content pages on that Web site. Please report any unauthorized use of this content to piracy@microsoft. redistribute. • Nest master pages. The Licensed Content is licensed "as-is. • Define a locked-down layout with editable placeholders. and then reuse it on multiple pages." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .

you will be able to: • Describe user controls. and how to access the properties in a user control. You will also learn how to reference a user control from an ASP. • Explain how to convert a Web Form to a user control. you will learn about user controls. • Explain how to convert a Web Form to a user control. Please report any unauthorized use of this content to piracy@microsoft. Lesson Objectives After completing this lesson. After you create a user control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Web Form A user control is an ASP. In this lesson.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 page that other Web Forms can import as a server control. The Licensed Content is licensed "as-is. other Web pages in the same Web application can use that control. • Describe the advantages and disadvantages of using user controls. and provided to you by QuickStart Intelligence. . and why they are a useful addition to your Web applications. guarantees or conditions. Similar to Web server controls—which are components that run on the server—user controls provide UI and other related functionality. • Explain how to add a user control to a Web Form. or resell this content. redistribute. It is illegal to reprint.NET Web Form.

Similar to a Web Form page. To develop effective ASP. a calendar control that stores the date in a text box. Note: By default. You can create a user control by extending the functionality of an existing server control—for example.NET Web applications with reusability." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. body. For example. a Web server such as IIS 7. . and user controls must be included in a Web Form page to work. User Control Features A user control consists of HTML and code.ascx file extension from being viewed in a Web browser. they do not contain the top-level HTML elements. Similar to a Web Form. When a Web Form uses a user control. This security measure ensures that you do not view the user control as a stand-alone ASP. The Licensed Content is licensed "as-is. user controls are compiled when first requested. redistribute.NET Web applications.com or by calling +1 800-785-3448. User Controls User controls are ASP. or resell this content. or form elements. Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.0 prevents files with the . the user control participates in the event life cycle for the Web Form.NET page. you can group several controls together to gather information about a user's previous work experience. Unlike Web Form pages. It is illegal to reprint. such as the html.ascx file extension. but because user controls are used by Web Forms. guarantees or conditions. User controls offer you the option to partition and reuse common UI functionality across ASP.NET pages with an . User controls can also consist of several elements that work and interact together to get a task done. you must know how to utilize user controls.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. and provided to you by QuickStart Intelligence. and add logic to them by using code-behind classes. and then stored in server memory to reduce the response time for subsequent requests. user controls cannot be requested independently. you can author these controls by using Visual Studio 2010.

the Control directive does not support the Trace attribute. The following table describes the specificities of components and control. and you can write code to implement the functionality of the user control. “Troubleshooting Microsoft ASP. For more information about tracing. Web server controls.aspx page that calls the user control. .” User Controls.ascx. If you choose to place the code for the user control in a separate code-behind file. if you want to enable tracing for the user control. which is the equivalent of the Page directive that is contained in a Web Form. it has its own page logic. However. such as calendar. [Visual Basic] <%@ Control Language="VB" AutoEventWireup="false" CodeFile="WebUserControl. see Module 7. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you must add the Trace attribute to the Page directive for the . and specific controls. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET page.QuickStart Intelligence Implementing Master Pages and User Controls 5-21 Because a user control is an ASP. then the Control directive references the code-behind file. redistribute. which are a special type of component that provides a user interface. it does not have a user interface. The following examples contain the Control directive for a user control named WebUserControl. Therefore.ascx. For example. Web server control Web server controls include form-type controls such as button and text box. a user control must have a user interface at both design time and run time. Web Server Controls. You can also create custom. Components and controls Description Component A component—also called a class library in Visual Studio 2010—provides logic only. or resell this content.cs" Inherits="WebUserControl" %> Note: The Control directive supports many of the same attributes as the Page directive. a user control handles its postback event in its Page_Load event handler. compiled Web server controls.com or by calling +1 800-785-3448. You can include only one Control directive per .NET Web Applications. User Controls Code-Behind Files User controls contain the Control directive. and components.vb" Inherits="WebUserControl" %> [Visual C#] <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl. and provided to you by QuickStart Intelligence. User control Unlike Web server controls. guarantees or conditions. and Components You must be able to distinguish between user controls.ascx file. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.

com or by calling +1 800-785-3448. . User controls are typically used for creating small units of layout and code that are used repeatedly within a Web application. User controls provide separate variable namespaces. 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. guarantees or conditions. or repeat blocks of code in a Web application project or Web site project. validation. because if it is generic. It is illegal to reprint. or resell this content. For example. toolbars. you can create headers and navigation bars. User controls are self-contained. which means that none of the methods and properties of the user control conflict with any existing methods or properties of the hosting page. a user control that is written in Microsoft Visual C#® can be used on a Web Form that is written in Microsoft Visual Basic®. Disadvantages of User Controls User controls come with a few disadvantages when you develop a Web application: • User interface and code can be duplicated. 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. This includes logon. redistribute. Please report any unauthorized use of this content to piracy@microsoft. Advantages of User Controls User controls have numerous functions. navigation. and similar functionality. it is difficult to maintain the UI and code. The Licensed Content is licensed "as-is.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. User controls also offer the following advantages when you develop a Web application: • User controls are self-contained." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. for example. and can be written in a programming language that is different from the language that is used for the main hosting page. • User controls can be used multiple times.NET Web applications. When sharing a user control between Web applications. can be used multiple times. • User controls can be shared in a Web application. You can share a single user control among all the pages in a Web application. and provided to you by QuickStart Intelligence.

If the code for the user control is generic or is not logically abstract." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you can create a Web custom control. Web custom controls are more difficult to create than user controls. To create a Web custom control. you cannot create Web custom controls by using Visual Studio 2010.aspx pages in one Web application cannot host a user control from another Web application. you create a class that derives from the Control or WebControl class. or resell this content. However. redistribute. Please report any unauthorized use of this content to piracy@microsoft. . To use a user control in multiple Web applications. It is illegal to reprint. all development is done through code only. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. unlike user controls. This is because.QuickStart Intelligence Implementing Master Pages and User Controls 5-23 a user control. which acts like a shareable user control that you can add to the Toolbox in a Web application. To share controls with multiple Web applications. you must copy the user control to the virtual root folder of each Web application. you need to rewrite or modify the code for each applied usage. the . unless you precompile the Web application. Advantages and Disadvantages of Using User Controls • The code-behind file is visible to anyone who has access to the deployed Web application. Sharing User Controls You can share a single user control with all the pages in a Web application. guarantees or conditions. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448.

Please report any unauthorized use of this content to piracy@microsoft. and then change the file extension from . change the type from which the class inherits. body. sometimes. and form elements. it is better to create user controls after development has started. you can easily convert a Web Form to a user control.ascx. you must also change the file extension of this page to . see "Directive Syntax" in the Visual Studio 2010 documentation. The Licensed Content is licensed "as-is.UI. because you can then identify the bits and pieces in your Web Forms that are duplicated. guarantees or conditions. AutoEventWireup (if present).cs or . you can still add one or more user controls at a later stage. In addition. • Add a ClassName attribute to the Control directive." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. from System. or resell this content. Converting an Existing Web Form to a User Control You can easily modify a Web Form to convert it to a user control. CodeFile. Your Web Form is a user control.UserControl. • Rename the file to a name that reflects its purpose.ascx. redistribute.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. with the exception of Language.UI. The ClassName attribute enables the user control to be strongly typed when you add it to a page. and provided to you by QuickStart Intelligence.aspx to . Because Web Forms are similar to user controls. • Change the existing Page directive to a Control directive.Web. Remove all directive attributes. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448.Page to System. In fact.Web.vb. .ascx. Note: For more information about the attributes that are supported by the Page and Control directives. including the html. and Inherits. Note: If the Web Form contains a code-behind file. The following is the process for converting a Web Form to a content page: • Remove all top-level HTML elements from the Web Form. head.

redistribute. Remove all attributes of the Control directive.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. Open the code-behind file. perform the following steps: a. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. CodeFile. 4. change the CodeFile attribute to point to the renamed code-behind file.QuickStart Intelligence Implementing Master Pages and User Controls • 5-25 Add properties to the user control to allow controlled access to the private data—if any—that is contained in the user control.cs. Remove the html. guarantees or conditions. body. 5.ascx.aspx file so that the file name extension is . c. d. or resell this content. The Licensed Content is licensed "as-is. 3. and form elements from the page. It is illegal to reprint. b. Include a className attribute in the Control directive. AutoEventWireup (if present). In the Control directive.ascx. . 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 . and change the class from which it inherits from Page to UserControl. These properties work the same way as they do for a Web Form. In the . Change the Page directive to a Control directive. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.ascx file. 2. Rename the code-behind file with either of the file name extensions .vb or . depending on which programming language the code-behind file is in.ascx. and Inherits. This allows the user control to be strongly typed when it is added to a page. except Language.

c.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. click Open Project. Log on to 10267A-GEN-DEV as Student.sln.aspx Web Form.aspx. guarantees or conditions. and provided to you by QuickStart Intelligence. b. Open the InsertCustomer. The Licensed Content is licensed "as-is. point to All Programs.sln or D:\Demofiles\M5\CS\CustomerManagement. In Solution Explorer. and then click Open. Pa$$w0rd. On the Start menu of 10267A-GEN-DEV. Please report any unauthorized use of this content to piracy@microsoft.vb" Inherits="InsertCustomer" %> [Visual C#] <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. in the File name box. right-click InsertCustomer. . 3.aspx. locate the Page directive. Demonstration Steps 1. and then change it to a Control directive. and then click Microsoft Visual Studio 2010. On the File menu of Visual Studio 2010.cs" Inherits="InsertCustomer" %> a.vb" Inherits="InsertCustomer" %> This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint. [Visual Basic] <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer. and change its Page directive to a Control directive. you will see how to convert a Web Form into a user control.com or by calling +1 800-785-3448. a. and then click Open. type either D:\Demofiles\M5\VB\CustomerManagement. with the password. In the Open Project dialog box. or resell this content. b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 2. Open the CustomerManagement solution from either the D:\Demofiles\M5\VB or D:\Demofiles\M5\CS folder.aspx window. [Visual Basic] <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer.aspx. In the InsertCustomer.aspx. redistribute. click Microsoft Visual Studio 2010.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. such as the DOCTYPE. Note: After removing all the top-level elements.cs" Inherits="InsertCustomer" ClassName="InsertCustomer" %> • In the InsertCustomer.com or by calling +1 800-785-3448.aspx. . redistribute. link. and form elements. head. remove all the top-level HTML elements.aspx window. body. [Visual Basic] <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer.aspx. html.vb" Inherits="InsertCustomer" ClassName="InsertCustomer" %> [Visual C#] <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. It is illegal to reprint.aspx window. add the following code at the end of the Control directive.aspx. [Visual Basic] <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer. Both the opening and closing tags for each element—if they exist—must be removed. Note: You should take care not to delete the div element and the content within the form element. The Licensed Content is licensed "as-is. Add a ClassName property with a value of InsertCustomer to the Control directive. and provided to you by QuickStart Intelligence. In the InsertCustomer. Please report any unauthorized use of this content to piracy@microsoft.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.aspx. title. guarantees or conditions.QuickStart Intelligence Implementing Master Pages and User Controls 5-27 [Visual C#] <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer.cs" Inherits="InsertCustomer" %> 4. or resell this content. you will get the following code. ClassName="InsertCustomer" 5.

guarantees or conditions. . or resell this content.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.com or by calling +1 800-785-3448.<asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel" /> </div> [Visual C#] <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. It is illegal to reprint. redistribute. Please report any unauthorized use of this content to piracy@microsoft.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx.

redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft.<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. It is illegal to reprint. and provided to you by QuickStart Intelligence. .com or by calling +1 800-785-3448. or resell this content. The Licensed Content is licensed "as-is.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.

vb or InsertCustomer.aspx to InsertCustomer. change the file name to InsertCustomer.UserControl. Move the content from the Page_LoadComplete event method.UI.EventArgs) Handles Me.ascx." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx.Page to System. In Solution Explorer. and then press ENTER.Web.Web.Web.cs user control code-behind file. In Solution Explorer.cs. Open either the InsertCustomer. [Visual Basic] Protected Sub Page_Load(ByVal sender As Object.UserControl [Visual C#] public partial class InsertCustomer : System. .ascx. [Visual Basic] Partial Class InsertCustomer Inherits System.ascx.Web.UserControl [Visual C#] public partial class InsertCustomer : System. click Rename. select and right-click the following code.UserControl 9.vb or InsertCustomer. Please report any unauthorized use of this content to piracy@microsoft.Web. b.UI.UI. In the Microsoft Visual Studio message box. a.Web. locate the InsertCustomer class. In the InsertCustomer.ascx.vb or InsertCustomer.Web. and change its base class from System. in the Page_LoadComplete event method. on the File menu. Save the InsertCustomer. // Populate the UI controls populateUI().ascx. guarantees or conditions. [Visual Basic] ' Populate the UI controls This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.UI.Page to System.Load ' Instantiate Customer instantiateCustomerObject() ' Populate the UI controls populateUI() End Sub [Visual C#] protected void Page_Load(object sender. In the CustomerManagement – Microsoft Visual Studio (Administrator) window. click Yes. and append it to the Page_Load event method.Web.QuickStart Intelligence 5-30 Introduction to Web Development with Microsoft® Visual Studio® 2010 </div> 6.ascx.UI. or resell this content.UserControl.ascx.ascx. right-click either InsertCustomer. } • In the InsertCustomer.vb or InsertCustomer.UI. b. The Licensed Content is licensed "as-is. 8.UserControl a.UI. click Save InsertCustomer.cs code window. [Visual Basic] Partial Class InsertCustomer Inherits System.com or by calling +1 800-785-3448.aspx Web Form. and then click Cut.ascx. ByVal e As System.ascx. and then click Open. It is illegal to reprint. • 7. Rename the Web Form from InsertCustomer. and change its property from System.aspx. EventArgs e) { // Instantiate Customer instantiateCustomerObject(). and provided to you by QuickStart Intelligence. right-click InsertCustomer.UI.cs code window. redistribute.

on the File menu. guarantees or conditions. In the InsertCustomer. click Save InsertCustomer.QuickStart Intelligence Implementing Master Pages and User Controls 5-31 populateUI() [Visual C#] // Populate the UI controls populateUI(). Save and close the user control code-behind file. In the CustomerManagement – Microsoft Visual Studio (Administrator) window click Close button. • In the CustomerManagement – Microsoft Visual Studio (Administrator) window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute.com or by calling +1 800-785-3448. b.ascx. 11. or resell this content. . In the InsertCustomer. The Licensed Content is licensed "as-is.ascx window. • In the InsertCustomer. EventArgs e) { // Instantiate Customer instantiateCustomerObject(). d. click Build Solution.vb or InsertCustomer.EventArgs) Handles Me. and provided to you by QuickStart Intelligence. c.ascx.ascx. click the Close button.cs. click the Close button. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft.cs code window.ascx. delete the Page_LoadComplete event method.ascx. on the Build menu. a.cs code window.Load ' Instantiate Customer instantiateCustomerObject() ' Populate the UI controls populateUI() End Sub [Visual C#] protected void Page_Load(object sender. // Populate the UI controls populateUI().ascx. Build the solution. [Visual Basic] Protected Sub Page_Load(ByVal sender As Object. In the CustomerManagement – Microsoft Visual Studio (Administrator) window. It is illegal to reprint. append the copied code to the Page_Load event method.ascx. } 10.vb or InsertCustomer.ascx. 12.vb or InsertCustomer. ByVal e As System. In the InsertCustomer.vb or Save InsertCustomer.cs code window.

The TagName attribute is the unique name for the user control. and differentiates between multiple user controls that have the same name. Including User Controls You include a user control in an ASP. redistribute. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 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.com or by calling +1 800-785-3448. When a user requests the Web Form on which the user control has been placed. The Src attribute is the virtual path to the user control file. <%@ Register src="WebUserControl. The Licensed Content is licensed "as-is. <uc1:WebUserControl ID="WebUserControl1" runat="server" /> Note: You can drag a user control from Solution Explorer onto a Web Form. Visual Studio 2010 automatically adds the Register directive and the tag for the user control to the page markup.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. . When you drag a user control onto a Web Form in Design View. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.NET Web Form. the runtime compiles the user control file and makes it available to the page. Placing the User Control in a Web Form After you register the user control by using the Register directive. The page that references the user control is called a host. The following code adds a user control to a Web Form.NET Web Form by using the Register directive." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or resell this content. and the control is included in that host.ascx" tagname="WebUserControl" tagprefix="uc1" %> The TagPrefix attribute determines a unique namespace for the user control. The following code illustrates this.

Please report any unauthorized use of this content to piracy@microsoft. in the Properties window. The following example sets the Name property of the user control to the value Gregory Weber. just as you write any other property.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or can be accessed from code. . If the public property is read-write.com or by calling +1 800-785-3448.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. The user control is in the file Spinner. [Visual Basic] WebUserControl1. and provided to you by QuickStart Intelligence. or resell this content. the control is registered to use the prefix uc. and the tag name Spinner. redistribute. check if the properties need to be set to initialize the user control. User Control Example The following are additional examples that show an ASP.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.Name = "Gregory Weber".Name = "Gregory Weber" [Visual C#] WebUserControl1. [Visual Basic] <%@ Page Language="VB" %> <%@ Register TagPrefix="uc" TagName="Spinner" Src="~\Controls\Spinner. The properties can be set declaratively in the markup. On the page. and Src attributes? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.ascx. in the Controls folder. you can also write the values in your Web Form. The user control properties MinValue and MaxValue are set declaratively. guarantees or conditions. It is illegal to reprint.NET Web page that contains a user control. TagName. The Licensed Content is licensed "as-is.

It is illegal to reprint. • Convert a Web Form into a user control.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. you will be able to: • Add and apply a master page in a Web application. you will implement master pages and user controls in an ASP. Please report any unauthorized use of this content to piracy@microsoft. If you are using Visual C# as your programming language. redistribute. • Create a content page. • Insert a user control on the content page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Before you begin the lab. Objectives After completing this lab. Lab Setup For this lab.NET Web project. • Add navigation to the master page. 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.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. In addition. you will add navigation to the master page and convert a Web Form to a user control. Introduction In this lab. . you will use the available virtual machine environment. refer to the steps provided in Section 1 of the lab document. guarantees or conditions. refer to the steps provided in Section 2 of the lab document. or resell this content. you must: • Start the 10267A-GEN-DEV virtual machine. • Convert a Web Form to a content page.

To do this.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Implementing Master Pages and User Controls 5-35 Lab Scenario You are a developer at Contoso. guarantees or conditions. and the developer has created a sitemap XML document. You can use the code and the document for adding navigation to the master page. and create a new content page with a user control. The organization has decided to modify their Web site to provide consistent user experience to all customers. move the content from the content page to the master page. you need to add a master page and convert an existing Web Form into a user control for reuse. In addition. . It is illegal to reprint. Your organization uses a Web site to manage its customer information. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you need to convert a Web Form into a content page. A senior developer has already created some of the code to add navigation to the Web site. and provided to you by QuickStart Intelligence. which is a large organization with a global customer base. Ltd. In addition. redistribute. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is. you will need to add navigation to the master page. or resell this content.

<body class="template"> • In the Site.  Task 1: Add a master page to an existing Web site • Log on to 10267A-GEN-DEV as Student. change the id property of the form element to MainForm. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M5\VB folder.master window. <div class="content"> <asp:ContentPlaceHolder id="MainContentPlaceHolder" runat="server"> </asp:ContentPlaceHolder> </div> • Save the master page. redistribute. guarantees or conditions. Pa$$w0rd.master window. • Open Microsoft Visual Studio 2010. and provided to you by QuickStart Intelligence. <link href="~/Styles/Site.master window. with the password. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. <head runat="server" id="MainHead"> • In the Site. set the value of the title element to Contoso Customer Management by using the following code. Add a master page to an existing Web site. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. add an id property to the head element by using the following code.css" rel="stylesheet" type="text/css" /> • In the Site.  Task 2: Initialize the style controls and elements on the master page • In the Site. to the CustomerManagement Web site.master window. <div class="content"> • In the Site. Define a ContentPlaceHolder control on the master page.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.master.master window. 3. <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> • Change the id property of the ContentPlaceHolder control within the div element to MainContentPlaceHolder. • Add a new master page named Site. relative to the root folder.css file in the Site. add a Class property to the body element by using the following markup.com or by calling +1 800-785-3448. Initialize the style controls and elements on the master page.master Web Form. It is illegal to reprint. add a Class property to the div element by using the following markup. by placing the following markup next to the closing tag of the title element. <form id="MainForm" runat="server"> • Reference the Site. <title>Contoso Customer Management</title>  Task 3: Define a ContentPlaceHolder control on the master page • Remove the ContentPlaceHolder from the head element. 2. .

and provided to you by QuickStart Intelligence. and defined a ContentPlaceHolder control on the master page. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.master. redistribute. or resell this content. It is illegal to reprint. you will have created a master page named Site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. . guarantees or conditions.QuickStart Intelligence Implementing Master Pages and User Controls 5-37 Results: After completing this exercise. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

• Format the Default.com or by calling +1 800-785-3448. Create a content page and insert a user control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.master.aspx. by pressing CTRL+K.master master page.w3.vb" Inherits="_Default" MasterPageFile="~/Site.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat"server"> </form> </body> </html> • In the Default. <div class="appTitle"> <asp:Literal ID="AppTitleLiteral" runat="server" Text="Customer Management"></asp:Literal> </div> • Format the Site. add a MasterPageFile property.aspx Web Form. . guarantees or conditions.dtd"> <html xmlns="http://www.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. Please report any unauthorized use of this content to piracy@microsoft.0 Transitional//EN" "http://www. Convert the default Web Form into a content page. • Save the changes to the Site.  Task 1: Convert the default Web Form into a content page • Open the Default. move the following code and it after the opening tag of the form element on the 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. redistribute. • In the Default. 2. • Save and close the Default. <asp:Content ID="MainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> </asp:Content> • In the Default. It is illegal to reprint. in the Page directive. and provided to you by QuickStart Intelligence.aspx Web Form.w3. by using the following code. and then pressing CTRL+D. Convert the Web Form into a user control. or resell this content. 3. 4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. add a server-side Content control. The Licensed Content is licensed "as-is.master master page. by pressing CTRL+K. Add navigation to the master page. and then pressing CTRL+D.master master page.aspx window.org/1999/xhtml"> <head runat="server"> <title></title> <link href="Styles/Site.aspx Web Form." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx window. with a value of ~/Site.aspx window.org/TR/xhtml1/DTD/xhtml1-transitional. <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.

wrapped in a div element with a class attribute value of siteMapPath. with a class attribute value of menu. . or resell this content. by using the Manage Styles window. The SiteMapDataSource control should not show the starting node. <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.sitemap site map file to the project. 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. Add the new div element below the existing div element with a class attribute value of appTitle. • Add the D:\Labfiles\Starter\M5\web. and provided to you by QuickStart Intelligence. • Modify the div. DataSourceID="MainSiteMapDataSource" • Add the following child elements to the Menu control. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. after the closing tag of the div element. The menu style must have the following definition: • • Category: Position • position: relative • z-index: 1 • Top: 62px Add a siteMapPath style. by setting the StaticEnableDefaultPopOutImage attribute. <div class="siteMapPath"> <asp:SiteMapPath ID="MainSiteMapPath" runat="server" /> </div> • Add a menu to the master page by adding a Menu control named MainMenu. StaticEnableDefaultPopOutImage="false" • Get the items for the Menu control from the MainSiteMapDataSource data source control by applying the DataSourceID attribute. Add the new div element below the existing div element with a class attribute value of siteMapPath. redistribute. by using the Manage Styles window. <div class="menu"> <asp:Menu ID="MainMenu" runat="server"> </asp:Menu> </div> • Make the menu layout horizontal by applying the Orientation attribute. guarantees or conditions. The Licensed Content is licensed "as-is. <asp:SiteMapDataSource ID="MainSiteMapDataSource" runat="server" ShowStartingNode="false" /> • Format the Site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.menu style.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. It is illegal to reprint. by placing them between the opening and closing Menu tags. wrapped in a div element with a class attribute value of menu.master master page. Orientation="Horizontal" • Ensure that the built-in image that indicates if a static menu item has a child menu is not displayed.

type 5px Save all modified files and run the Site. link.aspx. head. • Format the document.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.ascx.com or by calling +1 800-785-3448. redistribute.vb" Inherits="Customer" ClassName="Customer" %> • Remove all the top-level HTML elements.vb" Inherits="Customer" ClassName="Customer" %> • Change the CodeFile property value from InsertCustomer. <%@ Control Language="VB" AutoEventWireup="false" CodeFile="Customer.aspx.aspx Web Form. <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer. in the bottom box.aspx. html.vb to Customer. body.QuickStart Intelligence 5-40 Introduction to Web Development with Microsoft® Visual Studio® 2010 • • Selector: div.aspx window.css • Category: Position • Position: fixed • Top: 42px • Category: Box • Padding section: Remove the selection from the Same for all check box. <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer. Please report any unauthorized use of this content to piracy@microsoft. The Licensed Content is licensed "as-is.  Task 3: Convert the Web Form into a user control • Open the InsertCustomer. and change its Page directive to a Control directive. or resell this content.vb. you can view the following markup in the InsertCustomer.aspx. title.aspx. <%@ Control Language="VB" AutoEventWireup="false" CodeFile="InsertCustomer.vb" Inherits="InsertCustomer" %> • Add a ClassName property with a value of Customer to the Control directive. .vb" Inherits="InsertCustomer" ClassName="Customer" %> • Change the Inherits property value from InsertCustomer to Customer.master master page. and provided to you by QuickStart Intelligence. and form elements. such as the DOCTYPE. <%@ Control Language="VB" AutoEventWireup="false" CodeFile="Customer. It is illegal to reprint.aspx.siteMapPath • Define in: Styles/Site. Note: After removing all top-level HTML elements. guarantees or conditions.

redistribute.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. The Licensed Content is licensed "as-is. or resell this content. and provided to you by QuickStart Intelligence. . guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.

UI. and append it to the Page_Load event method. Please report any unauthorized use of this content to piracy@microsoft. ByVal e As System.<asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel" /> </div> </div> • Save the InsertCustomer. guarantees or conditions.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.Page to System.UI.ascx. • Open the Customer. • Change the Web Form name from InsertCustomer. and change its base class from System.Web. and provided to you by QuickStart Intelligence.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.aspx to Customer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint.UserControl • Move the content from the Page_LoadComplete event method.EventArgs) Handles Me.Web.com or by calling +1 800-785-3448. redistribute.UserControl. .vb user control code-behind file.aspx Web Form.ascx. Partial Class InsertCustomer Inherits System. change the class name to Customer.Web. The Licensed Content is licensed "as-is.UI. or resell this content. Protected Sub Page_Load(ByVal sender As Object.

• Open the InsertCustomer.aspx. It is illegal to reprint.  Task 5: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine.vb user control. • 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. Note: Notice that the new user control displays on the InsertCustomer Web Form. with a code-behind file based on the Site. guarantees or conditions.LoadComplete End Sub • Save the modified files. • Run the CustomerManagement Web application.ascx user control to the MainContentPlaceHolder control. by clicking New on the Customers menu. .  Task 4: Create a content page and insert a user control • Add a new content page named InsertCustomer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. added navigation to the master page. In addition. you should have created a content page and inserted a user control. Please report any unauthorized use of this content to piracy@microsoft. • Verify the Contoso Customer Management Web site.master master page. ''' <summary> ''' Populates UI controls ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks<>/remarks> Protected Sub Page_LoadComplete(ByVal sender As Object. Results: After completing this exercise. and provided to you by QuickStart Intelligence.EventArgs) Handles Me. and drag the Customer. redistribute. The Licensed Content is licensed "as-is. and then converted the Web Form into a user control.aspx content page in the Design view. you will have converted the default Web Form into a content page. or resell this content.com or by calling +1 800-785-3448. and close the Customer.ascx.QuickStart Intelligence Implementing Master Pages and User Controls • 5-43 Remove the Page_LoadComplete event method. ByVal e As System.

with the password.master window.master. redistribute. <head runat="server" id="MainHead"> • In the Site. The Licensed Content is licensed "as-is.master window. guarantees or conditions. It is illegal to reprint. <div class="content"> <asp:ContentPlaceHolder id="MainContentPlaceHolder" runat="server"> </asp:ContentPlaceHolder> </div> • Save the master page.com or by calling +1 800-785-3448. add a Class property to the body element by using the following markup. Please report any unauthorized use of this content to piracy@microsoft. to the CustomerManagement Web site. 2. by placing the following markup next to the closing tag of the title element. add an id property to the head element by using the following code.master window. and provided to you by QuickStart Intelligence. <div class="content"> • In the Site. or resell this content. add a Class property to the div element by using the following markup. Add a master page to an existing Web site. • Open Microsoft Visual Studio 2010. .  Task 2: Initialize the style controls and elements on the master page • In the Site. relative to the root folder. <title>Contoso Customer Management</title>  Task 3: Define a ContentPlaceHolder control on the master page • Remove the ContentPlaceHolder from the head element. <form id="MainForm" runat="server"> • Reference the Site.master window. Initialize the style controls and elements on the master page.master Web Form. change the id property of the form element to MainForm.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. Define a ContentPlaceHolder control on the master page. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M5\CS folder. set the value of the title element to Contoso Customer Management by using the following code.  Task 1: Add a master page to an existing Web site • Log on to 10267A-GEN-DEV as Student. <body class="template"> • In the Site. 3. <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> • Change the id property of the ContentPlaceHolder control within the div element to MainContentPlaceHolder. Pa$$w0rd. <link href="~/Styles/Site.css file in the Site.css" rel="stylesheet" type="text/css" /> • In the Site.master window. • Add a new master page named Site.

The Licensed Content is licensed "as-is.QuickStart Intelligence Implementing Master Pages and User Controls 5-45 Results: After completing this exercise. It is illegal to reprint. guarantees or conditions.master." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. you will have created a master page named Site. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. and provided to you by QuickStart Intelligence. . and defined a ContentPlaceHolder control on the master page. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.

master master page. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. • Format the Default. by pressing CTRL+K.master master page. 3.master"%> • Remove the top-level HTML elements from the Default Web Form. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx Web Form. Create a content page and insert a user control. Convert the default Web Form into a content page. • Save the changes to the Site. 2. • Save and close the Default. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. by using the following code.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. and then pressing CTRL+D.aspx Web Form. .cs" Inherits="_Default" MasterPageFile="~/Site.0 Transitional//EN" "http://www.w3. It is illegal to reprint.aspx. • In the Default. add a server-side Content control.org/1999/xhtml"> <head runat="server"> <title></title> <link href="Styles/Site. add a MasterPageFile property with a value of ~/Site.com or by calling +1 800-785-3448. redistribute. <div class="appTitle"> <asp:Literal ID="AppTitleLiteral" runat="server" Text="Customer Management"></asp:Literal> </div> • Format the Site. guarantees or conditions.master master page.w3.  Task 1: Convert the default Web Form into a content page • Open the Default.aspx window.dtd"> <html xmlns="http://www." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.master. Please report any unauthorized use of this content to piracy@microsoft. move the following code and place the code after the opening tag of the form element on the Site.aspx window. in the Page directive.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat"server"> </form> </body> </html> • In the Default.aspx Web Form.org/TR/xhtml1/DTD/xhtml1-transitional. <asp:Content ID="MainContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server"> </asp:Content> • In the Default. and then pressing CTRL+D.aspx window. Add navigation to the master page. Convert the Web Form into a user control 4. by pressing CTRL+K. Note: You should take care not to delete the div element and the content within the form element.

The Licensed Content is licensed "as-is. <div class="siteMapPath"> <asp:SiteMapPath ID="MainSiteMapPath" runat="server" /> </div> • Add a menu to the master page by adding a Menu control named MainMenu. StaticEnableDefaultPopOutImage="false" • Get the items for the Menu control from the MainSiteMapDataSource data source control by applying the DataSourceID attribute. The menu style must have the following definition: • Selector: div. with a class attribute value of menu.sitemap site map file to the project. <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. . by applying the Orientation attribute. DataSourceID="MainSiteMapDataSource" • Add the following child elements to the Menu control.com or by calling +1 800-785-3448. <div class="menu"> <asp:Menu ID="MainMenu" runat="server"> </asp:Menu> </div> • Make the menu layout horizontal. redistribute. Orientation="Horizontal" • Ensure that the built-in image that indicates if a static menu item has a child menu is not displayed.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 menu. Please report any unauthorized use of this content to piracy@microsoft. after the closing tag of the div element. by placing them between the opening and closing Menu tags. or resell this content.menu style. and provided to you by QuickStart Intelligence. by setting the StaticEnableDefaultPopOutImage attribute. • Add the D:\Labfiles\Starter\M5\web. guarantees or conditions. The SiteMapDataSource control should not show the starting node. <asp:SiteMapDataSource ID="MainSiteMapDataSource" runat="server" ShowStartingNode="false" /> • Format the Site. Add the new div element below the existing div element with a class attribute value of siteMapPath.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. Add the new div element below the existing div element with a class attribute value of appTitle. by using the Manage Styles window. It is illegal to reprint. • Modify the div. wrapped in a div element with a class attribute value of siteMapPath.master master page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

html.css • Category: Position • Position: fixed • Top: 42px • Category: Box • Padding section: Remove the selection from the Same for all check box.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. by using the Manage Styles window.siteMapPath • Define in: Styles/Site.master master page. and form elements. The Licensed Content is licensed "as-is. in the bottom box.cs to Customer. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Customer.  Task 3: Convert the Web Form into a user control • Open the InsertCustomer. The siteMapPath style must have the following definition: • Selector: div.QuickStart Intelligence 5-48 Introduction to Web Development with Microsoft® Visual Studio® 2010 • • Add a siteMapPath style. guarantees or conditions.com or by calling +1 800-785-3448.cs" Inherits="Customer" ClassName="Customer" %> • Remove all the top-level HTML elements. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="Customer.aspx Web Form.cs" Inherits="InsertCustomer" ClassName="Customer" %> • Change the Inherits property value from InsertCustomer to Customer.aspx. you can view the following markup in the InsertCustomer. • Format the document.aspx window.aspx.cs" Inherits="InsertCustomer" %> • Add a ClassName property with a value of Customer to the Control directive. title. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. and provided to you by QuickStart Intelligence. and run the Site. and change its Page directive to a Control directive. type 5px Save all modified files. <%@ Control Language="C#" AutoEventWireup="true" CodeFile="InsertCustomer. . head. link.cs.aspx." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note: After removing all top-level HTML elements.aspx. such as the DOCTYPE.cs" Inherits="Customer" ClassName="Customer" %> • Change the CodeFile property value from InsertCustomer. It is illegal to reprint.aspx.ascx. redistribute.aspx. body. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.

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. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. guarantees or conditions. .com or by calling +1 800-785-3448. redistribute. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.

.UserControl • Move the content from the Page_LoadComplete event method.UI. or resell this content. and provided to you by QuickStart Intelligence. change the class name to Customer. public partial class Customer : System.aspx Web Form.Page to System.ascx. Please report any unauthorized use of this content to piracy@microsoft.<asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel" OnClick="CustomerCancelButton_Click" /> </div> </div> • Save the InsertCustomer.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.ascx. • Change the Web Form name from InsertCustomer.Web. The Licensed Content is licensed "as-is. guarantees or conditions.aspx to Customer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.cs user control code-behind file.UI. • Open the Customer. and change its base class from System. It is illegal to reprint.UI. EventArgs e) { // Instantiate Customer This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute.Web. and append it to the Page_Load event method. protected void Page_Load(object sender.Web.com or by calling +1 800-785-3448.UserControl.

with a code-behind file based on the Site. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft.ascx user control to the MainContentPlaceHolder control. you will have created a content page and inserted a user control. Remove the Page_LoadComplete event method.  Task 5: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. redistribute. • Revert the changes made to the 10267A-GEN-DEV virtual machine.QuickStart Intelligence Implementing Master Pages and User Controls } • 5-51 instantiateCustomerObject()." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . • Open the InsertCustomer. • Run the CustomerManagement Web application. added navigation to the master page. /// <summary> /// Populates UI controls /// </summary> /// <param name="sender">>/param> /// <param name="e"></param> protected void Page__LoadComplete(object sender. Note: Notice that the new user control displays on the InsertCustomer Web Form.ascx. EventArgs e) { } • Save the modified files and close the Customer. Results: After completing this exercise. you will have converted the default Web Form to a content page. and drag the Customer.master master page.cs user control.aspx. and then converted the Web Form into a user control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.aspx content page in the Design view. and provided to you by QuickStart Intelligence. • Verify the Contoso Customer Management Web site by clicking New on the Customers menu.com or by calling +1 800-785-3448. In addition. or resell this content.  Task 4: Create a content page and insert a user control • Add a new content page named InsertCustomer. guarantees or conditions. It is illegal to reprint. // Populate the UI controls populateUI().

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET application? 2. The Licensed Content is licensed "as-is. Why did you convert a Web Form into an ASP. or resell this content. How will you programmatically attach master pages to an ASP. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. It is illegal to reprint.com or by calling +1 800-785-3448.NET user control in the lab? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. .QuickStart Intelligence 5-52 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Review 1. redistribute.

redistribute. and the other two being nested master pages. Please report any unauthorized use of this content to piracy@microsoft. What are the disadvantages of user controls? Real-World Issues and Scenarios 1. or resell this content. What is the file extension of a master page? 2." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You want to create a control that other developers can make changes to without recompiling the code.QuickStart Intelligence Implementing Master Pages and User Controls 5-53 Module Review and Takeaways Review Questions and Answers 1. • Apply master pages in the web. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448. guarantees or conditions. and provided to you by QuickStart Intelligence. . What is the file extension of a user control? 4. This makes it easier to replace the master pages at a later stage. • Use master pages whenever you have a layout that will be used for two or more pages. based on the overall master page. Which attribute overrides any master page setting specified in the web. based on the overall master page. or in specific areas of the Web site. You want to create an overall master page. Best Practices Mention some best practices in the context of your own business situations. if it is to be used with all or nearly all the pages on the Web site. 2. What is the easiest way to implement this? You could create three master pages. with the first being the overall master page. What is the easiest way to implement this? You should implement the controls as a user control. but you want to dictate two different types of layouts.config file? 3.config file. It is illegal to reprint.

. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. It is illegal to reprint. guarantees or conditions. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.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. or resell this content.

or resell this content. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.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. The Licensed Content is licensed "as-is.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. . Please report any unauthorized use of this content to piracy@microsoft. redistribute. It is illegal to reprint.com or by calling +1 800-785-3448.

NET. You can apply these controls to an ASP. These layers are used by other parts or layers of an application. To create this check. There are also concerns about how input validation is performed in the different layers of an application. This module discusses user input. you must make sure that input is validated wherever input is accepted. break your Web application. you need to link at least one input validation control to the input control. The Licensed Content is licensed "as-is. you reduce the traffic of data between the client and server. . and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or format of the input that you expect to receive from the user. or resell this content. you must check the input against the value. there are many other types of input that must be validated. and this means that input validation might have already been performed. There is more to a secure application than validating user input. It is illegal to reprint. save server resources. Please report any unauthorized use of this content to piracy@microsoft. redistribute. When you use client-side validation instead of server-side validation.NET Web Form to perform both client-side and server-side input validation. and then set the criteria of the validation control to test for your requirements. To verify that the user input meets your requirements. and improve the response time of your Web application. you have expectations or requirements about the type of input that the user will enter into that control. which generally means the User Interface (UI) layer. range. and with regards to input validation.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. guarantees or conditions. but the business logic layer (BLL) and the data access layer (DAL) also require input validation.com or by calling +1 800-785-3448. Various input validation controls are available in Microsoft® ASP. Incorrect input can in the worst case." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. but as a developer you cannot rely on that. or input from externally supplied files. Your Web Form must validate input from an external service such as a Web service.

and if necessary. . before the request is processed on the server. redistribute. Input validation is a powerful mechanism to check for errors. it may lead to application crashes. guarantees or conditions. Please report any unauthorized use of this content to piracy@microsoft. you can filter incorrect input before input is submitted to the server. Using server-side validation. Lesson Objectives After completing this lesson. you can perform validation checks on the server and on the client. you will be able to: • Describe input validation. Using client-side input validation. If you do not validate user input. The Licensed Content is licensed "as-is. to display messages to the user.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. or resell this content. and provided to you by QuickStart Intelligence. malicious database manipulation. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. application damage." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Describe client-side and server-side input validation. or even database corruption. It is illegal to reprint.com or by calling +1 800-785-3448.

The Licensed Content is licensed "as-is.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 user’s experience with a Web site by reducing the waiting time for error messages. prevents page processing when invalid data is found. Entering letters or too few numbers triggers the input validation control to display an error message. or a mathematical formula. Users receive immediate feedback on whether the data that they entered is valid according to the rules that were created.NET. guarantees or conditions. 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. The input validation on a Web page acts as a data filter before the page or server logic is processed. Input validation verifies control values. and provided to you by QuickStart Intelligence. the use of alphanumeric characters. For example. and improve the customer’s perception of the overall quality of the Web site. If the browser supports client-side validation and validation is enabled. These predetermined input formats can include the number of characters. and requires users to re-enter the data. the input validation mechanisms that you create perform error checking on the client before posting the data to the server. In ASP. or resell this content. When combined with comprehensive and useful error messages. For security reasons. and reducing the likelihood of incorrect returns and Web sites crashing due to problems with user input. Please report any unauthorized use of this content to piracy@microsoft. and helps avoid the addition of malicious code. but it can also run on the client side if the client browser supports validation. redistribute. the value range. Verification of Control Values You can use input validation to compare user input against a predetermined input format. Input validation verifies that the user has correctly filled in an input control before the request is processed on the server." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. any input validation that is run on the client side is also repeated on the server side. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. input validation can help you improve the usability of a Web site. It is illegal to reprint. a specific character string. . input validation always runs on the server side.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.com or by calling +1 800-785-3448. With ASP. they may enter malicious code. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Server-side processing is not blocked automatically if an input validation error occurs. or resell this content. If users are allowed to add unlimited text to a Web page through user input controls that do not have input validation. which creates a false level of authorization. At this stage. this code can be disruptive on the Web server and any connected applications. Even if scripting has been disabled on the client and the page is submitted to the server. validation has not yet taken place. . When the user sends the next request to the server. client-side input validation is always repeated on the server side. User input that does not match the predetermined format triggers an error message. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.NET protects against spoofing and malicious code: • Spoofing. but it is possible to check if a page is valid— meaning that all input is valid—by using the Page.Validate method. because users can turn off client-side script by changing browser options and not running the client-side validation code. However. redistribute. and then return values that spoof valid data or an authorization check pass. and stops server processing.NET. The Licensed Content is licensed "as-is. guarantees or conditions. the Page Load event is triggered. where users cannot modify or disable validation controls. Spoofing occurs when users modify the HTML page that is sent to them. and resubmits the page for processing.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. validation is susceptible to spoofing on the client side only. Protection Against Spoofing and Malicious Code By running all the validation controls on the server side regardless of client-side validation. ASP. • Malicious code. Further processing of the page is blocked until the user corrects the input to meet the expected format. Question: How do ASP.

redistribute. By checking for errors when data is entered. or resell this content. when the user moves from one input control to the next. Although server-side validation is always required by ASP.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. client-side validation allows errors to be detected on the client-side before the Web Form is submitted.NET have both client-side and server-side support. ASP. Browsers that do not support scripts will not receive clientside validation scripts. . The controls create browser-specific code so that users with client-side script support will have client-side input validation. In browser versions that support input validation—such as Windows® Internet Explorer® 8—client-side validation occurs when users click the Submit button. because the validation logic is encapsulated in the controls. Client-side validation uses JavaScript and Dynamic HTML (DHTML) scripts. It is illegal to reprint. In modern browsers. guarantees or conditions.NET validation controls eliminate this problem.NET Framework–based language. Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Both client-side and server-side validation use the same programming model. The page will not be posted back to the server until all the client-side validation completes. the client-side validation happens for the completed input control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This prevents the round trip that is necessary for server-side validation. and provided to you by QuickStart Intelligence. The validation controls in ASP. Client-Side Validation Client-side validation enhances the usability of the Web Form by checking user input when the user enters data. client-side validation is an option with some browsers.NET. This validation feature provides users with immediate feedback on their input. The Licensed Content is licensed "as-is. Writing multiple versions of validation code to support both the server and several types of browsers can be time consuming. although variations among languages may create minor differences to the validation functions. Server-side validation can be written in any Microsoft .com or by calling +1 800-785-3448.

Client-side validations are repeated on the server side when the page posts back to the server. The Licensed Content is licensed "as-is. and geographical restrictions related to local laws and taxes. guarantees or conditions. This repetition helps avoid spoofing attempts by users who try to bypass the client-side script and send invalid input. . such as valid credit card numbers. redistribute. In addition to validating input format.QuickStart Intelligence Validating User Input 6-7 Server-Side Validation All input validation controls run on the server side." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. even with errors? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. stored passwords. Question: When will you post a page to the server. and provided to you by QuickStart Intelligence. You can write Microsoft . Please report any unauthorized use of this content to piracy@microsoft.NET-based server-side validation controls. 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. It is illegal to reprint. or resell this content.com or by calling +1 800-785-3448.

• Add validation controls to a Web Form. Please report any unauthorized use of this content to piracy@microsoft. you needed to determine the requirements. if you wanted to perform client-side validation. .NET validation controls.com or by calling +1 800-785-3448. Then. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. such as JavaScript.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. guarantees or conditions. It is illegal to reprint. you will be able to: • Describe the various ASP.NET Validation Controls Validating user input used to be a tedious and time-consuming process. and then write the validation code for the server in your preferred programming language. For each input control. Lesson Objectives After completing this lesson. ASP. or resell this content. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. redistribute.QuickStart Intelligence 6-8 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lesson 2 ASP. • Describe the RegularExpressionValidator control. • Position and configure validation controls on a Web Form. • Describe the CustomValidator control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you would write the equivalent client-side validation for each expected browser in a script language. • Combine validation controls.

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 user’s input against a specific value, or against a
second input control. The CompareValidator control is often used where the risk of typographic errors is
high, such as password fields that conceal the user's actual input.
The CompareValidator control evaluates an empty input control as valid. Therefore, if you need to
ensure a value, combine the CompareValidator control with the RequiredFieldValidator control. The
CompareValidator control uses the following common properties:

ValueToCompare. This property references against a constant value, and is used to validate against
unchanged values, such as a minimum age limit. You can use the CustomValidator control to
compare against values that are likely to change.

ControlToCompare. This property identifies another control to compare the user input against. You
can use this property to check for typographic errors by having the user enter the same data in two
adjacent fields.
If you set both the ValueToCompare and ControlToCompare properties, the ControlToCompare
property takes precedence.

Type. This property specifies the data type. You can use this property if you want to compare the
value in an input control against one of the System.String, System.Int32, System.Double,
System.DateTime, and System.Decimal .NET Framework data types. You can do this by specifying
the corresponding value from one of the ValidationDataType enum: String, Integer, Double, Date,
or Currency. Note that for dates, only the date portion can be specified, and not the time portion.

Operator. This property specifies the comparison operator to use. Operators are specified with the
name of the comparison operators, such as: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

In the following code example, a CompareValidator control verifies that the values of the two TextBox
controls, PasswordTextBox and PasswordConfirmationTextBox, match.
<asp:TextBox id="PasswordTextBox" runat="server" Text="Enter your password"
TextMode="Password" />
<br />
<asp:TextBox id="PasswordConfirmationTextBox" runat="server" Text="Confirm your
password" TextMode="Password" />
<asp:CompareValidator id="PasswordCompareValidator" runat="server" ErrorMessage="The
entered passwords do not match." ControlToCompare="PasswordTextBox"
ControlToValidate="PasswordConfirmationTextBox" Text="*" />

The RangeValidator Control
You can use the RangeValidator control to test if an input value is within a given range. The range
measured is inclusive, and both the minimum and maximum values are considered valid. The
RangeValidator control is typically used to verify that the value entered—for example, age, height, salary,
or number of children—matches the expected range.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 18–50.
<asp:TextBox id="AgeTextBox" runat="server" Text="Enter your age" />
<asp:RangeValidator id="AgeRangeValidator" runat="server" ControlToValidate="AgeTextBox"
Type="Integer" MinimumValue="18" MaximumValue="50" ErrorMessage="Applicants must be
between 18 and 50 inclusive." Text="*" />

Question: Which server control will you use to perform data-type validation?

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b, and provided to you by QuickStart Intelligence. It is illegal to reprint,
redistribute, or resell this content. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express
warranties, 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 user’s input matches a predefined
pattern—such as a telephone number, a postal code, a URL, or an e-mail address. This validation control
compares the pattern of characters, digits, and symbols that are entered by the user, with one or more
patterns in the control.
In the Properties window, when you click the ellipsis (…) button for the ValidationExpression property,
Visual Studio 2010 provides a set of preset regular expression patterns in the Regular Expression Editor
dialog box. These patterns include e-mail addresses and URLs, telephone numbers, postal codes and zip
codes, and social security numbers. To create a new pattern, first select a pattern that resembles the
functions of your desired pattern, and then select the Custom template. The pattern that you first
selected will then be available for editing as your own custom pattern. This last-used feature gives you a
foundation from which you can create your own pattern by editing what you know will work.

Regular Expression Characters
The following table describes a common set of control characters that you can use to build your own
custom regular expressions, whether used client-side or server-side.
Character

Definition

a

Matches the lowercase letter a. This is the case for all alphabet characters. Any letter that
is not preceded by a backslash (\), or part of a range, matches that literal value.

1

Matches the number or digit 1. This is the case for all numeric characters. Any number or
digit that is not preceded by a backslash (\), or part of a range, matches that literal value.

?

Matches 0 or 1 literal.

*

0 to n literals.

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

with the password. click Microsoft Visual Studio 2010. In Solution Explorer. and provided to you by QuickStart Intelligence. <asp:RequiredFieldValidator ID="DueDateRequiredFieldValidator" ControlToValidate="DueDateTextBox" runat="server" ErrorMessage="The Due Date must be filled in. • 5. right-click Order.NET Web Form.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. click All Programs. Please report any unauthorized use of this content to piracy@microsoft. with an asterisk (*) as the text.aspx window. On the Start menu of 10267A-GEN-DEV. place the cursor next to the Due Date TextBox control. in the Folder box. • On the File menu of the Start Page . as the error message. expand Validation. The Licensed Content is licensed "as-is. Demonstration Steps 1. Add a RequiredFieldValidator control named DueDateRequiredFieldValidator. Open an existing Web site from either D:\Demofiles\M6\VB\Validation or D:\Demofiles\M6\CS\Validation. It is illegal to reprint. Pa$$w0rd." Text="*"></asp:RequiredFieldValidator> • In the Order.Microsoft Visual Studio window. guarantees or conditions. 2. • In the Open Web Site dialog box. Open the Order Web Form in Design view. and The Due Date must be filled in. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . and then double-click RequiredFieldValidator. 4. • In the Toolbox. you will see how to add validation controls to an ASP. type either D:\Demofiles\M6\VB\Validation or D:\Demofiles\M6\CS\Validation. or resell this content. and then click Open. • 3.com or by calling +1 800-785-3448.aspx. and then click Microsoft Visual Studio 2010. Open Visual Studio 2010. for the DueDateTextBox control. and then click View Designer. Log on to 10267A-GEN-DEV as Student. click Open Web Site." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. The display must be dynamic.

aspx. and then double-click RegularExpressionValidator. append the following code. 0. and in the Type list. and provided to you by QuickStart Intelligence. The validator should accept only dates.vb or Order. in the (ID) box. . with an asterisk (*) as the text.\w+([. 0.Now. type The Due Date must be valid. • In Properties window.]\w+)*\. • In the Order. type DueDateRangeValidator. • In the Toolbox. click Yes. • In the Order.ToShortDateString() DueDateRangeValidator. click DueDateTextBox. expand Validation. both programmatically. in the (ID) box. or resell this content.aspx window.]\w+)* as the validation expression. click DueDateTextBox. in the ControlToValidate list. and in the ErrorMessage box. type DueDateRequiredFieldValidator. 0)). DueDateRangeValidator. and then click View Code. 7. • In the Microsoft Visual Studio message box. Add a ValidationSummary control named OrderValidationSummary.]\w+)*"></asp:RegularExpressionValidator> 8.ToShortDateString() [Visual C#] DueDateRangeValidator. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. click the Close button. It is illegal to reprint. <asp:RangeValidator ID="DueDateRangeValidator" ControlToValidate="DueDateTextBox" runat="server" ErrorMessage="The Due Date must be valid. in the ValidationExpression box.com or by calling +1 800-785-3448. type CustomerEmailAddressRegularExpressionValidator. in the ControlToValidate list.]\w+)*\.MaximumValue = (DateTime.Now + new TimeSpan(30. 0. right-click Order. redistribute. type *. • In Solution Explorer. in the ControlToValidate list. click Date. 0. below the two Button controls..']\w+)*@\w+([-.cs window.]\w+)*. click CustomerEmailAddressTextBox. and then double-click RangeValidator. • In the Toolbox. place the cursor next to the Email Address TextBox control. [Visual Basic] DueDateRangeValidator.Now. 6-23 In Properties window." Text="*"></asp:RangeValidator > • In the Order.ToShortDateString().cs window. and in the Display list. Add a RangeValidator control named DueDateRangeValidator for the DueDateTextBox control.aspx window.aspx.MaximumValue = (DateTime. place the cursor next to the DueDateRequiredFieldValidator control. The Licensed Content is licensed "as-is. <asp:RegularExpressionValidator ID="CustomerEmailAddressRegularExpressionValidator" ControlToValidate="CustomerEmailAddressTextBox" runat="server" ErrorMessage="*" ValidationExpression="\w+([-+." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.\w+([. and today’s date plus 30 days should be set as the maximum value. in the ErrorMessage box. 0)).ToShortDateString().aspx. and then press ENTER. and then press ENTER.aspx.aspx. • In Properties window. Today’s date should be set as the minimum value. Add a RegularExpressionValidator control named CustomerEmailAddressRegularExpressionValidator for the CustomerEmailAddressTextBox control.. and \w+([-+.']\w+)*@\w+([-. with an asterisk (*) as the error message. In the Text box. In the Text box. type *.vb or Order.Now + New TimeSpan(30. and The Due Date must be valid.MinimumValue = DateTime. and then press ENTER. click Dynamic. In the Text box. type The Due Date must be filled in. in the Page_Load event handler. type *. • In the Order. guarantees or conditions.]\w+)*\.QuickStart Intelligence Validating User Input • 6. type The Email Address must be valid.']\w+)*@\w+([-.. in the ErrorMessage box. as the error message.\w+([-. in the (ID) box. type \w+([-+.MinimumValue = DateTime. expand Validation. Please report any unauthorized use of this content to piracy@microsoft.

• In Properties window.com. • In the Validation– Microsoft Visual Studio window. in the Email Address box. 14. Note: Notice that there are no validation errors. and an error message in the validation summary at the bottom. place the cursor next to the OrderCancelButton TextBox control. Note: Notice that there is an asterisk next to the Email Address box. Specify a valid due date. and then click the Save button. and then click View in Browser. in the Due Date box. click Save Order. Specify a valid email address. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. type a date that is 31 days from today’s date. right-click Order. and then click the Save button. type OrderValidationSummary. Note: Notice that there is an asterisk next to the Due Date box. and save the order. Save the Order Web Form. and save the order. type claus@cohowinery. 10. • In the Order Entry – Windows Internet Explorer window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. at the same location as the one shown on the previous try to save the order. • In the Toolbox. and provided to you by QuickStart Intelligence. on the File menu. • In the Order Entry – Windows Internet Explorer window. • In the Order. 11. Save the order. The Licensed Content is licensed "as-is. • In the Order Entry – Windows Internet Explorer window.aspx window. in the Due Date box. It is illegal to reprint. and view the changes in the browser.com or by calling +1 800-785-3448. • In Solution Explorer. and then click the Save button. 12. in the format m/d/yyyy. click the Save button. . in the (ID) box.aspx. and an error message in the validation summary at the bottom. in the Email Address box. • In the Order Entry – Windows Internet Explorer window. expand Validation. Specify an invalid due date. and there is a different error message in the validation summary at the bottom. redistribute. or resell this content. type claus@cohowinery. Please report any unauthorized use of this content to piracy@microsoft. and save the order. 13. in the format m/d/yyyy. and then click the Save button. Note: Notice that today’s date has been added to the Order Date box.aspx. Specify an invalid email address and save the order. and then double-click ValidationSummary. type a date that is 30 days or less from today’s date. Note: Notice that there is an asterisk next to the Due Date box. and then press ENTER.QuickStart Intelligence 6-24 Introduction to Web Development with Microsoft® Visual Studio® 2010 <asp:ValidationSummary ID="OrderValidationSummary" runat="server"></asp:ValidationSummary> 9. guarantees or conditions. • In the Order Entry – Windows Internet Explorer window.

redistribute. The Licensed Content is licensed "as-is. guarantees or conditions. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . and provided to you by QuickStart Intelligence. Close Windows® Internet Explorer®. 15.QuickStart Intelligence Validating User Input 6-25 Note: Notice that there are no validation errors.com or by calling +1 800-785-3448. • In the Order Entry – Windows Internet Explorer window. 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. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. click the Close button.

This message will also be included in a ValidationSummary control. The following code is the standard markup for an input validation control. <asp:ValidatorType. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. by default. you typically use a red asterisk (*) to the right of the invalid input control to indicate the location of the error.>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. if you use one on the Web Form. and a Text property—both of which can be displayed at the location of the input validation control. you must position the validation control on the page where the error message text should appear.. .com or by calling +1 800-785-3448. In Visual Studio 2010.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.NET input validation controls contain two error message properties—an ErrorMessage property. The Licensed Content is licensed "as-is. • Text. It is important to position input validation controls so that it is clear to the user which control has the incorrect input.. the value for the Text property is placed between the begin and end tags of the validation control. This property is the error message that displays at the location of a validation control when the validation control is triggered. The distinction between these two error message properties is as follows: • ErrorMessage. if the Text property is not set. guarantees or conditions. redistribute. <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. In Visual Studio 2010. If you use a ValidationSummary control to collect error messages. The following code illustrates this scenario. or resell this content. 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.

redistribute... or resell this content. <asp:ValidatorType. .com or by calling +1 800-785-3448. if the page is not posted back to the server. The following table describes the Display property options.Text="TextValue" /> Setting the Display Property The Display property sets the spacing of error messages from multiple validation controls on a Web Form.. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint. and it is the default option in Visual Studio 2010. This option sometimes causes controls to move on the Web Form when error messages display. This quite often means placing the ValidationSummary control near the submit button(s). None Blocks the display of the error message at the location of the validation control. guarantees or conditions. The Display property affects only error messages at the validation control location. You can use this option to prevent the display of blank spaces on the page when input validation controls are not triggered." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.. Dynamic Enables validation controls to render on the page as part of the text flow. The Licensed Content is licensed "as-is. The ValidationSummary control should be placed where it makes sense for the user to look. Messages that are displayed in the ValidationSummary are not affected by the Display property. This option allows you to define a fixed layout for the page.Text="TextValue"></asp:ValidatorType> or <asp:ValidatorType. Option Description Static Defines a fixed layout for the error message that causes each validation control to occupy space. The following code illustrates this approach. even when no error message text is visible.QuickStart Intelligence Validating User Input 6-27 You can explicitly declare the Text property. Please report any unauthorized use of this content to piracy@microsoft.

you should manually apply server-side validation. • Programmatically validate Web Forms. You can add server-side validation code to your ASP. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. or resell this content.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. guarantees or conditions. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Forms by using Visual Studio 2010. to avoid script exploits and to ensure that validation is performed." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will be able to: • Add the ValidationSummary control. . The Licensed Content is licensed "as-is. Lesson Objectives After completing this lesson. However. redistribute. as a best practice. It is illegal to reprint.

. instead of requiring each and every individual validation control to do this.QuickStart Intelligence Validating User Input 6-29 Adding the ValidationSummary Control Key Points The ValidationSummary control displays error messages when the Page. you can display the error messages as a bulleted list or as a single paragraph. 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. this control is the reporting control that is used by the other validation controls on a page.com or by calling +1 800-785-3448. instead. or resell this content. Depending on the value of the DisplayMode property. You can use the ValidationSummary control for larger forms. and provided to you by QuickStart Intelligence.IsValid property returns false. <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. redistribute. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. which have a comprehensive form validation process. The ValidationSummary control is not a control that performs validations on the content input in your Web Forms. Please report any unauthorized use of this content to piracy@microsoft. You can use this validation control to consolidate error reporting for all the validation errors that occur on a page. The following HTML code example demonstrates a typical ValidationSummary control. The Licensed Content is licensed "as-is. 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. and the ValidationSummary control aggregates the ErrorMessage messages. It is user-friendly to have all the possible validation errors reported to the user in a single and easily identifiable manner. Each of the validation controls on the page is polled. It is illegal to reprint.

It is illegal to reprint. 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 the ErrorMessage property displays in the ValidationSummary control display.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. which is usually placed near the event that triggers the control. guarantees or conditions. redistribute. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. An ErrorMessage property with a description of the input error displays in the ValidationSummary control.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. 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. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft. .

• If you need to determine the validity of a page or an individual control in the Page_Load event handler. Another example for apply your own programmatic validation is when you are working with the RangeValidator control. but before the control event-handling code is run. So. if you want to determine validity before the validation control event handler methods are run. It is illegal to reprint. and provided to you by QuickStart Intelligence. and you are setting the MinimumValue property at run time based on values read from a configuration file. such as the MinimumValue or MaximumValue of the RangeValidator control. you can programmatically start the validation by calling the Validate method of the page or control. or resell this content. guarantees or conditions.NET validation controls perform validation automatically when a Web Form is posted back to the server. Please report any unauthorized use of this content to piracy@microsoft.Validate() [Visual C#] this. The IsValid property determines the validity of the page or a validation control.com or by calling +1 800-785-3448. This happens after page initialization. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. [Visual Basic] Me.QuickStart Intelligence Validating User Input 6-31 Programmatically Validating Web Forms Key Points The ASP.Validate(). Sometimes you may want to apply your own validation programmatically: • If you are adding controls dynamically at run time. The following code examples demonstrate how you can call the Validate method. redistribute. The problem with this property is that when it is set. • If you are setting validation values at run time. such as preventing the access of certain server-side resources—like a database—when a page is invalid. it is accessible without an exception being thrown.

If the IsValid property is false. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.IsValid) { .IsPostBack) { // Validate page this. [Visual Basic] ' User postback? If Me.. and provided to you by QuickStart Intelligence. guarantees or conditions. or resell this content. End If Next End If End If [Visual C#] // User postback? if (this. When a control performs its validation check.IsValid) { // Loop through all validation controls to see which // generated the error(s) foreach (IValidator controlValidator in this. When an error is detected and the page is returned to the user. .QuickStart Intelligence 6-32 Introduction to Web Development with Microsoft® Visual Studio® 2010 After the validation runs.Validate() ' Is page valid? If Not Me.Validate().IsValid = False Then . redistribute. you can check the IsValid property of the Page. the error messages display. } // Is page valid? if (!this.. Please report any unauthorized use of this content to piracy@microsoft. and find the validation control that caused the validation error.com or by calling +1 800-785-3448. } } } 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.IsValid Then ' Loop through validation controls to see which ' generated the error(s) For Each controlValidator As IValidator In Validators If controlValidator. It is illegal to reprint. 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..Validators) { if (!controlValidator. the IsValid property is set accordingly. The following code examples illustrate how you can validate a page on postback.IsPostBack Then ' Validate page Me..

Lab Objectives After completing this lab. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. You will use client-side scripting. In addition.com or by calling +1 800-785-3448. you must: • Start the 10267A-GEN-DEV virtual machine. refer to the steps provided in the Section 1 of the lab document. you will be able to: • Add validation controls. redistribute. you will use the available virtual machine environment. and provided to you by QuickStart Intelligence. It is illegal to reprint. Lab Setup For 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 perform server-side validation to protect the Web project against spoofing and malicious code. • Add server-side validation. • Configure validation controls." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. which will help you avoid frequent crosschecking of user inputs with the server. If you are using Visual C# as your programming language. 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.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. The Licensed Content is licensed "as-is. refer to the steps provided in Section 2 of the lab document. Before you begin the lab. guarantees or conditions. If you are using Visual Basic as your programming language. Lab Introduction In this lab.

com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence. . which is a large organization with a global customer base." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. or resell this content. For effective communication. It is illegal to reprint. 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. To meet this requirement. Your organization uses a Web site to manage its customer information. the organization should maintain updated customer information in their database. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence 6-34 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Scenario You are a developer at Contoso. redistribute. guarantees or conditions. Ltd.

Add validation controls to the user control. <asp:RequiredFieldValidator ID="CustomerAddressRequiredFieldValidator" ControlToValidate="CustomerAddressTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerZipCodeRequiredFieldValidator. Open an existing Web site.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. for the CustomerCountryDropDownList control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. It is illegal to reprint. <asp:RequiredFieldValidator ID="CustomerFirstNameRequiredFieldValidator" ControlToValidate="CustomerFirstNameTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerLastNameRequiredFieldValidator. <asp:RequiredFieldValidator ID="CustomerCityRequiredFieldValidator" ControlToValidate="CustomerCityTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerCountryRequiredFieldValidator. for the CustomerCityTextBox control. and provided to you by QuickStart Intelligence. <asp:RequiredFieldValidator ID="CustomerZipCodeRequiredFieldValidator" ControlToValidate="CustomerZipCodeTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerCityRequiredFieldValidator. guarantees or conditions. for the CustomerLastNameTextBox control.  Task 1: Open an existing Web site • Log on to 10267A-GEN-DEV virtual machine as Student with the password. Please report any unauthorized use of this content to piracy@microsoft. for the CustomerFirstNameTextBox control. redistribute. or resell this content. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. for the CustomerZipCodeTextBox control. for the CustomerWebAddressTextBox control.com or by calling +1 800-785-3448. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M6\VB folder. Pa$$w0rd. <asp:RequiredFieldValidator ID="CustomerLastNameRequiredFieldValidator" ControlToValidate="CustomerLastNameTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerAddressRequiredFieldValidator. • Open Microsoft Visual Studio 2010. The Licensed Content is licensed "as-is. 2. • Add a RequiredFieldValidator control named CustomerFirstNameRequiredFieldValidator. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerWebAddressRequiredFieldValidator.  Task 2: Add validation controls to the user control • View the markup of the Customer user control. for the CustomerAddressTextBox control.

for the CustomerCreditLimitTextBox control.ascx user control. • Test the functionality of the Customer user control. and view the changes in the browser. redistribute. for the CustomerInsertButton control.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. and provided to you by QuickStart Intelligence. <asp:RequiredFieldValidator ID="CustomerCreditLimitRequiredFieldValidator" ControlToValidate="CustomerCreditLimitTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RegularExpressionValidator control named CustomerEmailAddressRegularExpressionValidator. • Close Windows® Internet Explorer®. • Save the Customer user control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will have added validation controls to a user control. It is illegal to reprint. <asp:RangeValidator ID="CustomerCreditLimitRangeValidator" ControlToValidate="CustomerCreditLimitTextBox" runat="server" MinimumValue="500" MaximumValue="50000" ErrorMessage="RangeValidator"></asp:RangeValidator> • Add a ValidationSummary control named CustomerValidationSummary. for the CustomerEmailAddressTextBox control. for the CustomerCreditLimitTextBox control. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. . guarantees or conditions. <asp:RegularExpressionValidator ID="CustomerEmailAddressRegularExpressionValidator" ControlToValidate="CustomerEmailAddressTextBox" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> • Add a RegularExpressionValidator control named CustomerWebAddressRegularExpressionValidator. or resell this content. Result: After completing this exercise. <asp:ValidationSummary ID="CustomerValidationSummary" runat="server"></asp:ValidationSummary> • Format the Customer.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. <asp:RegularExpressionValidator ID="CustomerWebAddressRegularExpressionValidator" ControlToValidate="CustomerWebAddressTextBox" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> • Add a RangeValidator control named CustomerCreditLimitRangeValidator. for the CustomerWebAddressTextBox control.

• Add a Text property with the value of * to the CustomerZipCodeRequiredFieldValidator control.Redirect("~/Default. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Click ' Redirect to home page Response. Add error indicators and error messages to the validation controls.  Task 1: Remove validation from the Cancel button • View the default Response. 2. and view the changes in the browser. redistribute. or resell this content.aspx") End Sub • Disable the validation caused by the CustomerCancelButton control by setting the CausesValidation property in the user control to false.  Task 2: Add error indicators and error messages to the validation controls • Add a Text property with the value of * to the CustomerFirstNameRequiredFieldValidator control. ByVal e As System. <asp:Button ID="CustomerCancelButton" runat="server" Text="Cancel" CausesValidation="false" /> • Save the Customer user 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. instead of displaying the error messages." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.EventArgs) Handles CustomerCancelButton. Note: Notice that the Web browser is redirected to the default Web Form. • Change the ErrorMessage property in the CustomerZipCodeRequiredFieldValidator control to The Zip Code must be filled in. and provided to you by QuickStart Intelligence. 3. • Add a Text property with the value of * to the CustomerCityRequiredFieldValidator control. • Change the ErrorMessage property in the CustomerFirstNameRequiredFieldValidator control to The Customer First Name must be filled in.QuickStart Intelligence Validating User Input 6-37 Exercise 2: Configuring Validation Controls The main tasks for this exercise are as follows: 1. guarantees or conditions. ''' <summary> ''' Redirects to home page ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub CustomerCancelButton_Click(ByVal sender As Object. • Change the ErrorMessage property in the CustomerCityRequiredFieldValidator control to The City must be filled in. • Change the ErrorMessage property in the CustomerAddressRequiredFieldValidator control to The Address must be filled in. The Licensed Content is licensed "as-is.Redirect method of the Cancel button. It is illegal to reprint. Set the e-mail address and credit limit validation controls. Remove validation from the Cancel button. • Add a Text property with the value of * to the CustomerLastNameRequiredFieldValidator control.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft.

Zip Code. and Credit Limit controls. press the TAB key.aspx Web Form in a browser. • In the Contoso Customer Management – Windows Internet Explorer window.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. or resell this content. . click No.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. click the Insert button. • Add a Text property with the value of * to the CustomerWebAddressRequiredFieldValidator control. • Change the ErrorMessage property in the CustomerCreditLimitRequiredFieldValidator control to The Credit Limit must be filled in. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Change the ErrorMessage property in the CustomerWebAddressRegularExpressionValidator control to The Web Address must be valid. Note: Notice the error indicator and error messages next to the First Name. Country. • Change the ErrorMessage property in the CustomerCreditLimitRangeValidator control to The Credit Limit must be within the valid range. It is illegal to reprint. in the Email Address box. redistribute. • Add a Text property with the value of * to the CustomerCreditLimitRequiredFieldValidator control.com. • Change the ErrorMessage property in the CustomerWebAddressRequiredFieldValidator control to The Web Address must be filled in. Please report any unauthorized use of this content to piracy@microsoft. • In the Contoso Customer Management – Windows Internet Explorer window. Address. Note: Notice the error indicator that displays next to the Email Address and Web Address boxes. • Close Windows® Internet Explorer®. Last Name. type contoso." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. type www. because of the invalid e-mail and web addresses. • Change the ErrorMessage property in the CustomerEmailAddressRegularExpressionValidator control to The Email Address must be valid. • In the Contoso Customer Management – Windows Internet Explorer window. • Add a Text property with the value of * to the CustomerCreditLimitRangeValidator control. and provided to you by QuickStart Intelligence. guarantees or conditions.  Task 3: Set the e-mail address and credit limit validation controls • View the InsertCustomer. in the Web Address box. • Add a Text property with the value of * to the CustomerWebAddressRegularExpressionValidator control. and then press the TAB key again. click the Insert button. and view the changes in the browser. • Add a Text property with the value of * to the CustomerEmailAddressRegularExpressionValidator control. • Save the Customer user control. • Change the ErrorMessage property in the CustomerCountryRequiredFieldValidator control to A country must be selected.contoso. City. Note: If an AutoComplete message box displays.

• Click the Insert button. • Save the Customer user control.contoso.com. • Change the MinimumValue property of the CustomerCreditLimitRangeValidator control to 0. in the Email Address box.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. However.\w+([-. in the Web Address box.com. Please report any unauthorized use of this content to piracy@microsoft. type claus@contoso. Note: Notice that the error indicator and error messages do not display for the Email Address. and provided to you by QuickStart Intelligence. guarantees or conditions. • Add a Display property with the value of Dynamic to the CustomerWebAddressRequiredFieldValidator control to change the display of the error indicator text.com or by calling +1 800-785-3448.]\w+)* to the CustomerWebAddressRegularExpressionValidator control. and view the changes in the browser. you will have removed validation control from the Cancel button. Results: After completing this exercise. redistribute.\w+([-. Web Address. and then click the Insert button. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.']\w+)*@\w+([-. and added error indicators and error messages to the validation controls.]\w+)* to the CustomerEmailAddressRegularExpressionValidator control. type http://www. It is illegal to reprint. and Credit Limit boxes. • In the Contoso Customer Management – Windows Internet Explorer window. • Set the Type property with the value of Integer to the CustomerCreditLimitRangeValidator control. • Add a ValidationExpression property with the value of \w+([-+. or resell this content.']\w+)*@\w+([-. and view the changes in the browser. the error message for the Credit Limit box is still The Credit Limit must be within the valid range. • Close Windows® Internet Explorer®. • Save the Customer user control. • Close Windows® Internet Explorer®. . • Add a Display property with the value of Dynamic to the CustomerCreditLimitRequiredFieldValidator control to change the display of the error indicator text. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Also notice that the error message for the Credit Limit box is The Credit Limit must be within the valid range. • Add a ValidationExpression property with the value of \w+([-+. Note: Notice that the location of the error indicator for the Credit Limit box has changed.]\w+)*\.]\w+)*\.

Please report any unauthorized use of this content to piracy@microsoft." Text="*" EnableClientScript="false"></asp:RequiredFieldValidator> • Save the Customer user control.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.Validate() ' Did page validation succeed? If Not Page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.IsValid Then Return End If ' Add the current user name currentCustomer.CreditLimit = 50000 End Sub • Add postback validation to the Page_Load event handler method. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint.com or by calling +1 800-785-3448.Name ' Add the user credit limit currentCustomer.ascx.EventArgs) Handles CustomerInsertButton. The Licensed Content is licensed "as-is.Load If Page. and provided to you by QuickStart Intelligence. ByVal e As System. • Add the code to validate the user control within the CustomerInsertButton_Click event handler method. or resell this content.User. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="A country must be selected. ''' <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.Identity.vb code window. and view the changes in the browser. ByVal e As System.CreatedBy = Context.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. guarantees or conditions.IsPostBack Then ' Validate Page Page.  Task 1: Validate the Customer User Control • Open the Customer. ''' <summary> ''' Instantiates Customer object ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> ''' <remarks></remarks> Protected Sub Page_Load(ByVal sender As Object.Click ' Did page validation succeed? If Not Page. redistribute.EventArgs) Handles Me.

the error indicator for the Country list and associated error message display. Please report any unauthorized use of this content to piracy@microsoft. redistribute. and format and save the Customer user control. Note: The answers to the exercises are on the Course Companion CD. or resell this content. . guarantees or conditions. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Remove the EnableClientScript property for the CustomerCountryRequiredFieldValidator control to enable the client-side validation for the CustomerCountryDropDownList control. and provided to you by QuickStart Intelligence. click the Close button. Also notice that after the postback." Text="*"></asp:RequiredFieldValidator> • In the CustomerManagement – Microsoft Visual Studio window. It is illegal to reprint. Results: After completing this exercise.QuickStart Intelligence Validating User Input • 6-41 In the Contoso Customer Management – Windows Internet Explorer. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. • Revert the changes made to the 10267A-GEN-DEV virtual machine.com or by calling +1 800-785-3448. you will have added server-side validation controls to the Customer user control.com Note: Notice the postback of the Web page with the inputs. • Close Windows® Internet Explorer®.cohowinery. type the following settings. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="A country must be selected. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.  Task 2: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine.

and provided to you by QuickStart Intelligence. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M6\CS folder. <asp:RequiredFieldValidator ID="CustomerFirstNameRequiredFieldValidator" ControlToValidate="CustomerFirstNameTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerLastNameRequiredFieldValidator.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.  Task 2: Add validation controls to the user control • View the markup of the Customer user control. for the CustomerFirstNameTextBox control. . <asp:RequiredFieldValidator ID="CustomerLastNameRequiredFieldValidator" ControlToValidate="CustomerLastNameTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerAddressRequiredFieldValidator. for the CustomerCityTextBox control. Please report any unauthorized use of this content to piracy@microsoft. <asp:RequiredFieldValidator ID="CustomerAddressRequiredFieldValidator" ControlToValidate="CustomerAddressTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerZipCodeRequiredFieldValidator. • Add a RequiredFieldValidator control named CustomerFirstNameRequiredFieldValidator. Open an existing Web site. Add validation controls to the user control. for the CustomerLastNameTextBox control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. <asp:RequiredFieldValidator ID="CustomerCityRequiredFieldValidator" ControlToValidate="CustomerCityTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerCountryRequiredFieldValidator. <asp:RequiredFieldValidator ID="CustomerZipCodeRequiredFieldValidator" ControlToValidate="CustomerZipCodeTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerCityRequiredFieldValidator. • Open Microsoft Visual Studio 2010. for the CustomerAddressTextBox control. or resell this content. for the CustomerZipCodeTextBox control. for the CustomerCountryDropDownList control. 2. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RequiredFieldValidator control named CustomerWebAddressRequiredFieldValidator. It is illegal to reprint. The Licensed Content is licensed "as-is. redistribute. Pa$$w0rd." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. for the CustomerWebAddressTextBox control.  Task 1: Open an existing Web site • Log on to 10267A-GEN-DEV virtual machine as Student with the password.

Result: After completing this exercise. for the CustomerEmailAddressTextBox control. for the CustomerInsertButton control. . <asp:RequiredFieldValidator ID="CustomerCreditLimitRequiredFieldValidator" ControlToValidate="CustomerCreditLimitTextBox" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> • Add a RegularExpressionValidator control named CustomerEmailAddressRegularExpressionValidator. It is illegal to reprint. and provided to you by QuickStart Intelligence. • Test the functionality of the Customer user control. for the CustomerCreditLimitTextBox control. redistribute. and view the changes in the browser." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. <asp:RangeValidator ID="CustomerCreditLimitRangeValidator" ControlToValidate="CustomerCreditLimitTextBox" runat="server" MinimumValue="500" MaximumValue="50000" ErrorMessage="RangeValidator"></asp:RangeValidator> • Add a ValidationSummary control named CustomerValidationSummary. for the CustomerWebAddressTextBox control. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Save the Customer user control. <asp:RegularExpressionValidator ID="CustomerWebAddressRegularExpressionValidator" ControlToValidate="CustomerWebAddressTextBox" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> • Add a RangeValidator control named CustomerCreditLimitRangeValidator.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. or resell this content. you will have added validation controls to a user control. The minimum value is 500 and the maximum value is 50000.ascx user control.com or by calling +1 800-785-3448. guarantees or conditions. <asp:ValidationSummary ID="CustomerValidationSummary" runat="server"></asp:ValidationSummary> • Format the Customer. Please report any unauthorized use of this content to piracy@microsoft. <asp:RegularExpressionValidator ID="CustomerEmailAddressRegularExpressionValidator" ControlToValidate="CustomerEmailAddressTextBox" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator> • Add a RegularExpressionValidator control named CustomerWebAddressRegularExpressionValidator. The Licensed Content is licensed "as-is. • Close Windows® Internet Explorer®.

/// <summary> /// Redirects to home page /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CustomerCancelButton_Click(object sender. • Add a Text property with the value of * to the CustomerCountryRequiredFieldValidator control. redistribute. or resell this content. EventArgs e) { // Redirect to home page Response. The Licensed Content is licensed "as-is. • Add a Text property with the value of * to the CustomerCityRequiredFieldValidator control. • Change the ErrorMessage property in the CustomerLastNameRequiredFieldValidator control to The Customer Last Name must be filled in. Set the e-mail address and credit limit validation controls. • Change the ErrorMessage property in the CustomerZipCodeRequiredFieldValidator control to The Zip Code must be filled in. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. } • Disable the validation caused by the CustomerCancelButton control by setting the CausesValidation property in the user control to false." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx").  Task 1: Remove validation from the Cancel button • View the default Response. • Add a Text property with the value of * to the CustomerLastNameRequiredFieldValidator control.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. • Add a Text property with the value of * to the CustomerAddressRequiredFieldValidator control. • Change the ErrorMessage property in the CustomerCityRequiredFieldValidator control to The City must be filled in.com or by calling +1 800-785-3448. Note: Notice that the Web browser is redirected to the default Web Form. • Change the ErrorMessage property in the CustomerAddressRequiredFieldValidator control to The Address must be filled in. and provided to you by QuickStart Intelligence. .Redirect("~/Default. Please report any unauthorized use of this content to piracy@microsoft. Add error indicators and error messages to the validation controls. <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. It is illegal to reprint. 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. Remove validation from the Cancel button.Redirect method of the Cancel button. guarantees or conditions. • Add a Text property with the value of * to the CustomerZipCodeRequiredFieldValidator control. 2. • Change the ErrorMessage property in the CustomerFirstNameRequiredFieldValidator control to The Customer First Name must be filled in. 3.

• In the Contoso Customer Management – Windows Internet Explorer window. Note: Notice the error indicator and error messages next to the First Name. • Change the ErrorMessage property in the CustomerWebAddressRequiredFieldValidator control to The Web Address must be filled in. type contoso. press the TAB key. • Add a Text property with the value of * to the CustomerEmailAddressRegularExpressionValidator control. because of the invalid e-mail and web addresses. click the No button.com. click the Insert button. in the Web Address box. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448.aspx Web Form in a browser. Note: If you see the AutoComplete message box display. • Add a Text property with the value of * to the CustomerWebAddressRegularExpressionValidator control. City. in the Email Address box. click the Insert button. Note: Notice the error indicator that displays next to the Email Address and Web Address boxes. Please report any unauthorized use of this content to piracy@microsoft. • Change the ErrorMessage property in the CustomerCreditLimitRangeValidator control to The Credit Limit must be within the valid range. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. type www. • Add a Text property with the value of * to the CustomerWebAddressRequiredFieldValidator 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. • Add a Text property with the value of * to the CustomerCreditLimitRangeValidator control. It is illegal to reprint. Zip Code. and Credit Limit controls. Last Name. • In the Contoso Customer Management – Windows Internet Explorer window. or resell this content. • Close Windows® Internet Explorer®. • In the Contoso Customer Management – Windows Internet Explorer window. • Save the Customer user control and view the changes in the browser. • Change the ErrorMessage property in the CustomerCreditLimitRequiredFieldValidator control to The Credit Limit must be filled in. Address.  Task 3: Set the e-mail address and credit limit validation controls • View the InsertCustomer. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Country.contoso. • Change the ErrorMessage property in the CustomerEmailAddressRegularExpressionValidator control to The Email Address must be valid.QuickStart Intelligence Validating User Input 6-45 • Change the ErrorMessage property in the CustomerCountryRequiredFieldValidator control to A country must be selected. and then press the TAB key. and provided to you by QuickStart Intelligence. redistribute. guarantees or conditions.

Please report any unauthorized use of this content to piracy@microsoft. you will have removed validation control from the Cancel button.com or by calling +1 800-785-3448. Note: Notice that the error indicator and error messages do not display for the Email Address. Also notice that the error message for the Credit Limit box is The Credit Limit must be within the valid range. and the error indicator text for the Web Address box is not aligned with the other error indictors. and view the changes in the browser. Note: Notice that the location of the error indicator for the Credit Limit box has changed.com. in the Web Address box. type http://www.']\w+)*@\w+([-. • Click the Insert button. • Add a ValidationExpression property with the value of \w+([-+. • Change the MinimumValue property of the CustomerCreditLimitRangeValidator control to 0.]\w+)* to the CustomerWebAddressRegularExpressionValidator control. • In the Contoso Customer Management – Windows Internet Explorer window.\w+([. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Add a ValidationExpression property with the value of \w+([-+. guarantees or conditions. The Licensed Content is licensed "as-is. However. or resell this content. and then click the Insert button. It is illegal to reprint. . Results: After completing this exercise.\w+([. type claus@contoso.']\w+)*@\w+([-.]\w+)*\.contoso.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 Credit Limit boxes.]\w+)*\.com. • Close Windows® Internet Explorer®. • Close Windows® Internet Explorer®. • Save the Customer user control and view the changes in the browser. • Add a Display property with the value of Dynamic to the CustomerWebAddressRequiredFieldValidator control to change the display of the error indicator text. and provided to you by QuickStart Intelligence. redistribute. the error message for the Credit Limit box is still The Credit Limit must be within the valid range. • Add a Display property with the value of Dynamic to the CustomerCreditLimitRequiredFieldValidator control to change the display of the error indicator text. in the Email Address box. and added error indicators and error messages to the validation controls.]\w+)* to the CustomerEmailAddressRegularExpressionValidator control. • Save the Customer user control. • Set the Type property with the value of Integer to the CustomerCreditLimitRangeValidator control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Web Address.

Please report any unauthorized use of this content to piracy@microsoft. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="A country must be selected.  Task 1 : Validate the Customer User Control • Open the Customer. • In the Contoso Customer Management – Windows Internet Explorer. . Disable the client-side validation for the CustomerCountryDropDownList control.IsPostBack) { // Validate Page Page. /// <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.cs code window.com or by calling +1 800-785-3448. • Add the code to validate the user control within the CustomerInsertButton_Click event handler method.Identity. EventArgs e) { if (Page. • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. guarantees or conditions. protected void Page_Load(object sender. // Instantiate Customer instantiateCustomerObject(). This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. EventArgs e) { // Did page validation succeed? if (!Page. } • // Add the current user name currentCustomer. // Populate the UI controls populateUI().IsValid) return. It is illegal to reprint.CreatedBy = Context. type the following settings.User. } } • // Did page validation succeed? if (!Page. and then click the Insert button. Add postback validation to the Page_Load event handler method." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. by setting the EnableClientScript property of the CustomerCountryRequiredFieldValidator control to false." Text="*" EnableClientScript="false"></asp:RequiredFieldValidator> • Save the Customer user control and view the changes in the browser.CreditLimit = 50000.Validate().IsValid) return.Name. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. redistribute.ascx. or resell this content. // Add the user credit limit currentCustomer.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.

• Close Windows® Internet Explorer®." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Revert the changes made to the 10267A-GEN-DEV virtual machine." Text="*"></asp:RequiredFieldValidator> • In the CustomerManagement – Microsoft Visual Studio window. the error indicator for the Country list and its associated error message displays. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. click the Close button. Results: After completing this exercise. The Licensed Content is licensed "as-is.com Note: Notice the postback of the Web page with the inputs. Note: The answers to the exercises are on the Course Companion CD. guarantees or conditions. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. you will have added server-side validation controls to the Customer user control.QuickStart Intelligence 6-48 Introduction to Web Development with Microsoft® Visual Studio® 2010 • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. or resell this content.  Task 2: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. . and format and save the Customer user control. • Remove the EnableClientScript property for the CustomerCountryRequiredFieldValidator control to enable the client-side validation for the CustomerCountryDropDownList control. <asp:RequiredFieldValidator ID="CustomerCountryRequiredFieldValidator" ControlToValidate="CustomerCountryDropDownList" runat="server" ErrorMessage="A country must be selected.com or by calling +1 800-785-3448.cohowinery. Also notice that after the postback.

Please report any unauthorized use of this content to piracy@microsoft. . redistribute. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 2. and then click Revert. in the Virtual Machines pane. click Revert. click Turn Off. It is illegal to reprint. In the Revert Virtual Machine dialog box. 3. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. in the Virtual Machines pane. In the Turn Off Machine dialog box. 1. The Licensed Content is licensed "as-is. right-click 10267A-GEN-DEV. 4. right-click 10267A-GEN-DEV. and provided to you by QuickStart Intelligence. In Hyper-V Manager. and then click Turn Off.QuickStart Intelligence Validating User Input 6-49 Lab Shutdown After you complete the lab. or resell this content. you must turn off the 10267A-GEN-DEV virtual machine and revert the changes. In Microsoft Hyper-V™ Manager.com or by calling +1 800-785-3448.

Why do you use a ValidationSummary control? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.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. It is illegal to reprint. . redistribute. Why have you added the RegularExpressionValidator control for the e-mail address field? 2. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is.

NET validation controls fit your validation needs. guarantees or conditions. Which control will you use to perform the following validation tasks? Real-World Issues and Scenarios 1. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. because client-side scripting might be disabled. or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. None of the intrinsic ASP. which could then be sent to the server.QuickStart Intelligence Validating User Input 6-51 Module Review and Takeaways Review Questions and Answers 1. redistribute. Best Practices Mention some best practices in the context of your own business situations. and add the validation logic as code. It is illegal to reprint. or a malicious user could compromise the user input. • Always validate user input that is used for performing actions server-side. . You want to make sure that an input control is always filled in by the user. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. but you also want it to be in a specific format. What would you do to solve the issue? Create a new CustomValidator control. What is the easiest way to add this? Add a RequiredFieldValidator and a RegularExpressionValidator control. 2. such as searching a database or accessing server-side resources. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. • Always add server-side validation code when using validation controls.

com or by calling +1 800-785-3448. It is illegal to reprint. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. . guarantees or conditions.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.

NET 7-17 Lab: Troubleshooting Microsoft ASP.NET Web Applications Contents: Lesson 1: Debugging in ASP.QuickStart Intelligence Troubleshooting Microsoft® ASP. The Licensed Content is licensed "as-is.NET Web Applications 7-25 This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft.NET Web Applications 7-1 Module 7 Troubleshooting Microsoft® ASP. and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. guarantees or conditions.NET 7-3 Lesson 2: Tracing in ASP. It is illegal to reprint. redistribute. or resell this content.

You can use the Microsoft® Visual Studio® 2010 compilers to identify compile-time errors. you can use the Visual Studio 2010 debugger. This module describes the steps required to enable tracing and debugging. you can identify errors and fix them. The Licensed Content is licensed "as-is. redistribute. logic errors. To find runtime errors and logic errors. or runtime errors. Errors could include compile-time errors. including how you can use debugging and tracing in a Web application.QuickStart Intelligence 7-2 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Overview When you develop a Web application. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint. Debugging is an important part of development to ensure that a Web application meets specified requirements. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. or use Visual Studio 2010 along with the Debug and Trace objects.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. You can also trace the application to capture its runtime information and analyze its performance. or resell this content. During the debugging process. it is difficult to find every possible error in code. .

you can run the Visual Studio 2010 debugger on the computer hosting the Web application. • Describe remote debugging in a Web application.NET Web Applications 7-3 Lesson 1 Debugging in ASP. guarantees or conditions. . and stepping through the code in debug mode.NET You can use debugging to find errors in an ASP. or resell this content. • Describe debugging. The Licensed Content is licensed "as-is. • Describe the methods for printing Debug information. • Describe debugging in a Web application. It is illegal to reprint.com or by calling +1 800-785-3448. This lesson describes how you can perform both local debugging and remote debugging.NET Web application. • Explain how to gather debug information at run time. Debugging is the process of identifying and resolving the logical and technical errors in a Web application. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft. you will be able to: • Describe types of errors. remote debugging enables you to debug a Web application that runs at a remote location. While local debugging helps you debug applications on your local computer.QuickStart Intelligence Troubleshooting Microsoft® ASP. Lesson Objectives After completing this lesson. redistribute. and provided to you by QuickStart Intelligence." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You can debug a Web application by adding breakpoints. For most debugging operations. • Describe the Debug class.

or the End Sub statement in Visual Basic. Runtime errors are also known as exceptions.. For example. and your application must decide whether or not to handle the exception.. Syntax notifications or squiggles under code indicates that the code will not compile or that might cause an error. this could be the curly braces that surround a block of code in Microsoft Visual C#® ((!this. a syntax error occurs.QuickStart Intelligence 7-4 Introduction to Web Development with Microsoft® Visual Studio® 2010 Discussion: Types of Errors Key Points When you develop applications. if the file is not available when the application tries to access it. redistribute. guarantees or conditions. . Syntax Errors The syntax of an application must be correct for a compiler to be able to compile the code. Exception handling can be implemented by wrapping code in a Try. runtime errors. Before you can resolve these errors. Syntax errors are part of what is referred to as compile-time errors.. and the rules associated with the structure. However.com or by calling +1 800-785-3448. an exception is thrown. Please report any unauthorized use of this content to piracy@microsoft.. you need to identify the type of error to fix it appropriately. an application may rely on another file at runtime. [Visual Basic] Try This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Syntax refers to the application structure.catch construct. You can identify syntax errors in order to resolve them when you compile the application. Visual Studio 2010 warns you of potential errors at design time. There are three kinds of errors that you need to handle when you develop applications: syntax errors. If you leave out one of the matching curly braces in Visual C#. The Licensed Content is licensed "as-is.). or the matching Begin and End statements in Microsoft Visual Basic® (Sub SubName() . It is illegal to reprint. like the following example.." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. and semantic errors. you could encounter several types of errors.Catch/try. End Sub..IsPostBack) { Block of Code }). or resell this content. and for the application to run. Runtime Errors Runtime errors occur while the application is running. For example.

guarantees or conditions. It is illegal to reprint. However. your application may not perform as intended. For example." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. a user performs a calculation. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. that are critical to your application. This means that the semantics of the application are wrong. . and provided to you by QuickStart Intelligence. output. redistribute. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Troubleshooting Microsoft® ASP. ' that potentially throws an exception Catch ' Add any cleanup/resolve code here to handle the exception ' thrown. The Licensed Content is licensed "as-is. and the correct result displays on the screen.NET Web Applications 7-5 ' Place any code here. because your application will appear to run successfully and you will not see any error messages. that are critical to your application. and the flow of the application’s logic to locate the bug. 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. If the calculation and related operations are not saved to the data storage. // that potentially throws an exception } catch { // Add any cleanup/resolve code here to handle the exception // thrown. a second user will view the same data initially viewed by the first user. 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 it requires you to follow the input. Identifying this type of error can be very tricky and confusing.com or by calling +1 800-785-3448.

The Licensed Content is licensed "as-is. Bug fixing does not apply to released software only. and provided to you by QuickStart Intelligence. eventually. Locating the Bug Without Using the Debugger When you decide to fix a bug. when an action—such as user input—leads to an unexpected error or result. you can start looking at each individual line of code—either manually. and finally.” and the process of tracking them is called debugging. 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. It is illegal to reprint. it is also for projects under development. When you find a single class or a single method that is responsible for the bug. you first need to decide whether you should fix it. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. . When you encounter a bug. you search for and locate the bug at runtime. This process can be accompanied by sending the output of the intermediary results to a file or the user interface (UI). 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.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 manually checking where the bug starts occurring." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you will locate the bug. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. then identify the source of the error. guarantees or conditions.com or by calling +1 800-785-3448. In general. fix the bug by using the tools provided by Visual Studio 2010. most bugs are fixed. or by commenting out lines of code to locate exactly which line of code is responsible for the bug. but not always.

you need to fix them according to the specification of the particular method or class that you are working with. line by line. or resell this content. Based on the type of bug found. When the line of code is hit at runtime. There are also other bugs that after extensive research require you to redesign an entire class or even a module. . redistribute. The Visual Debugger tool helps you set breakpoints." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 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. You set a breakpoint on a specific line of code. guarantees or conditions. Visual Studio 2010 provides you with the Visual Studio 2010 debugger. and step through the code line by line. you can examine the code to fix it. such as removing a line of code that is not needed.NET Framework objects and constructs that help you fix bugs. and Microsoft . Please report any unauthorized use of this content to piracy@microsoft.NET Web Applications 7-7 Fixing the Bug After you have found the problem line or lines of code. It is illegal to reprint. and provided to you by QuickStart Intelligence. While it is entirely possible to locate and fix a bug manually. Some errors require simple fixes. the code opens in the debugger. others require a new expression or calculation. it is more convenient to fix bugs by using various tools. it will save time if you use one or more tools for debugging your code. you have to determine how to fix it.QuickStart Intelligence Troubleshooting Microsoft® ASP. The Licensed Content is licensed "as-is. In most cases. At this point. and then proceed through the code that follows. if needed.com or by calling +1 800-785-3448.

you do not have to create an instance of it.Assert Use this method to display a message if a specified condition is false. The Licensed Content is licensed "as-is. So. The following table lists the methods of the Debug class. The Debug class is globally available to your application when you import the System." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 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. you can ensure that your code is robust. or to write the output from an object’s ToString method. This is because when compiling in Release mode. You cannot create an instance of the Debug class. and provided to you by QuickStart Intelligence. and you cannot inherit the class because it is sealed.Write Use this method to write a string of text of your choice. followed by a line terminator. . without affecting the performance and the code size of your released product. Debug. because it has no constructors. It is illegal to reprint. Using the Debug class.com or by calling +1 800-785-3448.Print Use this method to write a formatted line of text of your choice. is written to the trace listeners in the Listeners collection. Debug. guarantees or conditions. or to write conditionally the output from an object’s ToString method. The message or string of text.WriteLine Use this method to write a line of text of your choice. The message or string of text is written to the trace listeners in the Listeners collection. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. The call stack that is being shown in the dialog box when calling Debug.Diagnostics namespace. the calls to methods and properties of the Debug class are not compiled in the assembly at compile time. Method Description Debug. or to write the output from an object’s ToString method.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.WriteIf Use this method to conditionally write a string of text of your choice. Debug. redistribute.

redistribute. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Note: A listener produces formatted output when debugging and tracing.NET Web Applications Method 7-9 Description Visual Studio 2010 in a break state. The Listeners collection contain listeners monitors the debug and trace output. The Licensed Content is licensed "as-is. or resell this content.com or by calling +1 800-785-3448.QuickStart Intelligence Troubleshooting Microsoft® ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft. . and provided to you by QuickStart Intelligence. guarantees or conditions.

It is used to capture and present execution details about a Web request. Note: To use the Debug class. or resell this content. 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. In a Web Form. which. the TraceContext class is accessible by using the Trace property of the Page class. If you create a release build. displays the output in the Debug pane of the Output window in Visual Studio 2010. You can use the Debug class to output debug information.Diagnostics namespace. . the statements will not be included in the compiled assembly. redistribute. you can view diagnostic information about page requests by enabling the tracing feature for your page or application. With the Debug class. You need to remember that the Trace property is different from the Trace class in the System.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. by default. or to the trace log in memory. It is illegal to reprint. The TraceContext class enables you to display information on a Web page. Using the Debug and TraceContext classes. Statements that use the Debug class run only when you compile the application using the debug mode. you can make your code more stable without affecting the performance of the final product or the code size. and provided to you by QuickStart Intelligence. • The TraceContext class.com or by calling +1 800-785-3448." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you must import the System. you can collect and display diagnostic information at runtime: • The Debug class. or prefix the class method call with the namespace. guarantees or conditions. messages are sent as output to the current collection of trace listeners. A listener produces formatted output from the debug output. and when the Web application is run in the debugger. When you use the Debug class to print debug information and check your logic. The Licensed Content is licensed "as-is. Please report any unauthorized use of this content to piracy@microsoft.Diagnostics namespace in your code file.

including the Write and WriteLine methods.. you can use a number of methods. There are four overloads of this method—two that write a single line of text. Writes a text string to the trace listeners."). Please report any unauthorized use of this content to piracy@microsoft. Debug.") Debug.Write("Writing a string of text. "Category 2") [Visual C#] Debug.QuickStart Intelligence Troubleshooting Microsoft® ASP.WriteLine("Writing a line of text. "Category 1") Debug. guarantees or conditions..". so that any new text following your call will be written on the next line.. or resell this content. There are four overloads of this method—two that write a single line of text. Writes a text string to the trace listeners. and adds a new line character at the end of the text. You can use the category name to group the output messages. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Applications 7-11 Methods for Printing Debug Information Key Points To print any debug information."." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties... • Write.com or by calling +1 800-785-3448. and two others that write a single line of text and the category name.WriteLine("Writing a line of text. "Category 1").. It is illegal to reprint.WriteLine("Writing a line of text..."). The Licensed Content is licensed "as-is. The following code examples show how you can use the Write and WriteLine methods. you can use two other methods: the WriteIf method. .Write("Writing a string of text...WriteLine("Writing a line of text. The category name can be used to group the output messages. Debug.".Write("Writing a string of text. and the WriteLineIf method.Write("Writing a string of text. Debug. and provided to you by QuickStart Intelligence. [Visual Basic] Debug. • WriteLine.. and two others that write a single line of text and the category name.. To conditionally print any debug information...".") Debug. "Category 2")... redistribute.

or resell this content."). and provided to you by QuickStart Intelligence. which takes three parameters: condition. Debug. "Brief Message") Debug. "Brief Message".") Debug. The dialog box generates with the method overload. Debug. There are four overloads of this method: two that write a single line of text.IsPostBack) [Visual C#] Debug.") [Visual C#] Debug. Debug. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. To format any debug information when printing.IsPostBack. and then embed that representation in a string..IsPostBack. and adds a new line character at the end of the text.Print("Printing a line of text. There are four overloads of this method—two that write a single line of text.IsPostBack. Postback = {0}".. The method has four overloads. as shown in the following code examples. "Writing a line of text. and two that write a single line of text and the category name. "Brief Message".IsPostBack.Assert(Page. Conditionally writes a text string to the trace listeners. and whether you compile the application in debug or release mode. Conditionally writes a text string to the trace listeners.WriteLineIf(Page.Assert(Page.Assert method to check for the condition.Assert(Page.Assert(Page. "Brief Message") Debug. guarantees or conditions. The first overload shown above takes only a condition parameter. "Detail description message"." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.. If you need to display either a message or the call stack if a specific condition is false.Assert(Page. Postback = {0}".IsPostBack. A dialog box displays whether you run the application with or without debugging.IsPostBack. There are two overloads of this method..IsPostBack. [Visual Basic] Debug.Assert(Page."). "Detail description message") Debug. You can use the category name to group the output messages.IsPostBack) Debug. [Visual Basic] Debug.Format method to convert the value of an object to its text representation. "Brief Message". "Writing a line of text.IsPostBack.. you can use the Print method. and description.IsPostBack).. "Writing a string of text. The following code examples show how to use the WriteIf and WriteLineIf method.QuickStart Intelligence 7-12 Introduction to Web Development with Microsoft® Visual Studio® 2010 • WriteIf."). as shown in the following code examples. and two that write a single line of text and the category name that can be used to group the output messages. The Licensed Content is licensed "as-is.WriteIf(Page..Assert(Page. "Writing a string of text.IsPostBack.Assert(Page. [Visual Basic] Debug.. objectArrayToFormat) [Visual C#] Debug.IsPostBack.. "Brief Message". .Print("Printing a line a text.. objectArrayToFormat). Page. Page. "Detail description message").IsPostBack) Debug. • WriteLineIf. which uses the String.") Debug. It is illegal to reprint.Print("Printing a line of text. The Print method writes a formatted line of text to the trace listeners. redistribute. message.WriteIf(Page.. you can use the Debug.. 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. "Detail description message".WriteLineIf(Page.Print("Printing a line a text. so that any new text following your call will be written on the next line.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and the parameter values.NET Web Applications 7-13 the call stack.QuickStart Intelligence Troubleshooting Microsoft® ASP. or resell this content. and provided to you by QuickStart Intelligence. The call stack shows you the names of the functions on the call stack." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the parameter types. guarantees or conditions.com or by calling +1 800-785-3448. at a given point in time. Please report any unauthorized use of this content to piracy@microsoft. redistribute. It is illegal to reprint. . The Licensed Content is licensed "as-is.

web> <configuration> [Visual C#] <configuration> <system. and finally. guarantees or conditions.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.. The following code examples show how to set the value of the debug attribute. In addition. you can step through the code when a breakpoint is hit. [Visual Basic] <configuration> <system. or resell this content.com or by calling +1 800-785-3448.config file. Enabling Web Application Debugging You must enable debugging—if you want to debug your Web application—and you need to do this in the web. you can use debugging to identify the source of the problem. and provided to you by QuickStart Intelligence. When you want to debug a Web application. where you want execution to pause. Please report any unauthorized use of this content to piracy@microsoft. you need to decide if you want to add breakpoints in your code. redistribute. and then decide if you need to generate an output of debug information while your Web application is running. you first need to enable debugging. It is illegal to reprint. .web element. you need to run the Web application in the debug mode. You need to locate the opening compilation element that is found within the system.web> <compilation debug="true" strict="false" explicit="true"> .web> <configuration> This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and then set the value of the debug attribute to true.web> <compilation debug="true"> . </system. The Licensed Content is licensed "as-is.. If you have added any breakpoints... </system." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

QuickStart Intelligence Troubleshooting Microsoft® ASP. you will be prompted to enable debugging by the appearance of the Debugging Not Enabled message box. collectively known as variable windows. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. and then click NamespaceName.config file. The Value and Type columns display the value and data type of the corresponding variable or expression result. Value. or resell this content. To display these menu items. the Name column is where you can add your own variables or expressions. the lines of code with the breakpoints are highlighted in a white text color on a dark red background color. The Licensed Content is licensed "as-is. you must press F5. properties are normally stepped over. In the Watch window. in the Name column. By default. point to Step Into Specific. This will modify the web. or click Delete All Breakpoints on the Debug menu to remove all the breakpoints using a single action. guarantees or conditions. the debugger must be running or in break mode. or click Toggle Breakpoint on the Debug menu. Stepping Through Code When the debugger reaches the line with the breakpoint. because they generally do not contain any complex logic. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and Watch1 through Watch 4. or click Step Over on the Debug menu. Press F11. Locals. 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 Type. You need to first locate the line of code to which you want to add the breakpoint. or click Toggle Breakpoint on the Debug menu. press F9 again. if you want to step into the underlying code of the current line of code to be executed. and then choose the name of the variable window you want to display. Watch. then.com or by calling +1 800-785-3448.  To display a variable window • On the Debug menu. By default. You will be prompted to confirm this action. you cannot access these menu items or display these windows in design mode. choose Windows.set_PropertyName. Execution will pause on the next line of code. if there is any. In the message box. execution pauses. You can edit the value of a variable in the Value column. simply click OK to enable debugging. If you have many breakpoints and you decide to remove them all. Use Debugger Variable Windows The Visual Studio 2010 debugger provides several windows. for displaying variable information during debugging. It is illegal to reprint. 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. Press F10. you can add a breakpoint. To remove the breakpoint. or a method in another class). If debugging has not yet been enabled at this point. The Autos and Locals windows display names of the variables that are added automatically. Execution will pause on the next line of code in the underlying code. These windows are: Autos. but it is possible to step into a property.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 right-click the line of code that is calling the property getter or setter. redistribute. Running in Debug Mode To run your application in debug mode. and then press the F9 key. you can press CTRL+SHIFT+F9. or click Start Debugging on the Debug menu. You can then step through the code and examine the logic of your application. or click Step Into on the Debug menu.ClassName. on the context menu. Each variable window has a grid with three columns: Name.

you can use the Remote Debugging Monitor—or msvsmon. For example. the Remote Debugging Monitor runs as a Windows®-based application. It is illegal to reprint. or if you want to test the application while it is deployed on a Web server. or run the monitor remotely from a shared folder. .NET or another server environment. from a single workstation. redistribute. You must also consider security features. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448. Before you start remote debugging. You can either install the Remote Debugging Monitor on the remote computer.exe— which is a small application to which Visual Studio 2010 connects. To debug in ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Remote Debugging Setup Visual Studio 2010 supports remote debugging from one computer to another. the host computer can be any platform that supports Visual Studio 2010. The Licensed Content is licensed "as-is. By default. guarantees or conditions. Remote Debugging Monitor When you perform remote debugging. Remote debugging enables you to debug Web applications on numerous disparate servers. the remote server must grant access to the user who performs the debugging. and provided to you by QuickStart Intelligence. 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. you can configure the monitor to run as a Windows service by using the Visual Studio 2010 Remote Debugger Configuration Wizard.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. you must configure the environments on both the debugger host and the remote computer. You may want to use remote debugging if you cannot run your Web application locally. Reasons for performing remote debugging are when the program you are debugging is on the Web server. You can start this wizard from the Visual Studio Tools folder on the Start menu. or if the program is performing differently on your computer. or resell this content. When you perform remote debugging.

Please report any unauthorized use of this content to piracy@microsoft. Lesson Objectives After completing this lesson. because by default.QuickStart Intelligence Troubleshooting Microsoft® ASP. This includes recording any exception details. and recording the program flow.NET Web Applications 7-17 Lesson 2 Tracing in ASP. You can then enable tracing when you find an error. and provided to you by QuickStart Intelligence. you will be able to: • Describe tracing. or if you have a performance issue. or a similar environment in which you cannot perform debugging. 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. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Tracing is the process of receiving informative messages about the execution of a Web application at runtime—that is. • Perform tracing in a Web application. tracing is not enabled. Visual Studio 2010 provides the TraceContext class for this purpose. Tracing statements can remain in your code when you release your Web application. or resell this content. which means any trace output is ignored. guarantees or conditions. This lesson describes how to use the TraceContext class to implement tracing in a Web application. • Describe the TraceContext class. Tracing is typically used in a production environment. . tracing is useful when it is impractical to use the debugger. So. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. it is a way to monitor the execution of your Web application.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. It is illegal to reprint.

redistribute. or if you want to follow the path of execution and view how much time was spent in the various methods. If one of your Web pages contains an error and you want to analyze the error. you can use tracing. You also need to decide if you want to use page-level tracing. . ASP. or simply trace through the execution path of your page or application. two events occur: • ASP. It is illegal to reprint.NET introduces a function called tracing. or resell this content.NET Trace ASP. The information is also sent to a trace viewer application. The Licensed Content is licensed "as-is. you must enable tracing for the page or application. and then you need to decide if you need to get an output of the trace information while your Web application is running. You can write variables or structures in a page. To trace a Web application.NET appends a series of diagnostic information tables immediately following the page's output. 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. assert whether a condition is met. or application-level tracing. and provided to you by QuickStart Intelligence.NET page simply by enabling it for your page or application. Please report any unauthorized use of this content to piracy@microsoft.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. 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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. which allows you to view diagnostic information about a single request for an ASP. • ASP. guarantees or conditions.com or by calling +1 800-785-3448. In order for these messages and other tracing information to be gathered and displayed. you first need to enable tracing.NET displays your custom diagnostic messages in the Trace Information table of the appended performance data. When you enable tracing. if you have enabled tracing for the application.

because it is sealed. New Exception("En Exception was thrown. you should never create an instance of this class. which indicates that you can supply a caught or user-defined exception. the TraceContext class cannot be inherited. of type Exception. Because the TraceContext class is readily available when working in an ASP. all warnings appear in the log as red text. all of which write a trace message to the trace log." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET Framework infrastructure. unlike the Write method. It is illegal to reprint. The Licensed Content is licensed "as-is. • Warn.")) This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. because.com or by calling +1 800-785-3448. "Trace Message". [Visual Basic] Trace. you do not need to create an instance of it. The second overload specifies the category name that indicates the category that will receive the trace message. or resell this content.Write("Category 1". or to the trace log in memory.. Writes a trace message to the trace log. and provided to you by QuickStart Intelligence.HttpContext. The third overload takes a third parameter. However.NET Web Applications 7-19 TraceContext Class Key Points You can use the TraceContext class to write trace messages on a page. The following code examples show how you can write trace messages. In fact. redistribute. it is not intended to be used directly from your code. There are three overloads of the Write method.NET Web Form through the Trace property of the Page class. which encapsulates all HTTP-specific information about a Hypertext Transfer Protocol (HTTP) request.Web. guarantees or conditions.. Please report any unauthorized use of this content to piracy@microsoft.Write("Trace Message") Trace.Write("Category 2". The Warn method is similar to the Write method. you can use any of the following methods of the TraceContext class: • Write. the TraceContext class is of type System. "Trace Message") Trace. You implement the trace log by using the TraceRecords messages collection. To write information to the trace log. which is a collection of trace records that are associated with the current request. . because the constructor supports the . Also. Therefore.QuickStart Intelligence Troubleshooting Microsoft® ASP.

the output will be appended to the page in which the code has been executed. because. If you enable tracing. The following code examples illustrate this.IsEnabled Statement TraceContext class has a Boolean property named IsEnabled. to sort trace messages by the categories that you specified in the Warn and Write method calls. It is illegal to reprint..Write("Category 1". <%@ Page . On the trace information page.")). which enables you to call the Write and Warn methods only when tracing is enabled.com or by calling +1 800-785-3448. to sort trace messages in the order in which they are processed.Write("Category 2".IsEnabled statement. 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.Write("Tracing is enabled!") End If [Visual C#] if (Trace. For example.IsEnabled) { Trace. TraceContext. Set TraceMode to SortByTime. The following code examples illustrate how to use the Trace.QuickStart Intelligence 7-20 Introduction to Web Development with Microsoft® Visual Studio® 2010 [Visual C#] Trace. Please report any unauthorized use of this content to piracy@microsoft.IsEnabled = false. [Visual Basic] If Trace. Trace.. Trace="True" TraceMode="SortByCategory" %> You can use the IsEnabled property of the TraceContext class to dynamically change the state of tracing in a page." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. } You can also use the IsEnabled property to dynamically change the state of tracing for a page. Trace. new Exception("En Exception was thrown.Write("Tracing is enabled!"). the category parameter enables you to classify and group trace messages. and provided to you by QuickStart Intelligence. guarantees or conditions. redistribute.Write("Trace Message"). The Licensed Content is licensed "as-is.IsEnabled Then Trace. you can set the sort order of trace messages to display messages of the same category together.IsEnabled = False [Visual C#] Trace. or resell this content. "Trace Message". [Visual Basic] Trace.. "Trace Message").. . The following code shows how you can set TraceMode to SortByCategory. The TraceMode attribute can be used to specify the order in which you want your trace messages to appear.

NET Web Applications 7-21 You can use the TraceContext class to append messages to specific trace categories. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. and to obtain a set of trace records at the end of request execution for custom processing. guarantees or conditions. and provided to you by QuickStart Intelligence. It is illegal to reprint.QuickStart Intelligence Troubleshooting Microsoft® ASP.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content.

web> <trace enabled="true" /> . or resell this content. you need to configure the web. [Visual Basic] <%@ Page Language="VB" Trace="true" %> [Visual C#] <%@ Page Language="C#" Trace="true" %> When you use page-level tracing.. redistribute. Please report any unauthorized use of this content to piracy@microsoft.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.. guarantees or conditions. <configuration> . which enables you to quickly view the trace messages when you view the Web page. </system.config file for the Web application. Enabling Web Application Tracing The following code examples show how you can enable page-level tracing. To enable page-level tracing. The following code shows how you can enable application-level tracing. you must set the Trace attribute of the Page directive to true for the Web Form." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties..web> </configuration> If you need to view the trace information when your application is running. you can use the methods of the TraceContext class. <system. The Licensed Content is licensed "as-is. all trace messages append to the end of the Web page. and provided to you by QuickStart Intelligence. To enable application-level tracing. and add the trace element. It is illegal to reprint. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448.. .

along with the size of each item.Warn statements. the number of bytes it took to be rendered. For example. or to memory. You must be aware of the number of bytes used by each of your controls. However." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . The trace results contains lot of information. runtime type. Presents an HTML representation of the ASP.aspx page for which they are enabled. redistribute. if any. The following table lists each category. This is a very useful section for debugging. Session State Contains information about values stored in Session state. with page-level tracing. To view the application-level trace viewer.axd to the URL—for example. with application-level tracing. guarantees or conditions. you enable tracing for all the pages in the Web application. Form Collection Displays a list of controls. or resell this content. Application-level tracing also gives you flexibility when you write trace statements. http://www. and the From Last(s) column displays the increment duration. Trace statements that you save to memory are accessible by the application-level trace viewer trace. and then runs any trace statements that it contains. Querystring Displays a list of values passed in the URL. and provides the description about the type of information it contains. you can write trace messages to the page. and you can choose a specific request from any of the application pages that have been requested. and the bytes it requires in ViewState and ControlState. You want your controls to return as few bytes as possible to keep the overall page weight down.com/trace. Application State Contains information about values stored in Application state.Write and Trace. Category Description Request Details Contains information about the request: session identification (ID). Control Tree Lists of all of the items that are on the page. Shows each control’s unique ID. You can view the trace output in the trace viewer. time of request. The three columns showing the weight of each control indicates the number of bytes occupied in ViewState or ControlState by that particular control. Please report any unauthorized use of this content to piracy@microsoft.NET Web Applications 7-23 When you enable application-level tracing. the page gathers trace information. It is illegal to reprint. type of request. The Licensed Content is licensed "as-is. all trace messages are appended to the page. especially if you write your custom controls. and provided to you by QuickStart Intelligence. Cookies Collection Displays a list of cookies that are in use for the request and response. and add trace. The trace viewer lists the requests in the order in which they were processed.QuickStart Intelligence Troubleshooting Microsoft® ASP.NET Control Tree. type the URL for your application.axd. along with the custom messages that you created by using the Trace. The From First(s) column contains the total time from execution until the trace is run. The timing information located here is valuable when profiling and searching for methods in your application that take too long to execute.com or by calling +1 800-785-3448. Trace Results Page-level trace results are appended to the end of the . and request status. Trace Categories Trace results contain several categories of information. When a page in your Web application is requested.contoso. Headers Collection Displays a list of request and response message header name/value pairs. if any.axd. and their values on the form that is posted. Trace Information Contains output from standard and custom trace statements.

It is illegal to reprint. The Licensed Content is licensed "as-is.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. guarantees or conditions.com or by calling +1 800-785-3448. . and provided to you by QuickStart Intelligence. You can view trace information at the bottom of each page. Please report any unauthorized use of this content to piracy@microsoft." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. 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. redistribute.

NET Web Applications Note: You can perform tasks in this lab by using either the Visual Basic or Visual C# programming language. It is illegal to reprint.NET Web Applications 7-25 Lab: Troubleshooting Microsoft ASP. you will use the available virtual machine environment. and provided to you by QuickStart Intelligence. and server variables. guarantees or conditions. If you are using Visual Basic as your programming language. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. • Enable and implement tracing in a Web application. 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. Before you begin the lab. Application state.NET Web application for runtime errors by adding breakpoints and watches." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. refer to the steps provided in Section 2 of the lab page.QuickStart Intelligence Troubleshooting Microsoft® ASP. . Introduction In this lab. you must: • Start the 10267A-GEN-DEV virtual machine. If you are using Visual C# as your programming language. you will be able to: • Debug a Web application to view runtime information. The Licensed Content is licensed "as-is.com or by calling +1 800-785-3448. refer to the steps provided in the Section 1 of the lab page. you will debug an ASP. redistribute. In addition. Objectives After completing this lab. Lab Setup For this lab. you will implement tracing in the Web application to view information such as Session state.

aspx Web Form. or resell this content. and provided to you by QuickStart Intelligence.QuickStart Intelligence 7-26 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab Scenario You are a developer at Contoso. there seems to be a performance issue when loading or rendering the InsertCustomer. and then test that you can view the timings for the InsertCustomer." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. breakpoints. You also need to enable tracing by using the web. You need to debug the application by adding appropriate output statements. 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. guarantees or conditions. you need to debug the customer management Web application for logical issues in its functionality. You are not allowed to append trace information to each page. The Licensed Content is licensed "as-is. so you must therefore enable application-level tracing.com or by calling +1 800-785-3448. It is illegal to reprint.aspx Web Form. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Ltd. However. redistribute. 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. and watches.config file to identify possible errors in the code after the application’s deployment.

guarantees or conditions. Open an existing ASP. 3. send the message. • At the end of the private populateUI method. “No Page Postback detected in Page_Load” to the trace listeners. Imports System. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.WriteLine("Page has been unloaded") • At the end of the Click event of the CustomerInsertButton control. send the message. send the message. “Page has been unloaded” to the trace listeners. “UI controls have been populated” to the trace listeners." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. “Page Postback detected in Page_Load” to the trace listeners. “Customer object has been instantiated” to the trace listeners.NET Web site • Log on to 10267A-GEN-DEV as Student. • Set the debug attribute of the compilation element to true.Diagnostics namespace. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M7\VB folder. <compilation debug="true" strict="false" explicit="true" targetFramework="4.WriteLine("Customer has been inserted in CustomerInsertButton_Click"). Debug. It is illegal to reprint. Pa$$w0rd. Please report any unauthorized use of this content to piracy@microsoft. Debug.  Task 1: Open an existing ASP. "No Page Postback detected in Page_Load") • At the end of the Page_Unload event handler. Add debug output statements to the user control. Enable debugging of the CustomerManagement Web project.com or by calling +1 800-785-3448.config file. 4.  Task 3: Add debug output statements to the user control • Open the Customer user control. “Customer has been inserted in CustomerInsertButton_Click” to the trace listeners. Find and fix a bug. 2.NET Web site.WriteLine("Page Postback detected in Page_Load") • In the Page_Load event handler.config file of the CustomerManagement Web project. Debug.WriteLineIf(Not Page. and provided to you by QuickStart Intelligence. send the message. send the message. send the message. Debug. redistribute. or resell this content. .IsPostBack. when the page is loaded in response to a postback. when the page is not loaded in response to a postback.0" /> • Save and close the web. • Import the System. Debug. • Open Microsoft Visual Studio 2010. The Licensed Content is licensed "as-is. with the password.QuickStart Intelligence Troubleshooting Microsoft® ASP.  Task 2: Enable debugging of the CustomerManagement Web project • Open the web.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.WriteLine("UI controls have been populated") • At the end of the private instantiateCustomerObject method.Diagnostics • In the Page_Load event handler.

type USA. • Click the Smart Tag button. You may have to scroll up to see the statements. Please report any unauthorized use of this content to piracy@microsoft.com Close Windows Internet Explorer®.  Task 4: Find and fix a bug • Run the CustomerManagement Web application to test its functionality. • Save and close the user control file. by creating a new customer. and then click Edit Items. • • Verify the output for the Click event handler of the CustomerInsertButton control. by creating a new customer and viewing the Output pane of the Debugger variable windows. Note: In the Debug pane of the Output window.ascx. The Licensed Content is licensed "as-is. Page_Unload. right-click and then click View Designer. click Add. or resell this content. in the Text box. and instantiateCustomerObject methods. click the CustomerCountryDropDownList control. redistribute.vb window. • In the ListItem Collection Editor dialog box. using the following information. • In the Customer. • Create a new customer.com or by calling +1 800-785-3448. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www.QuickStart Intelligence 7-28 Introduction to Web Development with Microsoft® Visual Studio® 2010 Debug.cohowinery. Note: In the Debug pane of the Output window. It is illegal to reprint. notice that the Customer has been inserted in CustomerInsertButton_Click message is displayed.WriteLine("Customer object has been instantiated") • Save the user control code file. • In the Customer. • Zip Code: 98052 • City: Buffalo • State: NY This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. by using the following information: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. and then clicking the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. and provided to you by QuickStart Intelligence. . and then click OK. • Add a default item to the Country DropDownList control. • In the ListItem properties pane. notice that the output of the Debug statements displays. • Verify the output for the Page_Load.ascx window." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Run the Web application in the debug mode. guarantees or conditions.

This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web Applications • 7-29 Web Address: http://www. click New. Please report any unauthorized use of this content to piracy@microsoft. instantiateCustomerObject(). • Examine the code in the populateUI method that assigns a value to the CustomerCreditLimitTextBox. • In the Contoso Customer Management – Windows Internet Explorer window.cohowinery. . on the Customers menu. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. • Run the Web application in debug mode. and provided to you by QuickStart Intelligence. the value of the CustomerCreditLimitTextBox Text property is set to 0. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. which is incorrect.com Note: Notice that the value for the Credit Limit box is set to 0 by default. • Step over the call to the instantiateCustomerObject method. guarantees or conditions. • Create a new customer. notice that the value for the CustomerCreditLimitTextBox is changed to 50.QuickStart Intelligence Troubleshooting Microsoft® ASP. Note: Notice that the value for the Credit Limit box is set to 50.Text property. The Licensed Content is licensed "as-is. • Step over the first line of code and then check for postback in the instantiateCustomerObject method.com Note: Notice that in the Watch 1 window. or resell this content. • Add a watch to the Text property of the CustomerCreditLimitTextBox control. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. • Continue to debug the Web application. It is illegal to reprint.cohowinery. Note: In the Watch1 window. • Stop debugging the Web project.com or by calling +1 800-785-3448. • Click the Insert button. • Add a breakpoint in the Page_Load event handler method in the line of code that calls the instantiateCustomerObject method. • Step over the call to the populateUI method. • Close Windows Internet Explorer®. • Step into the instantiateCustomerObject method. by using the following information.

• Re-run the Web application in debug mode to examine the Customer class. and provided to you by QuickStart Intelligence.CreditLimit = creditLimit • Step through the assignment of the passed value to the CreditLimit property.com or by calling +1 800-785-3448. • Remove the extra value from the customerCreditLimit property. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. and then the check for postback. until the following line of code in the constructor that initializes the CreditLimit property is reached. by continuing program execution.vb code window. • Step into the method that instantiates the customer object. Me. . by using the following information: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St.cohowinery. by viewing the Call Stack window.customerCreditLimit = value + 50 • View the functions and procedure calls that are currently on the stack. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. Note: Stepping into the instantiation of the customer object action may take some time. Me. • Zip Code: 98052 • City: Buffalo This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Run the Web application to verify the Credit Limit value. The Licensed Content is licensed "as-is. and ignore the first breakpoint. guarantees or conditions.com • Step into the instantiateCustomerObject method. • Step over the first line of code. It is illegal to reprint. • Locate the step that adds the extra 50 to the private customerCreditLimit member Credit Limit box. Please report any unauthorized use of this content to piracy@microsoft. Me.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. by using the following information. • Create a new customer. • Step over each single line of code in the Customer.customerCreditLimit = value • Save and close the class file. • Create a new customer. or resell this content. • Stop debugging the Web project. • Create a new customer.

." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Troubleshooting Microsoft® ASP. • Close Windows Internet Explorer®. Results: After completing this exercise. and fixed a bug in the CustomerManagement Web application functionality.NET Web Applications • • State: NY • Web Address: http://www. guarantees or conditions. It is illegal to reprint.com or by calling +1 800-785-3448.com 7-31 Click the Insert button. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will have enabled debugging for the CustomerManagement Web project. The Licensed Content is licensed "as-is. Note: Notice that the value for the Credit Limit box is still 0. and provided to you by QuickStart Intelligence.cohowinery. or resell this content. Please report any unauthorized use of this content to piracy@microsoft. added debug output statements to the user control. redistribute.

 Task 1: Enable application-level tracing of the CustomerManagement Web project • Add a trace element to the web. Please report any unauthorized use of this content to piracy@microsoft. click View Details of /InsertCustomer. redistribute.config file as the first element within the system. and set the value of the enabled attribute to true. and unloading the Web Form. GET.com • View the trace details for the application. • Close Windows Internet Explorer®. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. Note: Scroll down to see all of the information output. Enable application-level tracing of the CustomerManagement Web project. • View the details for the InsertCustomer. It is illegal to reprint.  Task 2: Implement application tracing • Run the Web application. and provided to you by QuickStart Intelligence. 2. session and application state.aspx corresponding to the Verb. guarantees or conditions. rendering.axd URL in the browser. form and querystring collection.aspx Web page. or resell this content. Verify that you can see the Trace Information section. by using the http://localhost:1111/CustomerManagement/trace.com or by calling +1 800-785-3448. Results: After completing this exercise. • In the http://localhost:1111/CustomerManagement/trace. by using the following information.axd . • Revert the changes made to the 10267A-GEN-DEV virtual machine. and view the trace details. you will have enabled and implemented application-level tracing for the CustomerManagement Web application. including the control tree.config file. and server variables of the InsertCustomer. which gives you information about how much time is spent when loading. The Licensed Content is licensed "as-is. • Create a new customer.cohowinery. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St.  Task 3: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine.Windows Internet Explorer window. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.aspx Web page.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. <trace enabled="true" /> • Save and close the web. Implement application tracing.web.

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. 3.config file. 2. 4. using System. Please report any unauthorized use of this content to piracy@microsoft. “Customer has been inserted in CustomerInsertButton_Click” to the trace listeners. "No Page Postback detected in Page_Load"). Enable debugging of the CustomerManagement Web project. Debug. send the message.Diagnostics namespace to the user control. Debug. redistribute.0"> • Save and close the web.IsPostBack. when the page is not loaded in response to a postback.  Task 3: Add debug output statements to the user control • Open the Customer user control. • In the Page_Load event handler.Diagnostics. • In the Page_Load event handler. • At the end of the private populateUI method. and provided to you by QuickStart Intelligence. Find and fix the bug.com or by calling +1 800-785-3448. send the message. Debug.WriteLine("UI controls have been populated"). with the password. It is illegal to reprint. • Open Microsoft Visual Studio 2010.  Task 1: Open an existing ASP. “No Page Postback detected in Page_Load” to the trace listeners.NET Web site • Log on to 10267A-GEN-DEV as Student. <compilation debug="true" targetFramework="4. guarantees or conditions. • Set the debug attribute of the compilation element to true. • At the end of the Page_Unload event handler. Debug. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M7\CS folder. “Customer object has been instantiated” to the trace listeners. send the message.WriteLine("Customer has been inserted in CustomerInsertButton_Click").WriteLineIf(Not Page.QuickStart Intelligence Troubleshooting Microsoft® ASP. • At the end of the private instantiateCustomerObject method.  Task 2: Enable debugging of the CustomerManagement Web project • Open the web. • Import the System. Debug. “Page has been unloaded” to the trace listeners. send the message.WriteLine("Page Postback detected in Page_Load"). • At the end of the Click event of the CustomerInsertButton control. send the message. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Open an existing ASP. . Pa$$w0rd.NET Web site. when the page is loaded in response to a postback.WriteLine("Page has been unloaded"). “Page Postback detected in Page_Load” to the trace listeners. The Licensed Content is licensed "as-is. Add debug output statements to the user control. or resell this content.config file of the CustomerManagement Web project. send the message. “UI controls have been populated” to the trace listeners.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. in the Text box.com or by calling +1 800-785-3448. click Add. It is illegal to reprint.  Task 4: Find and fix a bug • Run the CustomerManagement Web application to test its functionality.cohowinery. • Save and close the user control file. or resell this content. The Licensed Content is licensed "as-is.ascx window. • In the ListItem properties pane.WriteLine("Customer object has been instantiated"). redistribute. and then click Edit Items.QuickStart Intelligence 7-34 Introduction to Web Development with Microsoft® Visual Studio® 2010 Debug. Note: In the Debug pane of the Output window. and then Click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. • In the ListItem Collection Editor dialog box. Page_Unload. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. Please report any unauthorized use of this content to piracy@microsoft. by creating a new customer and viewing the Output pane of the Debugger variable windows.ascx. notice that the output of the Debug statements display. • In the Customer. • In the Customer. .cs window. Note: In the Debug pane of the Output window. • Create a new customer. • Verify the output for the Page_Load. by using the following information: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. and instantiateCustomerObject methods. and provided to you by QuickStart Intelligence. type USA. guarantees or conditions. right-click and then click View Designer. • Zip Code: 98052 • City: Buffalo • State: NY This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Run the Web application in the debug mode. • Save the user control code file. notice that the Customer has been inserted in CustomerInsertButton_Click message is displayed. and then click OK.com Close Windows Internet Explorer®. • Click the Smart Tag button. You may have to scroll up to see the statements. click the CustomerCountryDropDownList control. • • Verify the output for the Click event handler of the CustomerInsertButton control. by creating a new customer using the following information. • Add a default item to the Country DropDownList control.

• Continue to debug the Web application. • Run the Web application in debug mode. • Step into the instantiateCustomerObject method. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. • Step over the first line of code and the check for postback in the instantiateCustomerObject method. • Stop debugging the Web project. which is incorrect. • Create a new customer. and provided to you by QuickStart Intelligence.NET Web Applications • 7-35 Web Address: http://www. instantiateCustomerObject()." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com Note: Notice that in the Watch 1 window. The Licensed Content is licensed "as-is. Note: Notice that the value for the Credit Limit box is set to 50. by using the following information. redistribute. Please report any unauthorized use of this content to piracy@microsoft. • Add a watch to the Text property of the CustomerCreditLimitTextBox control.QuickStart Intelligence Troubleshooting Microsoft® ASP. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St.Text property. Note: Notice that the value of 50 for the CreditLimit property is not assigned here. • Click the Insert button. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. the value of the CustomerCreditLimitTextBox Text property is set to 0. guarantees or conditions.com or by calling +1 800-785-3448. • Add a breakpoint in the Page_Load event handler method in the line of code that calls the instantiateCustomerObject method.com Note: Notice that the value for the Credit Limit box is set to 0 by default.cohowinery. . notice that the value for the CustomerCreditLimitTextBox is changed to 50. • Examine the code in the populateUI method that assigns a value to the CustomerCreditLimitTextBox. • Close Windows Internet Explorer®.cohowinery. or resell this content. • Step over the call to the instantiateCustomerObject method. Note: In the Watch1 window. • Step over the call to the populateUI method. It is illegal to reprint.

cohowinery. this. The Licensed Content is licensed "as-is. • Step into the method that instantiates the customer object. or resell this content. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. • Create a new customer. • Locate the step that adds the extra 50 to the private customerCreditLimit member Credit Limit box. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Step through the assignment of the passed value to the CreditLimit property.customerCreditLimit = value. • Remove the extra value from the customerCreditLimit property. Please report any unauthorized use of this content to piracy@microsoft.customerCreditLimit = value + 50. and ignore the first breakpoint.cs code window. It is illegal to reprint. guarantees or conditions. redistribute. and provided to you by QuickStart Intelligence. by using the following information.CreditLimit = creditLimit. • Step over the first line of code and then the check for postback. and then click the Insert button: • First Name: Claus • Last Name: Hansen • Address: 4567 Main St. by using the following information.com • Step into the instantiateCustomerObject method. • Save and close the class file. this. by viewing the Call Stack window. Note: Stepping into the instantiation of the customer object action may take some time. until the following line of code in the constructor that initializes the CreditLimit property is reached. by continuing program execution. • Step over each single line of code in the Customer. • Run the Web application to verify the Credit Limit value. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www. this.cohowinery. .com This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • View the functions and procedure calls that are currently on the stack. • Stop debugging the Web project. • Create a new customer.com or by calling +1 800-785-3448.Create a new customer.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.

" Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. • Close Windows Internet Explorer®. added debug output statements to the user control.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence Troubleshooting Microsoft® ASP. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. you will have enabled debugging for the CustomerManagement Web project. guarantees or conditions. . and provided to you by QuickStart Intelligence. and fixed a bug in the CustomerManagement Web application functionality.NET Web Applications 7-37 Note: Notice that the value for the Credit Limit box is still 0. The Licensed Content is licensed "as-is. redistribute. Results: After completing this exercise. or resell this content.

Results: After completing this exercise. • Revert the changes made to the 10267A-GEN-DEV virtual machine.config file. you will have enabled and implemented application-level tracing for the CustomerManagement Web application. • Turn off the 10267A-GEN-DEV virtual machine. redistribute. and unloading the Web Form. Enable application-level tracing of the CustomerManagement Web project. by using the http://localhost:1110/CustomerManagement/trace.web. you must turn off the 10267A-GEN-DEV virtual machine and revert the changes. • Close Windows Internet Explorer®." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.aspx Web page.  Task 3: Turn off the virtual machine and revert the changes After you complete the lab. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Implement application tracing. The Licensed Content is licensed "as-is. • Create a new customer. . Verify that you can see the Trace Information section. • Zip Code: 98052 • City: Buffalo • State: NY • Web Address: http://www.config file as the first element within the system.aspx Web page. form and querystring collection. It is illegal to reprint.axd . and then click the Insert button: • • First Name: Claus • Last Name: Hansen • Address: 4567 Main St.com or by calling +1 800-785-3448. by using the following information. GET.com View the trace details for the application.cohowinery. or resell this content. and view the trace details. and provided to you by QuickStart Intelligence. session and application state. View the details for the InsertCustomer. <trace enabled="true" /> • Save and close the web.Windows Internet Explorer window. click View Details of /InsertCustomer. • In the http://localhost:1110/CustomerManagement/trace. 2.aspx corresponding to the Verb. rendering. Note: Scroll down to see all of the information output. and set the value of the enabled attribute to true.  Task 2: Implement application tracing • Run the Web application. guarantees or conditions. and server variables of the InsertCustomer.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. Please report any unauthorized use of this content to piracy@microsoft.axd URL in the browser. including the control tree.  Task 1: Enable application-level tracing of the CustomerManagement Web project • Add a trace element to the web. which gives you information about how much time is spent when loading.

Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint.NET Web Applications 7-39 Lab Review Review Questions and Answers 1." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. guarantees or conditions.QuickStart Intelligence Troubleshooting Microsoft® ASP. What are the steps required to enable page-level tracing? 2. . The Licensed Content is licensed "as-is. or resell this content. redistribute. 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.

Diagnostics. and provided to you by QuickStart Intelligence. Best Practices Mention some best practices in the context of your own business situations. What is the difference between page-level tracing and application-level tracing? 3." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. What is the difference between the System. How do you enable application-level tracing? 4.QuickStart Intelligence 7-40 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Review and Takeaways Review Questions and Answers 1.WriteIf method.Debug object? 2. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.axd to view the trace output. you need to start tracing. and use the trace viewer trace. . The Licensed Content is licensed "as-is. redistribute. • Always disable tracing in a Web application before deployment to a production server. What is the easiest way to implement this? Call the Debug. you want to write the value of a variable to the trace listeners.Trace object and the System. guarantees or conditions. In a method. but only if a specific condition is true. 2. On a production server. Please report any unauthorized use of this content to piracy@microsoft. but you do not want the users to see the trace output on each page they request. or resell this content. What are the types of errors that you need to handle when you develop applications? Real-World Issues and Scenarios 1.Diagnostics. It is illegal to reprint. How will you implement this? You enable application-level tracing.com or by calling +1 800-785-3448. • 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.

The Licensed Content is licensed "as-is. guarantees or conditions. .NET 4." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.QuickStart Intelligence Managing Data in a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. redistribute.NET 8-3 Lesson 2: Connecting to a Database 8-13 Lesson 3: Managing Data 8-23 Lab: Managing Data in an ASP.0 Web Application 8-1 Module 8 Managing Data in a Microsoft® ASP. and provided to you by QuickStart Intelligence.0 Web Application Contents: Lesson 1: Overview of ADO.0 Web Application 8-36 This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint.com or by calling +1 800-785-3448.NET 4.NET 4.

NET Web application by using the tools that are built into Microsoft Visual Studio® 2010.NET is designed to work in disconnected environments such as the Internet. ADO." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. redistribute. Considering the reach of the Internet as the means of data communication. or resell this content. The Licensed Content is licensed "as-is. It is illegal to reprint. and how you can incorporate ADO.NET is. a data technology such as ADO.NET into a Microsoft ASP. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.QuickStart Intelligence 8-2 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Overview Microsoft® ADO. This module explains what ADO.NET is the technology that you can use to connect Microsoft .NET makes data accessible and updatable in a disconnected architecture. and it provides a flexible and simple way for you to integrate data access and data manipulation into your Web applications. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.NET Framework–based applications to data sources such as Microsoft SQL Server® databases and XML files. .com or by calling +1 800-785-3448.

You can use ADO. or resell this content. and how it works.NET Web Forms. Lesson Objectives After completing this lesson.NET Because of the importance of data storage in Web applications.NET Entity Framework. ADO.NET Framework base class library that helps you access and manipulate data.NET is a part of the . you must be familiar with the data access methods that ADO. . and provided to you by QuickStart Intelligence.NET to access and manage data in both non-relational data sources.NET object model. and relational database systems such as SQL Server 2008. guarantees or conditions.NET provides for ASP. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.NET is. • Describe the ADO. This lesson explains what ADO.NET—data providers and DataSet—help you connect to and access data sources.0 Web Application 8-3 Lesson 1 Overview of ADO. • Describe the ADO. The Licensed Content is licensed "as-is.NET.NET 4.QuickStart Intelligence Managing Data in a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft. redistribute.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will be able to: • Describe ADO. The two components in ADO.

redistribute.NET Framework Data Provider.NET consists of two layers—a disconnected layer. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.NET ADO.0 and newer databases." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. including: • SQL Server . ADO. The DataSet contains a collection of one or more DataTable objects that consist of rows and columns of data. and the primary key. for accessing any OLE DB data source for which you have an OLE DB provider.com or by calling +1 800-785-3448. guarantees or conditions.NET is a part of the .NET can be used to access data in non-relational data sources. Therefore.NET? Key Points ADO. its primary use is to access and manage data that is stored in relational database systems.NET is a good choice for Internet-based Web applications. Connected Layer The connected layer manages the traffic of data to and from the data source. ADO. such as SQL Server or an XML file. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. for accessing SQL Server 7. or resell this content. .NET Framework Data Provider. Even though ADO.NET uses XML as the format for data transmission between the database and your Web application. ADO.NET is specifically designed for data-related connections in a disconnected environment. and is a set of components that you can use to access and manipulate data. and relation information about the data in the DataTable objects. ADO. and a connected layer. constraint. ADO.NET ships with a number of ready-to-use data providers. The DataSet class is the main class that represents an in-memory cache of data. and is specific to a data source.NET Framework base class library. foreign key. Disconnected Layer The disconnected layer consists of a number of classes for storing data and relations.QuickStart Intelligence 8-4 Introduction to Web Development with Microsoft® Visual Studio® 2010 What Is ADO. It is illegal to reprint. The Licensed Content is licensed "as-is. • OLE DB . You can think of the DataSet class as an in-memory representation of a database. The connected layer is also known as the data provider. such as SQL Server 2008.

including IBM and Oracle.NET? This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. .NET 4. redistribute.QuickStart Intelligence Managing Data in a Microsoft® ASP. have created . It is illegal to reprint.NET Framework Data Provider.0 Web Application • 8-5 ODBC .NET." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.NET Framework Data Provider implementations. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. for accessing any ODBC data source for which you have an ODBC driver. Question: What is the primary use of ADO. or resell this content. The Licensed Content is licensed "as-is. Most data sources from major vendors facilitate data access by using ADO. A number of third-party vendors.com or by calling +1 800-785-3448.

Disconnected Layer The disconnected layer includes the DataTable. set to null values. which are found within the System. and can be used to manage inmemory data. and provided to you by QuickStart Intelligence. guarantees or conditions.Data namespace.NET object model provides an infrastructure that you can use to access data from different data sources. The disconnected layer is independent of a data source.NET Object Model Key Points The ADO. . it can be used with multiple data sources or XML data. you can connect the disconnected layer to a data source by using the connected layer. redistribute. 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. 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 following table lists these common types. which is usually made up of the DataSet class and related classes." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The ForeignKeyConstraint class determines whether the values in the related tables are also deleted.QuickStart Intelligence 8-6 Introduction to Web Development with Microsoft® Visual Studio® 2010 ADO. set to default values. Constraint. DataColumn Represents the schema of a single column in a DataTable. and DataView classes. The disconnected layer consists of common types for storing data and relations. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. The Licensed Content is licensed "as-is. A This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. It is illegal to reprint.NET object model: the disconnected layer. Optionally. Multiple DataColumn objects are used to specify the structure or schema of a DataTable. There are two layers of the ADO. or if no action should be taken. DataRelation Represents a parent/child relationship between two DataTable objects. and the connected layer. As a result. also known as the data provider. or to manage data that is local to the application. DataRow. DataRelation.com or by calling +1 800-785-3448. DataColumn.

consisting of one or more DataTable objects. • The Connection object provides connectivity to a data source. read-only access to data. This class is serializable.0 Web Application Type 8-7 Description DataRelation object is tied to an equal number of DataColumn objects in two different DataTable objects. • The DataAdapter class provides the bridge between the DataSet object and the data source. DataView Represents a customized view of a DataTable. guarantees or conditions. and can be transported over the wire. and provided to you by QuickStart Intelligence. Command.Data.NET Framework Data Providers are designed for data manipulation. The Licensed Content is licensed "as-is. The DataAdapter class uses Command objects to run SQL commands at the data source. .com or by calling +1 800-785-3448.Common namespace. which can be used for sorting. back to the data source." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and send or retrieve parameter information. Connected Layer The ADO. Please report any unauthorized use of this content to piracy@microsoft. The . editing. DataSet This is the general container object that represents an in-memory database. This type is generally split into four different command objects when managing data—one for selecting data. or resell this content.NET connected layer provides the link between the data source and the disconnected layer. Connection. DataRow Represents a row of data in a DataTable object. Type name Type description DbCommand Represents an SQL statement or stored procedure to run against a data source. The structure of the data is made of one or more DataColumn objects. searching. • The Command object enables access to database commands. another for inserting data. and the fourth for deleting data. run stored procedures. and DataReader classes. to both load the DataSet object with data.QuickStart Intelligence Managing Data in a Microsoft® ASP. and navigation. This class is serializable. DbConnection Represents the actual connection to a data source. The connected layer includes classes such as the DataAdapter. The common base types are found within the System. It is illegal to reprint.NET 4. forwardonly. which can be used to return data. and update the data source. and it uses a connection This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. and reconcile the changes that were made to the data in the DataSet object. forward-only result sets. and zero or more DataRelation objects. redistribute. and for fast. DbDataAdapter Represents a database connection and a set of SQL commands that are used to fill the DataSet and/or DataTable. which is either a DataSet and/or a DataTable object. The following table lists the common base types provided by the connected layer. modify data. • The DataReader class provides a high-performance stream of data from the data source. and connects by using a connection string. This type is the bridge between the client-side and the server-side. a third for updating data. DataTableReader Obtains the contents of one or more DataTable objects in the form of one or more read-only. DataTable Represents one table of in-memory data. and can be transported over the wire. and the data is saved in DataRow objects. The DataRelation object allows for navigation between related data tables. filtering.

or resell this content. OdbcCommand. • With the ODBC .NET Data Provider if you want to connect to an Oracle database version 8.1.NET Data Provider. OleDbCommand.NET Data Provider. guarantees or conditions. Note: You cannot mix and match the types from the connected layer. read-only stream of rows from a data source. You can use the Oracle . which are all found in the System. use the OracleDataAdapter.com or by calling +1 800-785-3448.SqlClient namespace. and OleDbConnection classes. which are all found in the System.Data. use the SqlDataAdapter.7 or newer. . Please report any unauthorized use of this content to piracy@microsoft. • With the OLE DB . It is illegal to reprint. The Licensed Content is licensed "as-is. SqlCommand.Data.OleDb namespace.NET Framework Data Provider. and provided to you by QuickStart Intelligence. and OracleConnection classes. use the OleDbDataAdapter. which are all found in the System. SqlDataReader. The types listed in the previous table are all abstract base types that must be inherited. and SqlConnection classes. OracleDataReader.OracleClient namespace. DbDataReader Reads a forward-only. you need to use the following types for specific data source implementation: • With the SQL Server .Data.NET Framework Data Provider. use the OdbcDataAdapter.NET Framework Data Provider.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. All the types used for managing data with a single data source must come from the same .Odbc namespace. • With the Oracle . 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. Therefore. redistribute. OracleCommand.Data." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. which are all found in the System. and OdbcConnection classes. OleDbDataReader. OdbcDataReader.

each with its own protocols. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence. or resell this content. Entity Framework applications can run on any computer on which the . This is enabled by elevating the level of abstraction at which you can work when working with data. such as partitioning and indexing.NET Entity Framework Key Points The Entity Framework is a set of technologies in ADO.QuickStart Intelligence Managing Data in a Microsoft® ASP. 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.NET Framework. 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.NET that support development of data-oriented software applications. and by reducing the code that is required to create and maintain data-oriented applications. The conceptual model defines the entities and relationships in the system that is being modeled. and it is part of the Microsoft data platform. a logical model. The logical model for a relational database normalizes the entities and relationships into tables with foreign key constraints. and logic of the business problems they are solving. The physical model is refined by database administrators to improve performance. relationships. Architects and developers of data-oriented applications have struggled with the need to achieve two very different objectives: they must model the entities. Please report any unauthorized use of this content to piracy@microsoft.NET Framework 4 is installed.0 Web Application 8-9 Overview of ADO. and a physical model. redistribute. Conceptual Models A longstanding and common design pattern for data modeling is the division of the data model into three parts: a conceptual model." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions. Because the Entity Framework is a component of the . The Entity Framework enables you to work with data in the form of domain-specific objects and properties—such as customers and customer addresses—without having to be concerned with the underlying database tables and columns where this data is stored.com or by calling +1 800-785-3448.NET 4. 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. It is illegal to reprint. The physical model addresses the capabilities of a particular data engine by specifying storage details. .

Defines the conceptual model. the organization of classes closely mirrors the organization of relational database tables. This enables greater flexibility both in defining objects. and frequently these conceptual models are used as inert diagrams that are viewed and discussed in the early stages of a project. but the Customer table in a database has no comparable column. the Entity Framework maps relational tables. The Entity Framework uses these XML-based models and mapping files to transform. redistribute. the storage model. 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. The conceptual model. Mapping Objects to Data Object-oriented programming poses a challenge for interacting with data storage systems. Please report any unauthorized use of this content to piracy@microsoft. update. Defines the storage model. and then abandoned. and keys in a relational database. known as the Entity Data Model (EDM). or resell this content. Because storage models are provider-specific. The classes that are generated for a particular conceptual model derive from base classes that provide Object Services for materializing entities as objects. guarantees or conditions. create. You can use conceptual models as a tool for capturing and communicating the requirements of an application.csdl). and provided to you by QuickStart Intelligence. You can use these classes to work with the entities and relationships as objects that are related by navigation properties. Many development teams skip creating a conceptual model and begin by specifying tables. and for tracking and saving changes. A Customer class might have a property named Orders that contains a collection of instances of the Order 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. Defines the mapping between the storage and conceptual models. columns. columns. read. For example. however.com or by calling +1 800-785-3448. • Mapping specification language file (." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. to represent the customer for a sales order. which is also called the logical model. and the mapping between the two are expressed in an external specification. and foreign key constraints in logical models to entities and relationships in conceptual models. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.msl). Frequently. data classes.The storage model and mappings can change as needed. In addition. Existing solutions help to bridge this gap—which is frequently called an impedance mismatch—by only mapping object-oriented classes and properties to relational tables and columns. the EDM supports mapping entities in the conceptual model to stored procedures in the data source. or application code. an Order class uses a property that contains a reference to an instance of a Customer class. It is illegal to reprint. the fit is not perfect. The EDM tools generate extensible data classes that are based on the conceptual model. Multiple normalized tables frequently correspond to a single class. This frees applications from hard-coded dependencies on a particular data source. These classes are partial classes that can be extended with additional members that the developer adds. • Store schema definition language file (. and in optimizing the logical model.QuickStart Intelligence 8-10 Introduction to Web Development with Microsoft® Visual Studio® 2010 queries and calling stored procedures. you can work with a consistent conceptual model across various data sources.ssdl). The Licensed Content is licensed "as-is. Instead of taking this traditional approach. and delete operations against entities and relationships in the conceptual model to equivalent operations in the data source. An EDM is defined by the following three model and mapping files that have corresponding file name extensions: • Conceptual schema definition language file (. and relationships between classes are represented differently from relationships between tables. without requiring changes to the conceptual model.

EDM Tools The EDM tools are designed to help you build Entity Framework applications. and then graphically visualize and edit your conceptual model. storage model (. The EntityDataSource control is able to obtain query parameter values from page controls.NET Framework 4. and in other scenarios such as ADO. and provided to you by QuickStart Intelligence. you can automatically update your model when the underlying database changes and automatically generate object-layer code for your application. Or. and delete operations with a data source on behalf of data-bound controls on the page. update. The EDM Generator can validate an existing model. and master-detail pages.QuickStart Intelligence Managing Data in a Microsoft® ASP. and mapping (. Please report any unauthorized use of this content to piracy@microsoft. and then generate a database that supports your model." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .ssdl).NET 4. This is an XML schema written in conceptual schema definition language (CSDL). Object Services Allows programmers to interact with the conceptual model through a set of common language runtime (CLR) classes. Data Platform Components In . the . EntityDataSource Control The EntityDataSource control supports data binding scenarios based on EDM.csdl). and generate a Microsoft Visual Basic® or Microsoft Visual C#® code file that contains the object classes generated from a conceptual model (. You can extend these objects as required to support various application needs.NET parameter objects. you can graphically create a conceptual model first. cookies. The EDM specification represents data as sets of entities and relationships.NET Framework 4 includes the EDM Generator. forms with user-controlled sorting and filtering. The EntityDataSource works with editable grids. query parameters appended to the page URI.NET Data Services.csdl) file. or can be developed independently to reflect the structure of the conceptual model.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. create.NET Entity Framework provides the Data Platform components that are listed in the following table.msl) files that are used by the Entity Framework. you can create a conceptual model from an existing database. redistribute. It can also generate a Visual Basic or Visual C# code file that contains the pre-generated views for an existing model. guarantees or conditions. Object Services also provide This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. EDM data types and relationships are defined in a conceptual model. The Entity Framework uses EDM in object-relational mapping. In either case. Database generation and object-layer code generation are customizable. With the EDM tools. Together with the Entity Framework runtime. The EntityDataSource control manages the read. and other ASP. It is illegal to reprint. Query results are materialized into objects that Object Services manages.NET Framework data provider. The Licensed Content is licensed "as-is. Object Services uses the EDM to translate object queries against entity types that are represented in the conceptual model into data source-specific queries. the ADO.NET data-binding controls will find the programming surface of the EntityDataSource control similar to that of other data source controls. Data in this model supports object-relational mapping and data programmability across application boundaries. You use the conceptual model to build programmable classes that represent application data.com or by calling +1 800-785-3448. and generate the conceptual model (. Users accustomed to the design-time model of ASP. Component Description EDM A design specification that defines application data as sets of entities and relationships. This command-line utility can connect to a data source by using a data source–specific . 2-way bound drop-down list controls. or resell this content. These classes can be automatically generated from the conceptual model.

It is illegal to reprint. and query building support for Entity SQL. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. such as inheritance.NET Framework data provider that allows you to interact with an EDM. The EntityDataSource control supports data binding scenarios based on the EDM." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. identity resolution. EntityClient works with the Entity SQL language. change tracking.NET Framework data provider pattern of exposing EntityConnection and EntityCommand objects that return an EntityDataReader. and explicit relationships. or resell this content. providing flexible mapping to storage-specific data providers. EntityClient follows the . Entity SQL is a SQL dialect that contains constructs for querying in terms of higher-level modeling concepts. EntityClient A. complex types. and designers to facilitate building EDM applications. The Licensed Content is licensed "as-is. propagating object changes to database modifications. The programming surface of the EntityDataSource control is similar to other data source controls in Microsoft Visual Studio®. . loading and navigating relationships. LINQ to Entities allows developers to work against a conceptual model with a very flexible objectrelational mapping across SQL Server and third-party databases. EDM Tools The Entity Framework provides command-line tools. Please report any unauthorized use of this content to piracy@microsoft. 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. You can also use Entity SQL directly with Object Services. including services such as state management. wizards.QuickStart Intelligence 8-12 Introduction to Web Development with Microsoft® Visual Studio® 2010 Component Description infrastructure support for the Entity Framework. redistribute.com or by calling +1 800-785-3448. Entity SQL A text-based query language designed to interact with an EDM. guarantees or conditions.

Lesson Objectives After completing this lesson.NET are selecting.NET.0 Web Application 8-13 Lesson 2 Connecting to a Database You can use ADO. updating.NET to connect data in a data source (such as a database) to objects and controls in your Web Forms. redistribute.com or by calling +1 800-785-3448. guarantees or conditions. You can also use the DataAdapter object and DataReader object to establish data communication between the client and server. and provided to you by QuickStart Intelligence. and deleting data. • Enable data transport between clients and servers. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. You can establish a connection to a data source by using the Visual Studio 2010 integrated development environment (IDE). and how to create a connection to access the data that is stored in a SQL Server database. inserting. or resell this content. The Licensed Content is licensed "as-is.QuickStart Intelligence Managing Data in a Microsoft® ASP. you will be able to: • Create a connection to a data source.NET 4. . Some of the common tasks you might perform programmatically by using ADO. This lesson explains how to programmatically work with data by using ADO.

under Log on to the server pane. select a database. .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 click OK. 5. and preview the data. In the Server name box. In Server Explorer. ensure that the correct data provider and data source type is selected. If you select SQL Server authentication. The Add Connection dialog box appears. You can also create a connection programmatically. Please report any unauthorized use of this content to piracy@microsoft. when you click Change. Creating a Connection by Using Server Explorer Server Explorer—which is part of the Visual Studio 2010 IDE—allows you to connect to data sources. 6. a Change Data Source dialog box appears and enables you to choose your data source type. right-click Data Connections. create database objects. it remains open whenever the window has focus. type or select the name of the data source server. click either Use Windows Authentication or Use SQL Server Authentication. This can have an impact on availability. The Licensed Content is licensed "as-is. It is illegal to reprint. and then verify the connection at design time. In the Data source box. guarantees or conditions. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Whenever you explore the server of a data source.  To connect to a SQL Server database 1. in the Select or enter a database name list. or resell this content. 4. • In the Add Connection dialog box. In the Add Connection dialog box. explore the properties of existing objects. and then click Add Connection. provide your credentials. the connection state is open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. In the Add Connection dialog box: 3. Under Connect to a database. redistribute. and provided to you by QuickStart Intelligence. especially if the server is remote and heavily used. 2.com or by calling +1 800-785-3448.

press the F4 key to open the Properties window—if it is not already open—and select and copy the text from the Connection String property. and provided to you by QuickStart Intelligence. you can create your connection object as follows. and the credentials used for accessing the database. in which case a GridView control is added to the form with a data source control. redistribute. and use it directly in code. you need to first import the System. You can get these details by contacting your database administrator. [Visual Basic] Imports System. an initial catalog or database. Server Explorer displays the connection in Data Connections. Finally. or modify existing tables or stored procedures. as the following code examples show. [Visual Basic] Dim orderConnection As New SqlConnection() [Visual C#] SqlConnection orderConnection = new SqlConnection(). Please report any unauthorized use of this content to piracy@microsoft. [Visual Basic] orderConnection. However. have all been specified. In Server Explorer.ConnectionString = "Data Source=DatabaseServer. You can also use the connection created to drag table objects directly to a Web Form. Tip: If you have created a connection to a database by using Server Explorer.ConnectionString = "Data Source=DatabaseServer. you can create a connection object programmatically. . therefore. you may have to specify the credentials by using the User ID and Password attributes. integrated security is often used as specified.0 or newer. and then click the data connection. The Licensed Content is licensed "as-is. and then expand the Tables folder to view the tables in the database connection. Open Server Explorer.Initial Catalog=OrderDatabase.Initial Catalog=OrderDatabase.SqlClient [Visual C#] using System. If you are connecting to a SQL Server. Creating a Connection Programmatically If you want your connection to be readily available from your code.NET 4. Notice how a data source or server. that is not always the case.0 Web Application 8-15 After you create a connection. It is illegal to reprint.QuickStart Intelligence Managing Data in a Microsoft® ASP. or resell this content. The connection created by using Server Explorer is useful in scenarios where you want to design new tables. you need to set the connection string.com or by calling +1 800-785-3448. paste the copied text into your code. Next.Integrated Security=True" [Visual C#] orderConnection.SqlClient namespace as follows. For creating a connection to SQL Server 7. guarantees or conditions.Integrated Security=True". This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The connection string directs the connection object to the server and database to connect with. After you have created the connection object.Data.SqlClient.Data. After importing the namespace.Data. you can copy the connection string form there. expand the connection." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

.Dispose() [Visual C#] // Close connection orderConnection. there is no penalty in calling both methods. this is a matter of personal preference.Dispose(). [Visual Basic] orderConnection.ConnectionString = _ "Data Source=DatabaseServer. as follows.Close() ' Dispose of connection orderConnection.. and it can make your code easier to read from a maintenance point of view. you must close or dispose of it.Close() End Using [Visual C#] using (SqlConnection orderConnection = new SqlConnection()) { orderConnection.Integrated Security=True".Open(). You need to close the connection or dispose of it. [Visual Basic] Using orderConnection As New SqlConnection() orderConnection. and potentially degrade server performance—or even deny other users from accessing the server. The Licensed Content is licensed "as-is. waste valuable server resources.. which is done as follows.Open() .com or by calling +1 800-785-3448. When you are done with your connection.ConnectionString = "Data Source=DatabaseServer. Note: Because a connection object uses an unmanaged resource. you must close or dispose of the connection object after using it. because both operations will eventually dispose of both the unmanaged and managed resources. it must be opened before it can be used by the DataAdapter and/or DataReader classes. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. you will keep the connection to the server open." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and provided to you by QuickStart Intelligence. orderConnection. Please report any unauthorized use of this content to piracy@microsoft.Initial Catalog=OrderDatabase.Open() [Visual C#] orderConnection. guarantees or conditions. It is illegal to reprint.. or resell this content. Another method to ensure the disposal of a connection object is to wrap it in a Using/using statement. . [Visual Basic] ' Close connection orderConnection. Otherwise.Close(). Therefore. orderConnection. .QuickStart Intelligence 8-16 Introduction to Web Development with Microsoft® Visual Studio® 2010 After the connection object is initialized and instantiated. or is based on the coding conventions in your workplace.Open().Initial Catalog=OrderDatabase. // Dispose of connection orderConnection. However. as in the following examples. Often. garbage collection does not happen automatically.Integrated Security=True" orderConnection. redistribute.

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. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. guarantees or conditions.QuickStart Intelligence Managing Data in a Microsoft® ASP. When you use the Using/using statement. it may help make your code easier to read. it is not necessary to call the Close method explicitly. which is implicitly called when you wrap the object instantiation in a Using/using statement.NET 4. and provided to you by QuickStart Intelligence. It is illegal to reprint. redistribute. The Licensed Content is licensed "as-is.0 Web Application } 8-17 orderConnection. as is done by the Dispose method. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.Close(). However.com or by calling +1 800-785-3448.

and DELETE operations. However. Of these four properties. and uses command objects to issue the commands for managing the data. Execute permission can be limited to the stored procedures.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. insert. or resell this content. The DataAdapter object has four command object–related properties: • SelectCommand. • InsertCommand. and provided to you by QuickStart Intelligence. whenever new data is created on the client. • DeleteCommand. an exception is thrown if the corresponding property has not been set. UPDATE. because the actual SQL code for performing the action is located on the server. Issues an SQL UPDATE statement for updating the data in the data source whenever changes are made on the client. . You can use stored procedures to reduce the amount of code that is required to perform SELECT. or can be calls to stored procedures in the database. whenever data is deleted on the client. if you only want to retrieve data from the database and not manipulate it in any way. • UpdateCommand. guarantees or conditions. Issues an SQL INSERT statement for inserting new data on the server. INSERT. It is illegal to reprint.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The Licensed Content is licensed "as-is. then the DataReader object is your best choice. but if you try to update. This is where the DataAdapter object is helpful. DataAdapter The DataAdapter object uses the Connection object to connect to a database. Each of these properties can have SQL statements. You also get an extra layer of security. only the SelectCommand must be set." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you need an object to facilitate the transport and synchronization of data between the client and the server. redistribute. Please report any unauthorized use of this content to piracy@microsoft. Issues an SQL SELECT statement for retrieving data from the data source. or delete data. Issues an SQL DELETE statement for deleting data on the server.

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. you can create the SqlDataAdapter object as shown in the following code examples. SqlCommand insertCommand = new SqlCommand("INSERT INTO Orders (CustomerID.SqlClient namespace.com or by calling +1 800-785-3448. orderConnection). ModifiedBy=@ModifiedBy WHERE ID=@ID".DeleteCommand ordersDataAdapter. and provided to you by QuickStart Intelligence. CreatedDate. [Visual Basic] ' Declare and instantiate data adapter Dim ordersDataAdapter As New SqlDataAdapter() [Visual C#] // Declare and instantiate data adapter SqlDataAdapter ordersDataAdapter = new SqlDataAdapter(). Please report any unauthorized use of this content to piracy@microsoft. InvoiceDate. CreatedDate.UpdateCommand = = = = selectCommand. so that it fits into an overall concrete solution. The Licensed Content is licensed "as-is. orderConnection). @CreatedBy)". deleteCommand. @CreatedDate. CreatedBy) VALUES(@CustomerID. ModifiedBy=@ModifiedBy WHERE ID=@ID". After importing the namespace. guarantees or conditions. @InvoiceDate.InsertCommand ordersDataAdapter. you first need to import the System.SelectCommand ordersDataAdapter. For creating a DataAdapter object to work with a SQL Server version 7. // Assign command objects ordersDataAdapter. orderConnection) ' Assign command objects ordersDataAdapter. orderConnection). insertCommand. [Visual Basic] ' Declare and instantiate command objects Dim selectCommand As New SqlCommand("SELECT * FROM Orders". redistribute.UpdateCommand = = = = selectCommand deleteCommand insertCommand updateCommand [Visual C#] // Declare and instantiate command objects SqlCommand selectCommand = new SqlCommand("SELECT * FROM Orders". CreatedBy) VALUES(@CustomerID. orderConnection) Dim insertCommand As New SqlCommand("INSERT INTO Orders (CustomerID. orderConnection). InvoiceDate=@InvoiceDate." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you can set the command properties as follows. orderConnection) Dim updateCommand As New SqlCommand("UPDATE Orders SET CustomerID=@CustomerID. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Data. @CreatedDate.SelectCommand ordersDataAdapter. orderConnection) Dim deleteCommand As New SqlCommand("DELETE FROM Orders WHERE ID=@ID".0 Web Application 8-19 Creating a DataAdapter Programmatically If you want your data adapter to be readily available from your code.0 or newer database. It is illegal to reprint. InvoiceDate=@InvoiceDate. you can create a DataAdapter object programmatically. or resell this content.NET 4.QuickStart Intelligence Managing Data in a Microsoft® ASP. "ModifiedDate=@ModifiedDate. InvoiceDate. updateCommand.DeleteCommand ordersDataAdapter. SqlCommand deleteCommand = new SqlCommand("DELETE FROM Orders WHERE ID=@ID". SqlCommand updateCommand = new SqlCommand("UPDATE Orders SET CustomerID=@CustomerID. When you instantiate the data adapter. @CreatedBy)". . "ModifiedDate=@ModifiedDate. @InvoiceDate.InsertCommand ordersDataAdapter.

The updateCommand object also makes use of the @ID parameter to identify the correct row to update (WHERE ID=@ID). and it can be assigned a value at a later stage.Parameters. "InvoiceDate") .com or by calling +1 800-785-3448. 0. you make your code more readable.QuickStart Intelligence 8-20 Introduction to Web Development with Microsoft® Visual Studio® 2010 When setting the command properties of the data adapter object. guarantees or conditions.UniqueIdentifier.SmallDateTime. Please report any unauthorized use of this content to piracy@microsoft. SqlParameter updateIDParameter = new SqlParameter("@ID". although with a different syntax... 0. 0. . "InvoiceDate"). 0. it assigns values to the various columns by using named parameters (SET CustomerID=@CustomerID. Dim insertInvoiceDateParameter As New SqlParameter("@InvoiceDate". // Assign parameters to command object deleteCommand.UniqueIdentifier. In addition. At this stage. [Visual Basic] ' Declare and instantiate parameter objects Dim deleteIDParameter As New SqlParameter("@ID". 0.SmallDateTime. 0. 0.). ' Assign parameters to command object deleteCommand...UniqueIdentifier. . "InvoiceDate") . It is illegal to reprint.. insertCommand." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SqlParameter insertInvoiceDateParameter = new SqlParameter("@InvoiceDate". "ID") Dim updateInvoiceDateParameter As New SqlParameter("@InvoiceDate". SqlDbType. SqlDbType. Using this method. The @ID part is also known as a named parameter. SqlDbType. The deleteCommand object deletes all the rows that contain a value of @ID in the ID column.UniqueIdentifier.SmallDateTime..SmallDateTime.Add(updateIDParameter) . "ID"). SqlDbType.Add(deleteIDParameter). you can easily assign parameters to Command objects where needed. You can assign the parameter values as follows.. you have declared and instantiated the Command object.. SqlDbType. "ID").Parameters. . Invoicedate=@Invoicedate.Add(insertInvoiceDateParameter) .. "ID") Dim updateIDParameter As New SqlParameter("@ID". In the code.Add(deleteIDParameter) updateCommand..Parameters.. 0. "InvoiceDate"). redistribute..Parameters.. or resell this content. The insertCommand object performs the same function as the updateCommand. if you create the Command object in a separate step and then assign it to the command properties. SqlParameter updateInvoiceDateParameter = new SqlParameter("@InvoiceDate". The Licensed Content is licensed "as-is. . SqlDbType. only one row with that value will be found. and provided to you by QuickStart Intelligence. SqlDbType. so when a value is assigned to the @ID parameter. [Visual C#] // Declare and instantiate parameter objects SqlParameter deleteIDParameter = new SqlParameter("@ID". the selectCommand object uses the SQL SELECT statement to retrieve all the rows from the Orders table. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Note: The ID column in the Orders table is unique.. SqlDbType.

ExecuteReader() ' Any more rows? While ordersDataReader.ExecuteReader().NET 4.0 Web Application 8-21 updateCommand. It is illegal to reprint." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.. . the SqlConnection object that is associated with the SqlCommand object must be open. After importing the namespace. If the cursor is not located in a valid row. Note: The SqlDbType enumeration used to specify the data type for the various parameters is part of the System.Add(insertInvoiceDateParameter). an exception is thrown. Using this method. or resell this content. [Visual Basic] Dim ordersDataReader As SqlDataReader = selectCommand. you can create your SqlDataReader object by using the ExecuteReader method of the SqlCommand object.com or by calling +1 800-785-3448.Close() [Visual C#] SqlDataReader ordersDataReader = selectCommand. you make your code more readable. the System. When setting the parameter properties of the Command objects. . you should create a DataReader object.SqlClient namespace. Creating a DataReader Programmatically If you want to create a fast. // Any more rows? while (ordersDataReader. and provided to you by QuickStart Intelligence. redistribute. 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.. For creating a DataReader object to work with SQL Server 7. therefore. you first need to import the System. and the source column name. you need to call the Read method.. read-only. the size. you can specify the data type.Data namespace. . it indicates that there are no more rows in the DataReader object. Notice how the SqlCommand object selectCommand is used to create the DataReader object. insertCommand.Add(updateIDParameter).Data namespace must be imported to your code files. as the following code examples illustrate. Notice that some parameters are duplicated because they are assigned to more than one Command object.QuickStart Intelligence Managing Data in a Microsoft® ASP.Parameters. Please report any unauthorized use of this content to piracy@microsoft..Read()) { //. To read any row from the DataReader object.Parameters.0 or newer.Close(). When the ExecuteReader method is called.Data. The Licensed Content is licensed "as-is. } // Always call Close when done ordersDataReader.Read() . which returns a Boolean value indicating if the cursor is located at a valid row. which selects all the rows from the Orders table... End While ' Always call Close when done ordersDataReader. otherwise.. if you create the Parameter objects in a separate step and then add them to the command parameters. forward-only stream of rows from your data source. the parameter name. So. guarantees or conditions.. You can assign a parameter object only to a single Command object.

. It is illegal to reprint. To retrieve data from a single database table without creating the various command objects manually. for a DataAdapter object—while it is being used by the DataReader object. (Though you can close it and re-open it. You cannot use the connection object—for example. you can use the CommandBuilder class. guarantees or conditions. it is an expensive operation in terms of server resources. and provided to you by QuickStart Intelligence. 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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. until you close the DataReader object. 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.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. ensure you call the Close method on the DataReader object to allow the connection object to be reused for other purposes. The Licensed Content is licensed "as-is. or resell this content. Please report any unauthorized use of this content to piracy@microsoft.) Finally. it will monopolize the connection associated with the command object that is used for creating the DataReader object.com or by calling +1 800-785-3448. redistribute. Note: When you open a DataReader object.

you do not have to maintain a DataSet object. It is illegal to reprint. or resell this content. • Manipulate data by using the DataAdapter object. 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. or accessing a password. such as displaying a single set of data directly to the user. Please report any unauthorized use of this content to piracy@microsoft. For such operations. The DataSet object provides a disconnected copy of all or some of the data in the database. The Licensed Content is licensed "as-is.NET. you can use a DataReader object.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. • Bind data to server controls by using the Visual Studio 2010 IDE." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. However. Lesson Objectives After completing this lesson. you can use a DataSet object. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com or by calling +1 800-785-3448. you will be able to: • Retrieve simple data by using the DataReader class. redistribute. and provided to you by QuickStart Intelligence. Instead. . This might be for the presentation of the data. you need a method to manage the data on the client.QuickStart Intelligence Managing Data in a Microsoft® ASP. This lesson explains how to use the DataSet and DataReader objects to support the local data storage and data manipulation requirements of Web Forms. For longrunning Web applications. • Retrieve non-simple data by using the DataSet class and DataTable class. you often perform basic operations. guarantees or conditions.NET 4.

SELECT * FROM Customers Note that the two SELECT statements are separated by a semicolon. If you want to retrieve data from the database that will only be displayed to the users. you can use the NextResult method to move to the next result set. execute the command. or resell this content. It is illegal to reprint. Please report any unauthorized use of this content to piracy@microsoft. For example. and provided to you by QuickStart Intelligence.NET Framework Data Provider. [Visual Basic] ' Declare and instantiate connection Dim orderConnection As New SqlConnection() ' Initialize connection orderConnection." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. redistribute. You can then use the Read method of the DataReader object to access the result set.com or by calling +1 800-785-3448. If the SELECT command returns multiple result sets. and then close the connection after processing the results.. orderConnection) This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . and then have the results returned in a DataReader object.." ' Declare and instantiate command object Dim selectCommand As New SqlCommand("SELECT * FROM Orders". store the result in the ordersDataReader object.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 value—such as a password or the number of rows from the database—you can use the ExecuteScalar method of the SqlCommand class. Retrieving Read-Only Data You can use the Command object to call the ExecuteReader method.ConnectionString = ". guarantees or conditions. the DataReader class is a good choice as a container for the retrieved data. the following SelectCommand object is used with the SQL Server . The Licensed Content is licensed "as-is. The following code examples create and open a connection. SELECT * FROM Orders. send the SELECT command to the data source. Multiple result sets are often the result of multiple SELECT statements.

The Licensed Content is licensed "as-is.0 Web Application 8-25 ' Open connection orderConnection. starting with the first row the first time it is called. } } // Close datareader ordersDataReader.. and provided to you by QuickStart Intelligence.HasRows) { . .NET 4. If the Read method returns false.Close() ' Close connection orderConnection. // Declare.Read() . Else ' Any more rows? While ordersDataReader.". instantiate and initialize datareader Dim ordersDataReader As SqlDataReader = _ selectCommand. redistribute.Read()) { . you can inform the user or perform any other appropriate action. the rows are looped through by using the Read method. guarantees or conditions. If the HasRows property is true...Open() ' Declare. The HasRows property of the DataReader object verifies if any rows have been returned.. If no rows have been returned. End While End If ' Close datareader ordersDataReader. } else { // Any more rows? while (ordersDataReader.Close(). // Declare and instantiate command objects SqlCommand selectCommand = new SqlCommand("SELECT * FROM Orders"...Close(). It is illegal to reprint.. orderConnection).. // Open connection orderConnection. // Any rows returned? if (!ordersDataReader." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.ExecuteReader().ConnectionString = ".ExecuteReader() ' Any rows returned? If Not ordersDataReader.. instantiate and initialize datareader SqlDataReader ordersDataReader = selectCommand.HasRows Then ' . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. there are no more rows.Close() [Visual C#] // Declare and instantiate connection SqlConnection orderConnection = new SqlConnection().QuickStart Intelligence Managing Data in a Microsoft® ASP.com or by calling +1 800-785-3448. or resell this content. an exception is thrown.. // Close connection orderConnection. // Initialize connection orderConnection. If you do.Open(). and you can no longer access the data in the DataReader object. which advances to the next row. Please report any unauthorized use of this content to piracy@microsoft.

. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. or resell this content. orderConnection).Open() ' Get scalar value Dim name As String = CType(selectCommand. orderConnection) ' Open connection orderConnection.Open(). and provided to you by QuickStart Intelligence. String) ' Close connection orderConnection. // Close connection orderConnection. guarantees or conditions. .com or by calling +1 800-785-3448. However. [Visual Basic] ' Declare and instantiate command object Dim selectCommand As New SqlCommand("SELECT ID FROM Orders WHERE CreatedBy='Weber'". The Licensed Content is licensed "as-is.ExecuteScalar(). // Initialize connection orderConnection. The following method returns a single scalar value.Close(). then only the first entry found will be returned.. // Declare and instantiate command objects SqlCommand selectCommand = new SqlCommand("SELECT ID FROM Orders WHERE CreatedBy='Weber'". you might need to cast the return value before you can use it. Therefore. // Open connection orderConnection.Close() [Visual C#] // Declare and instantiate connection SqlConnection orderConnection = new SqlConnection().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. // Get scalar value string name = (string) selectCommand. If more than a single field is returned by the SELECT statement—for example.Object. an entire row—then the ExecuteScalar method returns the first column of this row. It is illegal to reprint.ExecuteScalar(). The ExecuteScalar method returns the value of type System.ConnectionString = ". a single entry with the name “Weber.” is returned.". you can simply use the ExecuteScalar method. such as the value returned by this SELECT statement. if more than one customer with the name “Weber” is found." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The following code examples demonstrate the ExecuteScalar method. The ID that is returned depends on the manner in which the rows are sorted in the Orders table. Please report any unauthorized use of this content to piracy@microsoft. SELECT ID FROM Orders WHERE CreatedBy=’Weber’ If a single customer with the name “Weber” is found.

or resell this content.0 Web Application 8-27 Retrieving Non-Simple Data Key Points If you need to retrieve non-simple data—such as the content of an entire table or a subset of rows from a table—the DataSet or DataTable classes are excellent choices in a disconnected scenario. you can populate the DataSet object by using a DataAdapter object. You can call the Fill method on the DataAdapter object. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. You can enforce data integrity in a DataSet class by using constraints. It is illegal to reprint. where the first constructor does not take any parameters. you can use one of two constructors. The schema of the Orders table in the database is automatically copied to the Orders DataTable object. guarantees or conditions. You can use the DataSet class to store local data—which you add manually—or you can import XML documents. The following code examples create and populate the Orders table. Populating the DataSet After you have created a DataSet object. The Licensed Content is licensed "as-is. and the second constructor takes the name of the dataset.NET 4. Working with the DataSet Programmatically To create a DataSet object. . redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft.QuickStart Intelligence Managing Data in a Microsoft® ASP. You can also use the DataSet class for storing a copy or cache of the data—or a subset thereof—in a data source on a different server. and then specify the name of the DataTable object that is created for you within the DataSet. [Visual Basic] Dim ordersDataSet As New DataSet("OrdersDataSet") [Visual C#] DataSet ordersDataSet = new DataSet("OrdersDataSet"). and provided to you by QuickStart Intelligence.com or by calling +1 800-785-3448. The following code examples show how you can declare and instantiate a DataSet.

Tables["Orders"].Tables[0]. The DataRow and DataColumn classes are primary components of a DataTable class. and the DataRow objects contain the actual data. or resell this content.ColumnName) Next [Visual C#] This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. The following code examples retrieve the column names from the DataTable object named Orders. The Rows property of the DataTable object provides programmatic access to the DataRowCollection. preferably with the name of the table in the database. The Licensed Content is licensed "as-is. redistribute. which is accessed by using the SelectCommand property of the DataAdapter object. each DataSet object consists of one or more DataTable objects that you can refer to by name or by ordinal position. because you can use this name when accessing the data later.com or by calling +1 800-785-3448.QuickStart Intelligence 8-28 Introduction to Web Development with Microsoft® Visual Studio® 2010 [Visual Basic] ordersDataAdapter.Write(col.Tables(0) [Visual C#] // Access Orders table by name ordersDataSet. where the DataColumn objects make up the structure of the DataTable. and provided to you by QuickStart Intelligence.Fill method uses the DataReader object implicitly to return the column names and types that are used to create the tables in the DataSet. The Fill method runs the SQL statement that is contained in the Command object. The DataAdapter. guarantees or conditions. It is illegal to reprint.Tables("Orders"). "Orders").Tables("Orders") ' Access Orders table by ordinal position ordersDataSet. "Orders") [Visual C#] ordersDataAdapter. Please report any unauthorized use of this content to piracy@microsoft.Fill(ordersDataSet. Accessing a DataTable After you have placed data in a DataSet object. and the data to populate the rows of the tables in the DataSet. [Visual Basic] ' Access Orders table by name ordersDataSet. You can use a DataRow object and its properties and methods to retrieve and evaluate the values in a DataTable object. // Access Orders table by ordinal position ordersDataSet. [Visual Basic] For Each col As DataColumn In ordersDataSet.Columns Response. The DataRowCollection represents the actual DataRow objects that are in the DataTable object. . otherwise Fill uses the existing DataSet schema. and the DataColumnCollection contains the DataColumn objects that define the schema of the DataTable object. Tables and columns are only created if they do not already exist. As the following code examples illustrate. The Columns property of the DataTable object provides programmatic access to the DataColumnCollection. You should always name the table that is being created and populated." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Fill(ordersDataSet. you can programmatically access the data. which is contained in the ordersDataSet object.

Another option is to use the Find method of the DataRowCollection object that is exposed by the Rows property.FillSchema(ordersDataSet. making it difficult to know exactly which row to access.Count.Columns. 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. and when you find the correct row. guarantees or conditions.Rows." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. While the column can be accessed because it is implied from the data source. ordersDataSet. SchemaType. redistribute.Tables("Orders"). "Orders") ' Get the data row Dim ordersDataRow As DataRow = ordersDataSet.Tables("Orders"). you should not use the index to locate a row in the DataTable object. to locate one or more rows by using the primary key as follows.Count ordersDataSet. [Visual Basic] ordersDataSet. or resell this content. you must call the FillSchema method first.Rows. You need to call the FillSchema method to apply the full schema to the Orders DataTable object.Rows. "Orders").Count. and provided to you by QuickStart Intelligence. you can retrieve the values from the various columns.Rows.FillSchema(ordersDataSet. The following code examples illustrate this. Notice how a call to the FillSchema method of the DataAdapter object is made prior to calling the Find method of the DataRowCollection object. }.Write(col.Tables["Orders"]. 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. Please report any unauthorized use of this content to piracy@microsoft.Source.Tables["Orders"]. The Licensed Content is licensed "as-is. [Visual Basic] ' Apply the full schema from the data source ordersDataAdapter.Find("a05c7f53-9c4e-de11-aa78-0003ffa70544") [Visual C#] // Apply the full schema from the data source ordersDataAdapter. // Get the data row DataRow ordersDataRow = ordersDataSet. It is illegal to reprint.Tables["Orders"]. .Tables["Orders"].0 Web Application 8-29 foreach (DataColumn col in ordersDataSet. If you want to apply a primary key. or a row can be marked as deleted.Tables("Orders").Find("a05c7f53-9c4e-de11-aa78-0003ffa70544").NET 4. because only the data type and name is applied when using the Fill method of the DataAdapter object.QuickStart Intelligence Managing Data in a Microsoft® ASP. because you cannot be sure that you are accessing the correct row. SchemaType.ColumnName).Source.com or by calling +1 800-785-3448.Count [Visual C#] ordersDataSet.Columns) { Response.Columns. Generally. the rows can be sorted in different ways. You can loop through the rows.

Tables("Orders"). redistribute. newOrderDataRow["ID"] = Guid. or resell this content. newOrderDataRow["CustomerID"] = currentCustomer.NewGuid(). Manipulating Data by Using a DataAdapter Object The following code examples illustrate how you can insert a new row of data locally.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 database—either locally or directly on the server—you can use the DataAdapter object.NewRow() newOrderDataRow("ID") = Guid. "Orders") [Visual C#] // Create new row locally DataRow newOrderDataRow = ordersDataSet.NewRow().ID newOrderDataRow("InvoiceDate") = DateTime. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Now newOrderDataRow("CreatedBy") = currentUser.NewGuid() newOrderDataRow("CustomerID") = currentCustomer.ID.Now. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence.Now.Now newOrderDataRow("CreatedDate") = DateTime.Tables("Orders"). newOrderDataRow["InvoiceDate"] = DateTime. newOrderDataRow["CreatedDate"] = DateTime.Rows.Name.Name ' Insert new row locally ordersDataSet. newOrderDataRow["CreatedBy"] = currentUser. [Visual Basic] ' Create new row locally Dim newOrderDataRow As DataRow = ordersDataSet. It is illegal to reprint.Tables["Orders"]. You can also access the database commands and manipulate data by using the Command object." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Update(ordersDataSet.com or by calling +1 800-785-3448.Add(newOrderDataRow) ' Update data source ordersDataAdapter. guarantees or conditions. .

Rows.Name [Visual C#] // Find row DataRow orderDataRow = ordersDataSet.Rows. redistribute.Delete().Tables["Orders"].Add(newOrderDataRow). Please report any unauthorized use of this content to piracy@microsoft.Tables("Orders").Find("20389eb1-f24f-de11-aa78-0003ffa70544").NET 4. UpdateCommand.Rows.Delete() [Visual C#] // Find row DataRow orderDataRow = ordersDataSet. After manipulating the data locally. [Visual Basic] ' Find row Dim orderDataRow As DataRow = _ ordersDataSet.Name. It is illegal to reprint. The Licensed Content is licensed "as-is. orderDataRow["ModifiedBy"] = currentUser. you can do so.Tables("Orders"). or resell this content.Find("a05c7f53-9c4e-de11-aa78-0003ffa70544"). The following code examples illustrate this.Rows.QuickStart Intelligence Managing Data in a Microsoft® ASP. // Delete row locally orderDataRow. you can do so. If you want to delete the existing data locally." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Now.com or by calling +1 800-785-3448. you may need to send it to the server. // Update row locally orderDataRow["ModifiedDate"] = DateTime.Find("a05c7f53-9c4e-de11-aa78-0003ffa70544") ' Update row locally orderDataRow("ModifiedDate") = DateTime. as demonstrated in the following code examples. [Visual Basic] ' Find row Dim orderDataRow As DataRow = _ ordersDataSet.Now orderDataRow("ModifiedBy") = currentUser. guarantees or conditions. as demonstrated in the follow code examples.Update(ordersDataSet. "Orders") This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Tables["Orders"]. [Visual Basic] ' Update data source ordersDataAdapter. and provided to you by QuickStart Intelligence. .0 Web Application 8-31 // Insert new row locally ordersDataSet. Note: The example code in this topic assumes that you have set up the Command objects for the InsertCommand. and DeleteCommand properties of the DataAdapter object.Find("20389eb1-f24f-de11-aa78-0003ffa70544") ' Delete row locally orderDataRow.Tables["Orders"]. If you want to modify the existing data locally.Rows.

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. or resell this content.QuickStart Intelligence 8-32 Introduction to Web Development with Microsoft® Visual Studio® 2010 [Visual C#] // Update data source ordersDataAdapter. "Orders"). redistribute. guarantees or conditions. It is illegal to reprint.Update(ordersDataSet. Please report any unauthorized use of this content to piracy@microsoft. . The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448.

or resell this content." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. and edit the items that are displayed in the control. [CreatedBy]. @ModifiedBy)" ProviderName="<%$ ConnectionStrings:OrderConnectionString1. you can use Server Explorer to add data directly to a Web Form. [InvoiceDate] = @InvoiceDate. Enables you to use a server control to access data that is located in a relational database. guarantees or conditions.. [ModifiedDate].0 Web Application 8-33 Data to Server Controls by Using the IDE Key Points To effectively manage data. [InvoiceDate]. @ModifiedDate. sort. [CustomerID]. a user can select. • SqlDataSource control. redistribute. Please report any unauthorized use of this content to piracy@microsoft. [ModifiedBy] FROM [Orders]" UpdateCommand="UPDATE [Orders] SET [CustomerID] = @CustomerID. [CreatedDate]. [InvoiceDate]. Visual Studio 2010 allows you to administratively create a database connection. [ModifiedDate].ProviderName %>" SelectCommand="SELECT [ID]. and each row represents a record. and easily link the GridView control to the database.com or by calling +1 800-785-3448. [CreatedBy] = @CreatedBy. Displays the values of a data source in a table where each column represents a field. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. [CreatedDate] = @CreatedDate. [CreatedBy]. [CustomerID]. if you drag a table to the Text Editor in Design view.. [ModifiedDate] = @ModifiedDate. [ModifiedBy]) VALUES (@ID. [CreatedDate]. @CreatedBy. [ModifiedBy] = @ModifiedBy WHERE [ID] = @ID"> .NET 4. Displaying Data on a Web Form After you create a connection to a database. <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:OrderConnectionString1 %>" DeleteCommand="DELETE FROM [Orders] WHERE [ID] = @ID" InsertCommand="INSERT INTO [Orders] ([ID]. to and create a GridView server control on a Web Form. @CustomerID. . It is illegal to reprint. Visual Studio 2010 automatically sets the ConnectionString and Command properties of the SqlDataSource. Visual Studio 2010 creates a GridView control and a SqlDataSource control by default: • GridView control. In Server Explorer. and provided to you by QuickStart Intelligence. @CreatedDate. as shown in the following code. You can then add a SqlDataSource object to the Web Form. such as SQL Server databases.QuickStart Intelligence Managing Data in a Microsoft® ASP. @InvoiceDate. Optionally.

However. including LinqDataSource. guarantees or conditions. Enables sorting in the control. • AllowSorting. The GridView control includes the following main properties. • PageSize. You can set the properties in both the Properties window and the Design view. you can view the Web Form in a browser to display the data from the data source. Please report any unauthorized use of this content to piracy@microsoft. Enables paging in the control. and provided to you by QuickStart Intelligence. you can use other server controls also. The name of the . and sort data on a Web Form by using little or no code.Data. which is referred to in the previous markup. edit. or resell this content. The connection string to connect to the database. • ProviderName. <configuration> ..com or by calling +1 800-785-3448. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.Integrated Security=True" providerName="System. such as Visual Basic and Visual C#. Displays the set of columns to be shown in the control. The SqlDataSource control includes the following main properties: • ConnectionString.config file. redistribute. When you select a SqlDataSource control. you can use the Properties window to set its properties. It is illegal to reprint. The number of rows from the data source to display per page.SqlClient" /> </connectionStrings> ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The SqlDataSource control is also the default when dragging a table from Server Explorer onto a Web Form. You can also display.NET Framework programming languages. LINQ simplifies the interaction between object-oriented This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 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. • Columns. </configuration> The DataSourceID property of the GridView control is also set to the name of the SqlDataSource control.. The Licensed Content is licensed "as-is. <appSettings/> <connectionStrings> <add name="OrderConnectionString1" connectionString="Data Source=DatabaseServer.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. LINQ provides a unified programming model for querying and updating data from different types of data sources.NET Data Provider assembly. Displays the control ID of a data source. and extends data capabilities directly into the . which can also be set in the Properties window: • AllowPaging...NET data-source control architecture. You can use the SqlDataSource control to connect to a database with little or no code. . The LinqDataSource control exposes LINQ to Web developers through the ASP. • DataSourceID.Initial Catalog=OrderDatabase. The following code shows how the DataSourceID property is set to the SqlDataSource control."> At this stage.

guarantees or conditions.NET 4. The Licensed Content is licensed "as-is. redistribute.QuickStart Intelligence Managing Data in a Microsoft® ASP. Please report any unauthorized use of this content to piracy@microsoft.0 Web Application 8-35 programming and relational data by applying the principles of object-oriented programming to relational data.com or by calling +1 800-785-3448. 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. ." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. It is illegal to reprint. and provided to you by QuickStart Intelligence.

Lab Setup For this lab. If you are using Visual Basic as your programming language.com or by calling +1 800-785-3448. you will use the available virtual machine environment. or resell this content. • Bind a user control to the data source." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. and verify the changes that are made to the database. If you are using Visual C# as your programming language. refer to the steps provided in Section 2 of the lab document. Before you begin the lab. Introduction In this lab. • Modify the source database.QuickStart Intelligence 8-36 Introduction to Web Development with Microsoft® Visual Studio® 2010 Lab: Managing Data in an ASP. The Licensed Content is licensed "as-is. . Objectives After completing this lab.NET 4. guarantees or conditions. you will modify the source database. and verify the changes. It is illegal to reprint. you will connect the ASP. refer to the steps provided in the Section 1 of the lab document.NET Web application to a SQL Server database by using the server control. you will be able to: • Connect to a SQL Server database by using the SqlDataSource control. you must: • Start the NYC-CL1 virtual machine. and then bind the user control in the application to a data source. redistribute. and provided to you by QuickStart Intelligence. 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.0 Web Application Note: You can perform tasks in this lab either by using the Visual Basic or Visual C# programming language. In addition. Please report any unauthorized use of this content to piracy@microsoft.

In addition. The Licensed Content is licensed "as-is. which is a large organization with a global customer base. Please report any unauthorized use of this content to piracy@microsoft. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. . To perform this task." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. you need to add and configure a data source control to the user control. To minimize the chances of creating error-prone code when accessing the data in the database. and provided to you by QuickStart Intelligence. you need to add and bind a server control to the user control for displaying specific data from the database.0 Web Application 8-37 Lab Scenario You are a developer at Contoso. Ltd. Your organization uses a Web site to manage its customer information. You are responsible for managing the user information in your organization. redistribute. or resell this content. It is illegal to reprint.NET 4. you need to add functionality for simple data access tasks to retrieve data in a short time without using a lot of code.QuickStart Intelligence Managing Data in a Microsoft® ASP.com or by calling +1 800-785-3448. guarantees or conditions.

• Configure the SELECT statement to include the ID and Name columns from the Countries table. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Rename the SqlDataSource control as CountriesSqlDataSource. It is illegal to reprint. D:\LabFiles\Starter\M8\CustomerManagement.  Task 2: Add a SQL Server 2008 Express Database • Add a new database folder named App_Data. 3. guarantees or conditions." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. Open an existing ASP. redistribute.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.  Task 4: Configure a data source control • In Design view. and provided to you by QuickStart Intelligence.mdf. • Save the Customer user control. Pa$$w0rd. and an existing database to the database folder. Please report any unauthorized use of this content to piracy@microsoft. 2. connect to the CustomerManagement. • Open Microsoft Visual Studio 2010. 4. Add a data source control to the user control. • Save the Customer user control. and check whether you get the correct data from the Countries table. The Licensed Content is licensed "as-is. • Test the query.com or by calling +1 800-785-3448.  Task 3: Add a data control source to the user control • Open the Customer user control in Design view. Note: Ensure that the returned rows include the values for the ID and Name columns for various countries.mdf database.NET Web project • Log on to 10267A-GEN-DEV as Student. Configure a data source control. Add a SQL Server 2008 Express Database. with the CountriesSqlDataSource control selected.NET Web project.  Task 1: Open an existing ASP. • Add a SqlDataSource control to the user control to connect to an SQL Server database. with the password. • Open the CustomerManagement solution from the D:\Labfiles\Starter\M8\VB folder. • Open the Configure Data Source Wizard. display the Smart Tag. . and then create a new connection string named CustomerManagementConnectionString.

CustomerCityTextBox.Text. guarantees or conditions. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Text. Integer. It is illegal to reprint. Bind the DropDownList control to a data source. CustomerWebAddressTextBox. .Text.QuickStart Intelligence Managing Data in a Microsoft® ASP. CustomerAddressTextBox.NET 4.Now.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. New Guid(CustomerCountryDropDownList.Text. CustomerEmailAddressTextBox. DateTime. 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.Text.Text. and provided to you by QuickStart Intelligence. redistribute. "". Note: Notice the Build succeeded message in the Build pane of the Output window.Text. DataTextField="Name" • Build the user control. CustomerNewsSubscriberCheckBox. Nothing.Parse(CustomerCreditLimitTextBox.com or by calling +1 800-785-3448. CustomerZipCodeTextBox. or resell this content.  Task 2: Pass the values to the Customer object • Open the Customer user control in the Code view. • Locate the markup for the CustomerCountryDropDownList control. CustomerPhoneTextBox. Please report any unauthorized use of this content to piracy@microsoft. <asp:ListItem>USA</asp:ListItem> • Bind the CustomerCountryDropDownList control to the CountriesSqlDataSource control by using the DataSourceID attribute. and fix any errors.Text. 2. and fix any errors. • 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. CustomerLastNameTextBox.Customer( Nothing.Text). • Remove the static ListItem element from the CustomerCountryDropDownList control. Pass the values to the Customer object. ' Instantiate new Customer object with user input currentCustomer = New CustomerManagementEntities. CustomerStateTextBox.SelectedValue).  Task 1: Bind the DropDownList control to a data source • Open the Customer user control in Source view. The Licensed Content is licensed "as-is. CustomerFirstNameTextBox.Text. "") • Build the user control.Checked.

Add the ListView control to the Web Form. .  Task 1: Create the Customers Web Form • Create the Customers Web Form based on the master page. Please report any unauthorized use of this content to piracy@microsoft.aspx Web Form. 5. • Rename the ListView control as CustomersListView. Site. Add the SqlDataSource control to the Web Form. and ensure that it is possible to manipulate the data in the data source. redistribute. • Open the Customers Web Form in the Design view. Configure the SqlDataSource control. • Close Windows® Internet Explorer®. • Rename the SqlDataSource control as CustomersSqlDataSource. or resell this content. 3. and use optimistic concurrency. • Save the Customers Web Form. Update sitemap to enable view all customers. 4. Create the Customers Web Form. • Save the Customers Web Form. display the Smart Tag. 6. • Enable paging in the CustomersListView control. • Configure the SELECT statement to include all the columns from the Customers table.  Task 2: Add the SqlDataSource control to the Web Form • Add the SqlDataSource control to the Customers. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. guarantees or conditions. • View the Customers Web Form in the browser. • Bind the CustomersListView control to the CustomersSqlDataSource control by using the Smart Tag. with the CustomersSqlDataSource control selected. Create a customer and verify the Data Source. 7. and provided to you by QuickStart Intelligence. • Build the user control.  Task 5: Add code to manually save a customer to a data source • Open the Customer user control in the Code view.  Task 3: Configure the SqlDataSource control • In Design view. 2.  Task 4: Add the ListView control to the Web Form • Add the ListView control to the Customers Web Form. • Open the Configure Data Source Wizard. It is illegal to reprint.master. The Licensed Content is licensed "as-is. • Save the Customers Web Form. and fix any errors. Add code to manually save a customer to a data source." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.com or by calling +1 800-785-3448. • Select the CustomerManagementConnectionString connection string for the CustomersSqlDataSource control.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 and instantiate connection Using customerManagementConnection As New SqlConnection() ' Initialize connection string from web. Please report any unauthorized use of this content to piracy@microsoft. @WebAddress. @Phone. or resell this content. System. System. . @ZipCode.CreditLimit = 50000 End Sub • Remove the assignment of the value 50000 to the CreditLimit property.Click ' Did page validation succeed? If Not Page. 50. System. Address. • Locate the CustomerInsertButton_Click event handler. • Import the namespace used with the disconnected ADO. CreatedBy) VALUES(@FirstName. " & "Url.config file. "LastName") Dim insertAddressParameter As New SqlParameter("@Address".CreatedBy = Context. SqlDbType.User. @CreatedDate. 50. customerManagementConnection) ' Assign command objects customerManagementDataAdapter.NVarChar. @EmailAddress. LastName. " & "@CountryID.com or by calling +1 800-785-3448. redistribute. @State.0 Web Application • Import the namespace used for accessing a SQL Server 2008 database.ConnectionStrings("CustomerManagementConnectionString"). CreditLimit.Identity. "Address") This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.Data. Phone. ' Add the user credit limit currentCustomer. @City.IsValid Then Exit Sub End If ' Add the current user name currentCustomer. ByVal e As System. CreatedDate. ZipCode.QuickStart Intelligence Managing Data in a Microsoft® ASP. by using a code snippet named ADO.ConnectionString = ConfigurationManager. State. 8-41 Protected Sub CustomerInsertButton_Click(ByVal sender As Object.Data. The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. SqlDbType. @LastName.SqlClient. It is illegal to reprint. @CreditLimit. "FirstName") Dim insertLastNameParameter As New SqlParameter("@LastName".SelectCommand = selectCommand customerManagementDataAdapter.Open() ' Declare and instantiate data adapter Dim customerManagementDataAdapter As New SqlDataAdapter() ' Declare and instantiate command objects Dim selectCommand As New SqlCommand("SELECT * FROM Customers". guarantees or conditions.NET layer.config customerManagementConnection. City. The code snippet has been supplied by the senior developer. and provided to you by QuickStart Intelligence. @CreatedBy)". @NewsSubscriber.NET 4. customerManagementConnection) Dim insertCommand As New SqlCommand( "INSERT INTO Customers (FirstName.NVarChar. CountryID. NewsSubscriber.InsertCommand = insertCommand ' Declare and instantiate parameter objects Dim insertFirstNameParameter As New SqlParameter("@FirstName".Configuration. 30.CreditLimit = 50000 • Append the following code to the CustomerInsertButton_Click event handler. SqlDbType.NVarChar. EmailAddress.Connectio nString ' Open connection customerManagementConnection. @Address.EventArgs) Handles CustomerInsertButton. • Import the namespace for reading the connection string from the web.Name ' Add the user credit limit currentCustomer. and is placed in the My Code Snippets folder.NET Insert Customer.

"Customers") ' Create new row locally Dim newCustomerDataRow As DataRow = customerManagementDataSet.ZipCode newCustomerDataRow("City") = currentCustomer. 0.LastName newCustomerDataRow("Address") = currentCustomer.Add(insertCountryIDParameter) insertCommand." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. "EmailAddress") Dim insertWebAddressParameter As New SqlParameter("@WebAddress". SqlDbType. 30. SqlDbType.State newCustomerDataRow("CountryID") = currentCustomer.MissingSchemaAction = MissingSchemaAction. 0.Parameters. "ZipCode") Dim insertCityParameter As New SqlParameter("@City". SqlDbType. "NewsSubscriber") Dim insertCreatedDateParameter As New SqlParameter("@CreatedDate".Parameters.City newCustomerDataRow("State") = currentCustomer.Parameters. It is illegal to reprint. SqlDbType.Add(insertAddressParameter) insertCommand.Add(insertPhoneParameter) insertCommand. "City") Dim insertStateParameter As New SqlParameter("@State". guarantees or conditions. SqlDbType.NVarChar. "CountryID") Dim insertPhoneParameter As New SqlParameter("@Phone".Add(insertZipCodeParameter) insertCommand. 10. 30.Parameters.EmailAddress This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NVarChar.Fill(customerManagementDataSet.Passthrough ' Populate Customers DataTable customerManagementDataAdapter.Bit.Add(insertCreatedDateParameter) insertCommand. SchemaType. The Licensed Content is licensed "as-is. .Phone newCustomerDataRow("EmailAddress") = currentCustomer.VarChar.Tables("Customers"). SqlDbType. Please report any unauthorized use of this content to piracy@microsoft.FirstName newCustomerDataRow("LastName") = currentCustomer. redistribute. "CreatedBy") ' Assign parameters to command object insertCommand. SqlDbType.NVarChar.NewRow() newCustomerDataRow("ID") = Guid. SqlDbType.Add(insertCreditLimitParameter) insertCommand. 15.MissingMappingAction = MissingMappingAction.Parameters. "CreditLimit") Dim insertNewsSubscriberParameter As New SqlParameter("@NewsSubscriber". or resell this content.NVarChar.Parameters. "Url") Dim insertCreditLimitParameter As New SqlParameter("@CreditLimit".Parameters.Add(insertStateParameter) insertCommand. "Customers") customerManagementDataAdapter. 0.Address newCustomerDataRow("ZipCode") = currentCustomer.QuickStart Intelligence 8-42 Introduction to Web Development with Microsoft® Visual Studio® 2010 Dim insertZipCodeParameter As New SqlParameter("@ZipCode".FillSchema(customerManagementDataSet.VarChar. "Phone") Dim insertEmailAddressParameter As New SqlParameter("@EmailAddress".Parameters.SmallDateTime.Add(insertWebAddressParameter) insertCommand. SqlDbType.AddWithKey customerManagementDataAdapter.Add(insertLastNameParameter) insertCommand.Parameters. 30. "State") Dim insertCountryIDParameter As New SqlParameter("@CountryID".UniqueIdentifier.Parameters. SqlDbType. "CreatedDate") Dim insertCreatedByParameter As New SqlParameter("@CreatedBy".com or by calling +1 800-785-3448.Parameters. SqlDbType.EmailAddress newCustomerDataRow("Url") = currentCustomer.Add(insertEmailAddressParameter) insertCommand. 0.Add(insertFirstNameParameter) insertCommand.NVarChar.Add(insertCityParameter) insertCommand. and provided to you by QuickStart Intelligence.CountryID newCustomerDataRow("Phone") = currentCustomer.Parameters.Parameters.Add(insertNewsSubscriberParameter) insertCommand.Int.NewGuid() newCustomerDataRow("FirstName") = currentCustomer.Parameters. 50. 80.Source.Add(insertCreatedByParameter) ' Declare and instantiate dataset Dim customerManagementDataSet As New DataSet("CustomerManagementDataSet") ' Apply the full schema from the data source customerManagementDataAdapter.

It is illegal to reprint. "Customers") = 1 Then ' Instantiate new Customer object currentCustomer = New CustomerManagementEntities. 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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Rows. The Licensed Content is licensed "as-is.Redirect("~/InsertCustomer.0 Web Application 8-43 newCustomerDataRow("CreditLimit") = currentCustomer.aspx" /> • Save and close the web.sitemap file. and provided to you by QuickStart Intelligence. • Close Internet Explorer.NewsSubscriber newCustomerDataRow("CreatedDate") = currentCustomer.NET 4. • Append the new siteMapNode element to the Customers siteMapNode.CreatedDate newCustomerDataRow("CreatedBy") = currentCustomer.Update(customerManagementDataSet.com • Web Address: http://www.CreditLimit newCustomerDataRow("NewsSubscriber") = currentCustomer. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. <siteMapNode title="All" description="View All Customers" url="~/Customers.litwareinc. guarantees or conditions. redistribute. • Run the CustomerManagement Web application.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.  Task 6: Update sitemap to enable view all customers • Open the web.aspx") End If End Using • Save the Customer code-behind file. or resell this content. and click New on the Customers menu.  Task 7: Create a customer and verify the Data Source • Build the CustomerManagement solution.Add(newCustomerDataRow) ' Update data source If customerManagementDataAdapter. • Create a new customer by using the following information. Please report any unauthorized use of this content to piracy@microsoft.com or by calling +1 800-785-3448.Tables("Customers").QuickStart Intelligence Managing Data in a Microsoft® ASP.sitemap file. .Customer() ' Reload page to refresh with "blank" input controls Response. • Open the InsertCustomer Web Form.CreatedBy ' Insert new row locally customerManagementDataSet.

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

• Open the CustomerManagement solution from the D:\Labfiles\Starter\M8\CS folder. • Add a SqlDataSource control to the user control to connect to a SQL Server database.com or by calling +1 800-785-3448. and an existing database to the database folder. redistribute. with the CountriesSqlDataSource control selected. or resell this content. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Test the query. • Open Microsoft Visual Studio 2010. and then create a new connection string named CustomerManagementConnectionString. • Save the Customer user control.mdf database." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. Open an existing ASP. • Configure the SELECT statement to include the ID and Name columns from the Countries table. 2. 3. • Open the Configure Data Source Wizard. • Rename the SqlDataSource control as CountriesSqlDataSource.NET Web project • Log on to 10267A-GEN-DEV as Student. . Add a SQL Server 2008 Express Database. 4. Note: Ensure that the returned rows include the values for the ID and Name columns for various countries. connect to the CustomerManagement. Pa$$w0rd.  Task 4: Configure a data source control • In Design view.NET Web project. D:\LabFiles\Starter\M8\CustomerManagement.NET 4. and provided to you by QuickStart Intelligence. The Licensed Content is licensed "as-is. with the password. • Save the Customer user control. It is illegal to reprint.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.  Task 2: Add a SQL Server 2008 Express Database • Add a new database folder named App_Data. guarantees or conditions. display the Smart Tag.  Task 3: Add a data source control to the user control • Open the Customer user control in Design view.  Task 1: Open an existing ASP.QuickStart Intelligence Managing Data in a Microsoft® ASP. Add a data source control to the user control. and check whether you get the correct data from the Countries table. Configure a data source control.mdf.

CustomerEmailAddressTextBox. . Please report any unauthorized use of this content to piracy@microsoft.Text. and fix any errors. guarantees or conditions.Text).Text. 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.Text. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. or resell this content. CustomerStateTextBox. • Locate the markup for the CustomerCountryDropDownList control.Text. null. and provided to you by QuickStart Intelligence. CustomerWebAddressTextBox. • Locate the code for the private instantiateCustomerObject method. <asp:ListItem>USA</asp:ListItem> • Bind the CustomerCountryDropDownList control to the CountriesSqlDataSource control by using the DataSourceID attribute. // Instantiate new Customer object with user input currentCustomer = new CustomerManagementEntities. CustomerNewsSubscriberCheckBox. DataTextField="Name" • Build the user control. int. redistribute. "").Now. CustomerPhoneTextBox.Text. DataValueField="ID" • Set the text field of the CustomerCountryDropDownList control to the Name column of the database by using the DataTextField attribute. DateTime. DataSourceID="CountriesSqlDataSource" • Set the value field of the CustomerCountryDropDownList control to the ID column of the database by using the DataValueField attribute. CustomerCityTextBox.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.  Task 2: Pass the values to the Customer object • Open the Customer user control in the Code view. • Remove the static ListItem element from the CustomerCountryDropDownList control." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.  Task 1: Bind the DropDownList control to a data source • Open the Customer user control in Source view.Text.Text. 2. CustomerLastNameTextBox.Text. "". Pass the values to the Customer object.SelectedValue).Customer( null.Parse(CustomerCreditLimitTextBox. • Build the user control. and fix any errors. Bind the DropDownList control to the data source.com or by calling +1 800-785-3448.Checked.Text. CustomerFirstNameTextBox. new Guid(CustomerCountryDropDownList. The Licensed Content is licensed "as-is. CustomerAddressTextBox. CustomerZipCodeTextBox. It is illegal to reprint.

 Task 2: Add the SqlDataSource control to the Web Form • Add the SqlDataSource control to the Customers. and provided to you by QuickStart Intelligence.  Task 1: Create the Customers Web Form • Create the Customers Web Form.  Task 3: Configure the SqlDataSource control • In Design view. Add the ListView control to the Web Form. It is illegal to reprint. • Save the Customers Web Form." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. .  Task 5: Add code to manually save a customer to a data source • Open the Customer user control in the Code view. and use optimistic concurrency. 6. • Rename the ListView control as CustomersListView. Add the SqlDataSource control to the Web Form. 2. • Configure the SELECT statement to include all the columns from the Customers table. • Save the Customers Web Form. • Bind the CustomersListView control to the CustomersSqlDataSource control by using the Smart Tag. redistribute.0 Web Application 8-47 Exercise 3: Modifying a Data Source The main tasks in this exercise are as follows: 1. Please report any unauthorized use of this content to piracy@microsoft. • Rename the SqlDataSource control as CustomersSqlDataSource. Add code to manually save a customer to a data source.master master page. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • Close Internet Explorer.aspx Web Form. based on the Site. and fix any errors. 5. • Open the Configure Data Source Wizard. guarantees or conditions. 7. Create the Customers Web Form. • Build the user control.com or by calling +1 800-785-3448. Configure the SqlDataSource control. or resell this content. 4. The Licensed Content is licensed "as-is. • Select the CustomerManagementConnectionString connection string for the CustomersSqlDataSource control. display the Smart Tag. • Enable paging in the CustomersListView control. Create a customer and verify the Data Source.QuickStart Intelligence Managing Data in a Microsoft® ASP. 3. • Open the Customers Web Form in the Design view. • Save the Customers Web Form.NET 4. and ensure that it is possible to manipulate the data in the data source. with the CustomersSqlDataSource control selected. Update sitemap to enable view all customers. • View the Customers Web Form in the browser.  Task 4: Add the ListView control to the Web Form • Add the ListView control to the Customers Web Form.

System. "FirstName"). • Append the following code to the CustomerInsertButton_Click event handler. It is illegal to reprint. SqlParameter insertLastNameParameter = new SqlParameter("@LastName". • Import the namespace for reading the connection string from the web. State. SqlDbType. // Declare and instantiate data adapter SqlDataAdapter customerManagementDataAdapter = new SqlDataAdapter().User. // Assign command objects customerManagementDataAdapter. or resell this content.ConnectionStrings["CustomerManagementConnectionString"].InsertCommand = insertCommand.ConnectionString = ConfigurationManager.SqlClient. EventArgs e) { // Did page validation succeed? if (!Page. NewsSubscriber. @CreatedDate. • Import the namespace used with the disconnected ADO. // Create and instantiate connection using (SqlConnection customerManagementConnection = new SqlConnection()) { // Initialize connection string from web.Open(). ZipCode. @CreatedBy)".Connectio nString. customerManagementConnection).NVarChar. by using a code snippet named ADO.com or by calling +1 800-785-3448. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. @ZipCode. @EmailAddress.Identity. customerManagementConnection).config file. . guarantees or conditions. LastName. CreatedBy) VALUES(@FirstName.NVarChar. "LastName").NET layer. and provided to you by QuickStart Intelligence.CreditLimit = 50000.Configuration. System.NET Insert Customer.Data. // Add the user credit limit currentCustomer. @Phone. CountryID. customerManagementDataAdapter. // Add the user credit limit currentCustomer. Please report any unauthorized use of this content to piracy@microsoft. EmailAddress. Address. CreditLimit." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. @Address. // Declare and instantiate parameter objects SqlParameter insertFirstNameParameter = new SqlParameter("@FirstName".CreatedBy = Context. Phone. The code snippet has been supplied by the senior developer. // Declare and instantiate command objects SqlCommand selectCommand = new SqlCommand("SELECT * FROM Customers". @NewsSubscriber. // Open connection customerManagementConnection. System. " + "@CountryID. 50. SqlCommand insertCommand = new SqlCommand( "INSERT INTO Customers (FirstName. " + "Url. @City.QuickStart Intelligence 8-48 Introduction to Web Development with Microsoft® Visual Studio® 2010 • Import the namespace used for accessing a SQL Server 2008 database.Data. @WebAddress. protected void CustomerInsertButton_Click(object sender. CreatedDate. @LastName.SelectCommand = selectCommand. 30. • Locate the CustomerInsertButton_Click event handler. @CreditLimit. SqlDbType.IsValid) return. City. and is placed in the My Code Snippets folder.config customerManagementConnection. Remove the assignment of the value 50000 to the CreditLimit property. @State. The Licensed Content is licensed "as-is. } • // Add the current user name currentCustomer.CreditLimit = 50000.Name. redistribute.

0. SqlDbType.AddWithKey. SqlParameter insertCountryIDParameter = new SqlParameter("@CountryID".Address. 15. SqlParameter insertCityParameter = new SqlParameter("@City". "Address"). "EmailAddress").State. // Apply the full schema from the data source customerManagementDataAdapter. newCustomerDataRow["Address"] = currentCustomer.NVarChar.NVarChar.Parameters. SchemaType.0 Web Application 8-49 SqlParameter insertAddressParameter = new SqlParameter("@Address".City. 30. "Url").NewGuid(). "City").Add(insertCountryIDParameter).Parameters.Parameters.Parameters.Add(insertCityParameter). SqlDbType.MissingSchemaAction = MissingSchemaAction. newCustomerDataRow["ZipCode"] = currentCustomer. 0. newCustomerDataRow["LastName"] = currentCustomer. insertCommand.Add(insertPhoneParameter). insertCommand. insertCommand. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 30. SqlParameter insertStateParameter = new SqlParameter("@State".Parameters. SqlDbType. "CreatedBy").Fill(customerManagementDataSet.VarChar.Parameters. insertCommand.Add(insertLastNameParameter). customerManagementDataAdapter. "NewsSubscriber"). SqlParameter insertCreditLimitParameter = new SqlParameter("@CreditLimit". SqlParameter insertZipCodeParameter = new SqlParameter("@ZipCode". insertCommand. SqlParameter insertCreatedDateParameter = new SqlParameter("@CreatedDate". redistribute. guarantees or conditions. 30.Add(insertWebAddressParameter).NVarChar. SqlDbType.NewRow(). SqlDbType. // Create new row locally DataRow newCustomerDataRow = customerManagementDataSet.Parameters. "Phone"). and provided to you by QuickStart Intelligence. insertCommand.Parameters.UniqueIdentifier. It is illegal to reprint. insertCommand. SqlParameter insertEmailAddressParameter = new SqlParameter("@EmailAddress".Parameters.NVarChar. 80. newCustomerDataRow["FirstName"] = currentCustomer. insertCommand. "CountryID").Add(insertZipCodeParameter). The Licensed Content is licensed "as-is." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. "Customers").Int. insertCommand.Parameters.Parameters. SqlParameter insertPhoneParameter = new SqlParameter("@Phone".Add(insertAddressParameter).Parameters.Bit. "CreatedDate"). 50. customerManagementDataAdapter. "CreditLimit"). insertCommand. SqlDbType.Add(insertCreatedByParameter). SqlDbType.com or by calling +1 800-785-3448.FirstName.Parameters.Add(insertStateParameter). "ZipCode").Tables["Customers"].NVarChar.Add(insertNewsSubscriberParameter). insertCommand. insertCommand.NVarChar.VarChar.Passthrough. // Assign parameters to command object insertCommand. // Declare and instantiate dataset DataSet customerManagementDataSet = new DataSet("CustomerManagementDataSet").Add(insertEmailAddressParameter). newCustomerDataRow["State"] = currentCustomer.SmallDateTime. "State").MissingMappingAction = MissingMappingAction. "Customers").FillSchema(customerManagementDataSet. or resell this content.QuickStart Intelligence Managing Data in a Microsoft® ASP. insertCommand. // Populate Customers DataTable customerManagementDataAdapter.Add(insertCreatedDateParameter).ZipCode. SqlDbType. 50.LastName.Parameters. SqlDbType. newCustomerDataRow["ID"] = Guid.Add(insertCreditLimitParameter). 10. SqlParameter insertWebAddressParameter = new SqlParameter("@WebAddress". SqlDbType.Source. 0. SqlParameter insertNewsSubscriberParameter = new SqlParameter("@NewsSubscriber". SqlDbType. SqlParameter insertCreatedByParameter = new SqlParameter("@CreatedBy". newCustomerDataRow["City"] = currentCustomer. . 0.Add(insertFirstNameParameter).NET 4. Please report any unauthorized use of this content to piracy@microsoft. SqlDbType.

// Update data source if (customerManagementDataAdapter. newCustomerDataRow["CreditLimit"] = currentCustomer. newCustomerDataRow["CreatedBy"] = currentCustomer. // Insert new row locally customerManagementDataSet.sitemap file. • Open the InsertCustomer Web Form. newCustomerDataRow["CreatedDate"] = currentCustomer.QuickStart Intelligence 8-50 Introduction to Web Development with Microsoft® Visual Studio® 2010 newCustomerDataRow["CountryID"] = currentCustomer. redistribute.litwareinc.  Task 6: Update sitemap to enable view all customers • Open the web.Phone. newCustomerDataRow["Url"] = currentCustomer. It is illegal to reprint. • Create a new customer by using the following information. . // Reload page to refresh with "blank" input controls Response. newCustomerDataRow["EmailAddress"] = currentCustomer.Customer(). newCustomerDataRow["NewsSubscriber"] = currentCustomer. 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.CreatedDate. and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft.com • Credit Limit: 50000 • News Subscriber: Yes This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.com • Web Address: http://www.EmailAddress.Tables["Customers"]." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. newCustomerDataRow["Phone"] = currentCustomer. guarantees or conditions. The Licensed Content is licensed "as-is.CountryID.Add(newCustomerDataRow).Redirect("~/InsertCustomer. • Append the new siteMapNode element to the Customers siteMapNode.NewsSubscriber.sitemap file.CreatedBy. } } • Save the Customer code-behind file.Update(customerManagementDataSet. "Customers") == 1) { // Instantiate new Customer object currentCustomer = new CustomerManagementEntities.EmailAddress.com or by calling +1 800-785-3448.Rows.CreditLimit. <siteMapNode title="All" description="View All Customers" url="~/Customers. • Run the CustomerManagement Web application.  Task 7: Create a customer and verify the Data Source • Build the CustomerManagement solution. or resell this content.aspx" /> • Save and close the web.aspx").

It is illegal to reprint. The Licensed Content is licensed "as-is. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. Please report any unauthorized use of this content to piracy@microsoft. or resell this content.NET 4. • Close Internet Explorer.com or by calling +1 800-785-3448. • Revert the changes made to the 10267A-GEN-DEV virtual machine.QuickStart Intelligence Managing Data in a Microsoft® ASP. and provided to you by QuickStart Intelligence.  Task 8: Turn off the virtual machine and revert the changes • Turn off the 10267A-GEN-DEV virtual machine. . Note: The answers to the exercises are on the Course Companion CD. guarantees or conditions. redistribute.0 Web Application 8-51 • Check that the new customer has been added in the data source by using the new Customers Web Form.

In the Turn Off Machine dialog box. 2.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. right-click 10267A-GEN-DEV. you must turn off the 10267A-GEN-DEV virtual machine and revert the changes. The Licensed Content is licensed "as-is. 3. and then click Revert." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 4. in the Virtual Machines pane. It is illegal to reprint. . right-click 10267A-GEN-DEV. click Turn Off. and then click Turn Off. In Microsoft Hyper-V™ Manager. guarantees or conditions. In the Revert Virtual Machine dialog box. in the Virtual Machines pane. In Hyper-V Manager. click Revert. Please report any unauthorized use of this content to piracy@microsoft. and provided to you by QuickStart Intelligence. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. 1. redistribute. or resell this content.

It is illegal to reprint. 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.0 Web Application 8-53 Lab Review Review Questions and Answers 1. . and provided to you by QuickStart Intelligence. or resell this content.NET 4." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. guarantees or conditions. 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. How can you enable paging for a GridView control? 2. redistribute.

On a production server—where many connections are opened to the database—it appears that after a few days of uptime.QuickStart Intelligence 8-54 Introduction to Web Development with Microsoft® Visual Studio® 2010 Module Review and Takeaways Review Questions and Answers 1.NET Framework Data Provider. What is the easiest way to connect to the Oracle database? Use the OLE DB . What is the main difference between a DataSet and a DataReader object? Real-World Issues and Scenarios 1. What is the first thing you should check? You should check if you have closed your connection objects correctly. • Use a DataTable object whenever you only need to work locally with the content of a single database entity. instead of a DataSet object. redistribute. The Licensed Content is licensed "as-is.config file. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. How do you create a connection to a database in Visual Studio 2010? 2. . It saves resources. making it accessible to all of the Web application. or resell this content. and provided to you by QuickStart Intelligence. the Web server and the database server slow down due to increased amount of memory and connection resources being used. • Connection objects should always be explicitly disposed of." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. 2. Which object is used to facilitate transport from the data source to a DataSet object and back again?? 3. place the connection string in the web.com or by calling +1 800-785-3448. Best Practices Mention some best practices in the context of your own business situations. You need to connect to an Oracle database. Please report any unauthorized use of this content to piracy@microsoft. and making it easy for an administrator to change the file without recompiling code. It is illegal to reprint. • Whenever possible. guarantees or conditions.

or resell this content.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." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. The Licensed Content is licensed "as-is. . It is illegal to reprint. and provided to you by QuickStart Intelligence. redistribute.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions.

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 . and provided to you by QuickStart Intelligence. and transmission of data. This module explains what LINQ is. It is illegal to reprint.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. However. relational databases and XML. . This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b.NET Web application by using Web server controls. Please report any unauthorized use of this content to piracy@microsoft. management. XML has become a standard for storage. LINQ improves developer productivity through Microsoft IntelliSense® and compiletime error checking. and some code. and how you can use LINQ to manage both XML data and SQL Server data in a Microsoft ASP." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. both SQL Server and XML data require different methods for managing the data. or resell this content.com or by calling +1 800-785-3448.NET object. redistribute.NET. The Licensed Content is licensed "as-is. guarantees or conditions.

The Licensed Content is licensed "as-is. • Describe LINQ to SQL. there was no single. you will be able to: • Describe LINQ.com or by calling +1 800-785-3448. you can write data management code that can be used across various data sources with minor syntax changes. 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 grouping SQL Server data. and how you can use LINQ to SQL to write SQL-type queries for selecting. It is illegal to reprint. and provided to you by QuickStart Intelligence. redistribute. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Please report any unauthorized use of this content to piracy@microsoft. or resell this content. Lesson Objectives After completing this lesson.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 access—such as an SQL Server database or XML data—but not both. because the manner in which you access and manage SQL Server data and XML data differs. or use a single application programming interface (API) for doing these tasks. manage the data. unified way to access data in different data sources. . Before the introduction of LINQ. guarantees or conditions. • Describe LINQ Query Operators. • Describe LINQ to Entities." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. This lesson explains what LINQ is. Using LINQ. filtering. and how to use LINQ to entities. • Describe LINQ to XML.

which Microsoft Visual Studio® provides. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. Visual Studio 2010 provides various tools and features that support application development by using LINQ. or Microsoft Visual C#®. redistribute. You can write queries in a simplified manner against strongly-typed collections of objects. LINQ also provides a unified syntax that you can use to query any data source that supports LINQ. LINQ-aware code editors for Visual Basic and Visual C# provide IntelliSense and LINQ-specific formatting capabilities. resulting in type-checking at compile time. or resell this content. including: • LINQ-Aware Code Editors. guarantees or conditions. • Visual Studio Debugger Support. XML documents. LINQ bridges the gap between the objects in object-oriented programming (OOP) and the various data used by OOP applications. It is illegal to reprint. With LINQ. or events. Visual Studio Features and Tools for LINQ LINQ is an integrated part of the Visual Basic and Visual C# programming languages. There was no IntelliSense support. Before the introduction of LINQ.NET datasets. a query is a first-class language construct in Visual Basic and Visual C#. including SQL Server databases. whether standard or generic. The Visual Studio debugger supports the debugging of LINQ query expressions. In addition.NET Framework–based programming language such as Microsoft Visual Basic®.com or by calling +1 800-785-3448. The Licensed Content is licensed "as-is. each type of data source required a different query language. or ADO.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 . just like classes." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. by using programming language keywords and familiar operators. and provided to you by QuickStart Intelligence. You can also write queries against any collection of objects that supports the IEnumerable interface. data queries were expressed as a simple string. . methods. Please report any unauthorized use of this content to piracy@microsoft.

• LINQ to Entities.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#. guarantees or conditions.IO. Enables you to query data stored in XML documents. Enables you to query in-memory data such as arrays and lists. Please report any unauthorized use of this content to piracy@microsoft. [Visual Basic] Dim files = From file In My. 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. including: • LINQ to DataSet. • LINQ to XML. .Computer.FileSystem. This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. • LINQ to Objects. • LINQ to SQL. Enables you to query data in relational databases by querying a LINQ to SQL data context.com or by calling +1 800-785-3448. redistribute.Directory. LINQ Implementations Visual Studio 2010 includes LINQ provider assemblies that enable you to use LINQ with several different types of data.PhysicalApplicationPath & "\Public") Select file [Visual C#] var files = from file in System. The Licensed Content is licensed "as-is. and provided to you by QuickStart Intelligence.GetFiles( Request.PhysicalApplicationPath + "\\Public") select file. Notice the full type-checking and IntelliSense support that Visual Studio 2010 provides. Enables you to query data in relational databases by querying an Entity Data Model (EDM)." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. or resell this content. It is illegal to reprint.GetFiles( Request. Enables you to query data cached in a DataSet object.

respectively. They provide query capabilities. . Most of methods operate on sequences. Those methods that return a single value—for example. or a sequence of values. where a sequence is an object whose type implements the IEnumerable<T> or IQueryable<T> interface. (VB: IQueryable(Of T) or C#: IQueryable<T> The methods that make up each set are static members of the Enumerable and Queryable classes.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. (VB: IEnumerable(Of T) or C#: IEnumerable<T>) • One set of query operators operates on objects of type IQueryable(T). and sorting." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. [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. It is illegal to reprint.Split(" "c) Dim query = From word In words Group word.ToUpper() By word. The Licensed Content is licensed "as-is. which means they can be called by using either static method syntax or instance method syntax. There are two sets of LINQ standard query operators: • One set of query operators operate on objects of type IEnumerable(T). The following code examples demonstrate how the standard query operators can be used to obtain information about a sequence. or resell this content. The standard query operators differ in the timing of their execution. Methods that return a sequence defer the query execution and return an enumerable object. They are defined as extension methods of the type on which they operate. including filtering. and provided to you by QuickStart Intelligence.Length Into gr = Group Order By Length This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. aggregation. depending on whether they return a single value. guarantees or conditions. Average or Sum—run immediately. Please report any unauthorized use of this content to piracy@microsoft.

Words = gr }.Length).Split(' ').ToUpper()) _ .QuickStart Intelligence Managing Data Access Tasks by Using LINQ 9-7 Select Length.Write(string. } foreach (string word in obj.ToUpper()).Length into gr orderby gr.GroupedWords Response. The Licensed Content is licensed "as-is.Write(word & "<br />") Next Next [Visual C#] string sentence = "the quick brown fox jumps over the lazy dog".GroupBy(Function(w) w. obj. Please report any unauthorized use of this content to piracy@microsoft.Length)). // Using query expression syntax var query = from word in words group word. w => w. foreach (var obj in query) { Response.Select(Function(g) New With {.com or by calling +1 800-785-3448. and provided to you by QuickStart Intelligence.Length.Write(String. GroupBy(w => w. GroupedWords = gr ' Using method-based query syntax Dim query2 = words _ .Key.Length = g. Select(g => new { Length = g.Format("Words of length {0}:<br />".Key select new { Length = gr.Words) Response. Function(w) w.ToUpper() by word. // Using method-based query syntax var query2 = words. .Length.Write(word + "<br />").Key.Key.GroupedWords = g}) _ . obj.Format("Words of length {0}:<br />".OrderBy(Function(o) o." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.Length) For Each obj In query2 Response. guarantees or conditions. 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. string[] words = sentence. OrderBy(o => o. . It is illegal to reprint.Length)) For Each word As String In obj. redistribute. // Split the string into individual words to create a collection. Words = g }). or resell this content.

... Question: What are the types of objects... Performs a join. guarantees or conditions... Operator(s) Visual Basic operator Visual C# operator Description Select Select select Selects a sequence from the container. Please report any unauthorized use of this content to piracy@microsoft... In from . by . and provided to you by QuickStart Intelligence.... in Extracts a subset (From/from) of data from a container (In/in).. Join From x In . on ....] In ... or resell this content...com or by calling +1 800-785-3448. join .. 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.. In From . The Licensed Content is licensed "as-is.. Group By Group .a -orJoin . [As . On .. Into .a = b. based on the specified key. y In . Where Where where Defines a restriction for the items to extract... descending Sorts a subset in ascending or descending order. From .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#." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties...... ..... Where x... It is illegal to reprint. group . by -orgroup . equals .. Order By Order By -orOrder By . into Groups a subset by specified value. Descending orderby -ororderby ... in .. By .. redistribute..

or resell this content. The Licensed Content is licensed "as-is. and is integrated with LINQ. LINQ to XML makes XML easier to manage. In the following LINQ to XML code examples. because the query expression is similar to the SQL programming syntax. It is illegal to reprint. redesigned document object model (DOM) XML programming interface.Element("InternetTLD") This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. redistribute. and provided to you by QuickStart Intelligence. it can also be used to compute values—such as numbers or Boolean values—from the content of the XML document. LINQ to XML provides an in-memory XML programming interface that capitalizes on the . it is important to understand how to work with data in the XML format. the query is run to obtain the Internet top-level domain (TLD) value for every Country element in the Countries root element. .<Country> Select country.NET LINQ Framework. LINQ to XML is comparable to DOM in that it makes an XML document accessible in memory. [Visual Basic] Dim internetTLDs = From country In countries. Note: XPath is a query language for navigating an XML document and selecting nodes from the document. and is comparable to an updated. The latter enables you to run queries on the in-memory XML document to retrieve collections of elements and attributes. and transporting data.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. However. LINQ to XML uses the . The LINQ to XML query expressions provide functionality that is similar to that of XML Path Language (XPath). guarantees or conditions. LINQ to XML takes advantage of language improvements in both Visual Basic and Visual C#.NET Framework language capabilities.com or by calling +1 800-785-3448. Please report any unauthorized use of this content to piracy@microsoft. but LINQ to XML differs from DOM in that it provides a new object model that is easier to work with. formatting." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties.

Please report any unauthorized use of this content to piracy@microsoft. "63750c5e-092c-de11-8c6e-0003ff4ed632"). new XElement("Name". "DK") ).QuickStart Intelligence 9-10 Introduction to Web Development with Microsoft® Visual Studio® 2010 [Visual C#] var internetTLDs = from country in countries. "UG") ). "## ## ## ##").com or by calling +1 800-785-3448. new XElement("Country". and provided to you by QuickStart Intelligence. "Denmark").Element("InternetTLD"). new XElement("InternationalDialingCode". new XElement("DialingCountryCode"." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. new XElement("DialingCountryCode". new XElement("Name". guarantees or conditions. The Licensed Content is licensed "as-is. new XElement("InternationalDialingCode". new XElement("Name". redistribute. The XML tree can be created more or less as you would write it in an XML file.Elements("Country") select (string)country. "602cf8a8-b62f-de11-a6b1-0003ffa70544"). new XElement("ID". new XElement("PhoneNoFormat". "Great Britain"). "45"). new XElement("Country". new XElement("InternetTLD". ""). "Uganda"). new XElement("ID". new XElement("PhoneNoFormat". new XElement("Country". "000"). new XElement("PhoneNoFormat". It is illegal to reprint. "256"). "00"). If you need to create in-memory XML—such as an XML tree—you can use the following lines of code. [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("ID". "62750c5e-092c-de11-8c6e-0003ff4ed632"). This is a unique copy of the course material identified by code b67a4674-036e-4ef4-a5a9-1dda5be2511b. ""). . new XElement("InternetTLD". because of how the Visual Basic Code Editor handles the XML. or resell this content.

"00"). It is illegal to reprint. The Licensed Content is licensed "as-is. new XElement("InternationalDialingCode".com or by calling +1 800-785-3448. or resell this content. redistribute." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. "44"). ) 9-11 new XElement("DialingCountryCode". and provided to you by QuickStart Intelligence. Please report any unauthorized use of this content to piracy@microsoft. guarantees or conditions. . "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. new XElement("InternetTLD".QuickStart Intelligence Managing Data Access Tasks by Using LINQ ).

After you have added the tables to the designer surface. Please report any unauthorized use of this content to piracy@microsoft. A programming language accesses information in a database by using objects through one or more APIs. or resell this content.exe command-line tool automatically generates the classes that give you access to the data by using strongly-typed objects in your code. It is illegal to reprint. and most often. which is a mapping of the relational data to objects." Microsoft does not support this Licensed Content in any way and Microsoft gives no express warranties. the sqlmetal. because it provides a runtime infrastructure for managing relational data as objects. The difference lies in how the data in programming languages and data in relational databases is represented. you can view and set the properties of the classes. redistribute.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. IntelliSense does not work in the Visual Studio 2010 text editor. You can use the Object Relational Designer (O/R Designer) in Visual Studio 2010 to create a data context. 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. LINQ to SQL translates the LINQ queries in the object model into SQL. Also. they cannot be verified for errors such as syntax errors. Because queries are represented as text strings. . and is mapped by using a DataContext object. the query is run to obtain all the customers in the Customers table in a SQL Server database. Upon return. [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. At runtime. The tables become classes. and provided to you by QuickStart Intelligence. and you can manipulate the data in the tables.com or by calling +1 800-785-3448. and sends them to the database for execution. These APIs require that you specify your queries as simple text strings. When you build your project or solution. The data model of a traditional relational data