Sunteți pe pagina 1din 346

Slide 00

Saturday, September 06, 2008


12:11 AM

Instructor Notes (PPT Text)


This introduction module provides students with an overview of the course content materials and logistics for Course
2310C, Developing ASP.NET Web Applications by Using Microsoft Visual Studio 2008.
Required materials
To teach this course, you need the following materials:
• Course Handbook
• Course Companion CD
• Trainer materials including:
• Trainer Preparation Guide
• Microsoft Office PowerPoint® files for this course
• Microsoft Virtual PC/Server Classroom Setup Guide
• Virtual machines for the course
• Latest error logs for the course (if any)
Important It is recommended that you use PowerPoint 2002 or a later version to display the slides for this course. If
you use PowerPoint Viewer or an earlier version of PowerPoint, all the features of the slides might not be displayed
correctly.
Preparation tasks
To prepare for this course, you must follow and complete the tasks outlined in the Trainer Preparation Guide.
Presentation: 20 minutes

Module 00-Course Overview página 1


Slide 01
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Welcome students to the course and introduce yourself. Provide a brief overview of your background
to establish credibility.
Ask students to introduce themselves and provide their backgrounds, product experience, and
expectations of the course.
Record student expectations on a whiteboard or flip chart that you can reference during class.

Module 00-Course Overview página 2


Slide 02
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Tell students that everything they will need for this course is provided at their desks.
Have students write their names on both sides of the name cards if name cards are provided.
Describe the contents of the Course Handbook and the Course Companion CD. Explain that the Course
Handbook is meant to be used in conjunction with the Course Companion CD. Specifically, explain
that:
• The Course Handbook is meant as:
• a succinct classroom learning guide
• a quick on-the-job reference (particularly with the end-of-module takeaways section)
• The Course Companion CD provides the full course content with:
• more detailed support information for each topic
• complete lab exercise information and procedures to use during lab time
• well categorized reference materials for extended learning support
Explain how you intend for students to use the Course Handbook and the Course Companion CD
during the class. Demonstrate how to open the Course Companion CD and how to navigate the
companion content structure.
Tell students where they can send comments and feedback on this course.
Tell students that they will have an opportunity to provide course evaluation at the end of the course.

Module 00-Course Overview página 3


Slide 03
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Explain the class hours, extended building hours for labs, parking, restroom location, meals, phones,
message posting, and where smoking is or is not allowed.
Let students know if your facility has Internet access that is available for them to use during class
breaks.
Also, make sure that the students are aware of the recycling program if one is available.

Module 00-Course Overview página 4


Slide 04
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Explain that course 2310 is not a direct prerequisite to course 6463 but that some students may
benefit from taking both courses.
Explain the Microsoft Learning program and present the list of additional recommended courses.
Refer students to the Microsoft Learning Web page at
http://www.microsoft.com/learning/ for information about curriculum paths

Module 00-Course Overview página 5


Slide 05
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


This course does not map to any specific certification exam.
Explain that Microsoft® Learning offers a variety of certification credentials for developers and IT
professionals. If the students require more information, describe the key developer certifications such
as Microsoft Certified Technology Specialist (MCTS) and Microsoft Certified Professional Developer
(MCPD). Direct the students to the link provided on the slide.
Inform students about the Microsoft Certified Professional (MCP) program, any certification exams that
are related to this course, and the various certification options.

Module 00-Course Overview página 6


Slide 06
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Describe the audience and the prerequisites for this course. This is an opportunity for you to identify
students who may not have the appropriate background or experience to attend this course.
Describe the course objectives.

Module 00-Course Overview página 7


Slide 07
Saturday, September 06, 2008
12:11 AM

Instructor Notes (PPT Text)


Briefly describe each module and what students will learn.
Explain how this course will meet students' expectations by relating the information that is covered in
individual modules to their expectations.

Module 00-Course Overview página 8


Slide 08
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)

Module 00-Course Overview página 9


Slide 09
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)


Tell students that they will use Microsoft Virtual Server to perform the labs.
Describe the virtual machine lab environment. Briefly describe the names and roles of the virtual
machines that students will use for the lab exercises.
Explain that the course files (lab files required for performing the labs) are located in the folder E:
\Labfiles on the student computers.
Explain that all student computers have the same configurations.

Module 00-Course Overview página 10


Slide 10
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)


If the course does not use virtual machines, this topic is not necessary.

Module 00-Course Overview página 11


Slide 11
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)

Module 00-Course Overview página 12


Introduction to the .NET Framework
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 1
Introduction to the .NET Framework
This lesson introduces Microsoft .NET and the .NET Framework. It describes some of the problems that developers
confront while they develop Web applications and explains how the .NET Framework solves these problems. This
lesson also introduces Microsoft Visual Studio ® 2008, which is the development tool that you will use to develop
Web applications by using the .NET Framework.

Module 01-Overview of the Microsoft .NET Framework página 13


What Is Microsoft .NET
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)


The key point about the Microsoft® .NET Framework is that it is a platform-independent and device-
independent system that is designed to work over the Internet.
Do not cover the .NET Framework components in depth here because there is a slide for that later in
the course.
Briefly name some of the features of the common language runtime (CLR), which will be covered in
more depth later.

Student Book Content


What Is Microsoft .NET?
Key Points
Microsoft .NET can include the following technologies:
The .NET Framework
Servers
Clients
Visual Studio 2008

Question: Which Microsoft .NET technologies does your workplace currently use?
CD Content
Microsoft .NET is a development model that you can use to create platform-independent and device-independent
software. You can also use the .NET Framework to make data available over the Internet. The .NET Framework is the
infrastructure of Microsoft .NET.
Components of Microsoft .NET
Microsoft .NET is built from the ground up on open architecture and you can use it to build and run the next
generation of Microsoft Windows ® and Web applications. The goal of Microsoft .NET is to simplify the development
of Web and other applications.
Microsoft .NET can include the following technologies:
The .NET Framework. The .NET Framework provides a programming model that enables developers to build
Windows and Web applications and XML Web services.
Servers. Microsoft .NET provides an infrastructure to integrate, run, operate, and manage .NET-Framework
solutions on servers such as Microsoft Windows Server 2003™ and Microsoft SQL Server™.
Clients. Microsoft .NET enables developers to deliver a comprehensive user experience across a family of devices
such as mobile devices, Web browsers, and personal computers.

Module 01-Overview of the Microsoft .NET Framework página 14


The .NET Framework Components
Saturday, September 06, 2008
12:12 AM

Instructor Notes (PPT Text)


Mention that this course covers version 3.5 of the .NET Framework. Distinguish between this version
and version 3.0 and 2.0.
Briefly cover each key component.
Mention that the user interface (UI) and ASP.NET are below the
languages, meaning there is one Forms model for all languages.
Discussion Question:
Do not spend too much time on the discussion point. There are several "correct" answers; however,
there are many different items to consider including current network environment, user skill level, and
development time. This can easily become more of a question along the lines of what is "appropriate"
rather than suitable.

Student Book Content


The .NET Framework Components
Key Points
The CLR environment is a managed environment.
The .NET Framework provides a choice of development languages.
The .NET Framework class library implements the .NET Framework.
Version, 3.5 of the .NET Framework builds incrementally on features from the previous two versions, namely 2.0
and 3.0.

Question: You have been asked to build a new distributed and service-oriented Web application in a Microsoft
Windows ® environment. Which technologies may be suitable for this new application?
CD Content
The .NET Framework provides the necessary compile-time and run-time foundation to build and run Microsoft .NET-
based applications.
The .NET Framework
The .NET Framework consists of different components that help you to build and run Microsoft .NET-based
applications:
Operating System. The .NET Framework must run on an operating system. The supported operating systems for
the .NET Framework version 3.5 are Microsoft Windows Server ® 2003, Windows Vista™, and Windows XP.
Common Language Runtime. The CLR simplifies application development, provides a robust and secure execution
environment, supports multiple languages, and simplifies application deployment and management. The CLR
environment is a managed environment, which provides common services such as garbage collection and security.
By using the CLR, you can develop a Microsoft .NET solution by using the programming language of your choice.
The .NET compiler then transforms your source code and creates a managed module, which the CLR on the client
computer can execute.

Module 01-Overview of the Microsoft .NET Framework página 15


Benefits of the .NET Framework
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


Discuss the benefits of the .NET Framework in developing Web applications.

Student Book Content

Windows Forms, which provides the functionality to develop executable applications that run on client computers.

.NET Framework 3.0 Technologies


The .NET Framework version 3.0 builds on the .NET Framework version 2.0 and provides new technologies to help
you develop the next generation of distributed applications. The .NET Framework 3.0 is included as part of the
Windows Vista operating system and is available for Windows XP and Windows Server 2003.
The .NET Framework 3.0 technologies are:
Windows Communication Foundation (WCF), which provides a unified programming model for service-oriented
applications.
Windows Presentation Foundation (WPF), which provides classes for smart-client applications that combine user
interface, documents, and media.
Windows Workflow Foundation (WF), which provides a programming model and tools to build workflow-enabled
applications that model business processes.
Windows CardSpace, which simplifies the security of working online by using personal identity information in the
form of virtual business cards.

.NET Framework 3.5 Technologies


The latest version of the .NET Framework, the .NET Framework 3.5, builds incrementally on the new features added
in the .NET Framework 3.0. The .NET Framework 3.5 also provides new features in several technology areas. These
features are contained in new assemblies to avoid breaking existing applications that are written for previous
versions of the .NET Framework.
The .NET Framework 3.5 technologies include:
Language Integrated Query (LINQ), which enables you to write code to access and manipulate data by using any
LINQ-enabled language.
Note:For more information about LINQ, see Module 9, "Accomplishing Complex Data Access Tasks."

ASP.NET AJAX, which enables you to create more efficient and interactive Web applications.

Module 01-Overview of the Microsoft .NET Framework página 16


Visual Studio 2008 - The Tool for .NET Development
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


Inform the students that if they have the .NET Framework installed on their computers, they can build
programs without Microsoft Visual Studio® 2008 (for instance, by using Microsoft Notepad only).
However, Visual Studio 2008 is a great development environment that makes developing Web
applications a rich experience for developers. Visual Studio 2008 is designed to support the developer
all the way through the development process.

Student Book Content


Visual Studio 2008: The Tool for .NET Development
Key Points
Visual Studio 2008 is a complete development environment that provides many features, including the following:
Multi-targeting support to enable developers to select which version of the .NET Framework they want their
application to target (2.0, 3.0, or 3.5).
Tools for building many different types of application, including Web, Windows-based, Windows Presentation
Foundation (WPF), Windows Communication Foundation (WCF), Windows Workflow Foundation (WF), and ASP.NET
AJAX.
Complete error-handling and debugging, along with easily accessible help and documentation.

Module 01-Overview of the Microsoft .NET Framework página 17


Overview of ASP.NET
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 2
Overview of ASP.NET
ASP.NET is a programming framework for building Web applications. ASP.NET Web Forms, which are part of an
ASP.NET Web application, provide an easy way to build dynamic Web sites. ASP.NET also includes the technology to
build XML Web services, which provide the building blocks for the construction of distributed Web-based
applications. This lesson describes the key features of ASP.NET and ASP.NET Web applications.

Module 01-Overview of the Microsoft .NET Framework página 18


What Is ASP.NET
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


Mention that ASP.NET is the successor to ASP and that there have been several versions of ASP.NET,
such as 1.0, 1.1, and 2.0.
Explain that each successive version of ASP.NET aims to increase the productivity of developers but
requires them to write less code.
Mention the development server that is provided as part of the Visual Studio 2008 suite of tools;
however, emphasize that students must use Internet Information Services (IIS) to host the deployed
Web application.

Student Book Content


What Is ASP.NET?
Key Points
Microsoft ASP.NET is a set of Web application development technologies. ASP.NET applications consist of one or
more Web Forms and developers can use Visual Studio 2008 as an environment to build and test these applications.

CD Content
For many years, developers have used ASP technology to build dynamic Web pages. Similar to ASP, ASP.NET runs on
a Web server and provides a way for you to develop content-rich, dynamic, personalized Web sites. In addition,
ASP.NET offers many improvements over ASP.
What Is ASP.NET?
Microsoft ASP.NET is a set of Web application development technologies that enables programmers to build
dynamic Web sites, Web applications, and XML Web services. Because ASP.NET is part of the .NET Framework, you
can develop ASP.NET Web applications in any .NET-based language.
The fundamental component of ASP.NET is the Web Form. A Web Form is the Web page that users view in a
browser. An ASP.NET Web application consists of one or more Web Forms. A Web Form is a dynamic page that can
access server resources.
For example, a traditional HTML Web page can run script on the client to perform basic tasks. However, an ASP.NET
Web Form can also run server-side code to access a database, to generate additional Web Forms, or to take
advantage of built-in security on the server.
In addition, because an ASP.NET Web Form does not rely on client-side scripting, it is not dependent on the client's
browser type or operating system. This independence enables you to develop a single Web Form that you can view
on practically any device that has Internet access and a Web browser.
You can use Visual Studio 2008 to build and execute an ASP.NET Web application. This results in a simplified
development process because you can test the application without creating an external hosting environment.
A deployed ASP.NET application runs as a process in Internet Information Services (IIS).

Module 01-Overview of the Microsoft .NET Framework página 19


ASP.NET Web Applications
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


This topic focuses on what constitutes an ASP.NET Web application. Discuss the different components
at a high level.

Student Book Content


ASP.NET Web Applications
Key Points
An ASP.NET Web application contains several different components, including the following:
Web Forms (.aspx pages), which provide the UI for the Web application.
Code, which resides in the .aspx page or in a code-behind page.
Configuration files, which are XML files that define the settings for the Web application and the Web server.

Question: Think of a typical production Web site with which you are familiar such as your company's intranet site.
How many different pages and other components may be required to build that Web site?
CD Content
An ASP.NET Web application contains different components. When you create a Web application, you must
understand how to implement and use all of these components.
Components
The components of an ASP.NET Web application include:
Web Forms, or .aspx pages. Web Forms provide the UI for the Web application.
Code-behind pages. Code-behind pages are associated with Web Forms and contain the server-side code for the
Web Form. You can also create a single-file ASP.NET page, which contains both the page markup and the .NET
Framework code in the same file.
Configuration files. Configuration files are XML files that define the settings for the Web application and the Web
server. Every Web application has one or more web.config configuration files. In addition, each Web server has only
one machine.config file.
Global.asax file. Global.asax files contain code for responding to application-level events that are raised by ASP.NET.

Module 01-Overview of the Microsoft .NET Framework página 20


Multimedia - ASP.NET Dynamic Compilation Execution Model
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


There is no sound in this animation.
Explain the steps as the multimedia runs:
• First, the request shows that the page is compiled and then processed.
• Second, the request shows that the page is directly processed.
Mention that, regardless of whether the page is in the cache, parsing will occur if the content changes
and recompiling will occur for any code change.

Student Book Content


Multimedia: ASP.NET Dynamic Compilation Execution Model
Key Points
ASP.NET Web pages and code files use dynamic compilation by default.
Dynamic compilation ensures that pages are compiled on first request.
Precompilation provides improved response time on first request and a means to identify errors.

Question: You are developing and testing a new Web site. This requires constant updates to multiple Web pages.
Which form of compilation would be the best choice for this scenario: dynamic compilation or precompilation?
CD Content
ASP.NET Web pages and code files use dynamic compilation by default when a user requests a resource for the first
time. The compiled resources are then cached, which ensures that subsequent requests are performed efficiently.
In this animation, you will see how dynamic compilation in ASP.NET works to send information to a requesting
client.
First Request
When the client requests a Web page for the first time, the following set of events take place:
1. The client browser issues a GET HTTP request to the server.
2. The ASP.NET parser interprets the source code.
3. If the code was not already compiled in a dynamic-link library (DLL), ASP.NET invokes the compiler.
4. The runtime loads and executes the Microsoft intermediate language (MSIL) code.

Module 01-Overview of the Microsoft .NET Framework página 21


Microsoft .NET Framework Resources
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


The goal in this lesson is to give students options for finding information about Microsoft .NET.
Microsoft MSDN®
Offers help for developers who write applications by using Microsoft products and technologies.
ASP.NET
The ASP.NET 2.0 site is a portal site for the ASP.NET development community.
Channel 9
Channel 9 is a Microsoft discussion forum used to promote conversations among Microsoft's
customers.
CodePlex
CodePlex is Microsoft's open source project hosting web site.

Student Book Content


Microsoft .NET Framework Resources
Key Points
There are many resources available to help you find further information and troubleshoot problems when you
develop by using the .NET Framework.
CD Content
The following list of resources provides you with a starting point to find more information about the .NET
Framework, along with answers to specific questions:
The .NET Framework documentation. You can access the .NET Framework documentation in two places.
Visual Studio 2008.
The Start menu of your Windows operating system.

Module 01-Overview of the Microsoft .NET Framework página 22


Overview of the Lab Application
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 3
Overview of the Lab Application
This lesson introduces the lab application that you will build throughout the remainder of this course. You will also
have the opportunity to explore a complete version of the lab application and understand some of its functionality.

Module 01-Overview of the Microsoft .NET Framework página 23


Lab Application Setup
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


This list gives a sense of the scale of the Web application project that the students will create by the
end of the course.
Throughout this course, students can choose to develop lab solutions by using either Microsoft Visual
Basic® or Microsoft Visual C#®.
Solutions are provided for both languages.

Student Book Content


Lab Application Setup
Key Points
In the labs in this course, you will build a complete ASP.NET Web application that simulates an internal Web site for
the fictitious company, Coho Winery. This fictitious Web site provides information to employees about their benefit
options.
Throughout this course, you can develop lab solutions by using either Microsoft Visual C# ® or Visual Basic.

CD Content
In the labs in this course, you will build a complete ASP.NET Web application that simulates an internal Web site for
the fictitious company, Coho Winery. This fictitious Web site provides information to employees about their benefit
options.
Details
The Benefits Web application includes the following components:
Two projects, which consist of a Web site and an XML Web service.
11 Web Forms that display the employee benefits information.
Two SQL Server databases.

Note:Throughout this course, you can develop lab solutions by using either Visual Basic or Visual C#.

The following table lists the Visual Basic and Visual C# components of the Benefits Web application.
Page or file name Description
benefitsMaster.mast Master page
er
Default.aspx Home page. Calls the BenefitsList component and lists the benefits options in a
CheckBoxList control
dental.aspx Calls the XML Web service to get a listing of dentists
doctors.aspx Lists the primary care physicians from the Doctors SQL Server database
growth.xml XML files with the prospectus information
lgcap.xml
midcap.xml
smcap.xml
header.ascx User control that is the header of each page

Module 01-Overview of the Microsoft .NET Framework página 24


header.ascx User control that is the header of each page
life.aspx Input form for life insurance data. Uses validation controls
Login.aspx Logon page for the Web site
medical.aspx Input form for medical data. The page used for selecting primary care physician from the
doctors.aspx page
mutual_funds.xml XML file containing the list of mutual funds
namedate.ascx User control that is used to gather name and birth date information. Used on the
medical.aspx page
nestedData.aspx Enables you to create a nested XML file from the several tables that the Doctors database
includes
prospectus.aspx Displays a retirement fund prospectus from an XML file by using a style sheet file
prospectus_style.xsl Style sheet file for displaying the prospectus
register.aspx Adds new users to the Coho Winery database
retirement.aspx Displays XML data from the mutual_funds.xml file in an HTML format
securitytest.aspx Displays the identity and the authentication method that is used to authenticate the current
user, to test the security system
web.config Configuration file
Benefits component Contains a Visual Basic or Visual C# component named Benefits that returns a list of benefit
options
DentalService Web Contains an XML Web service named DentalService.asmx. This XML Web service reads
service project information from the Dentists SQL Server database and returns the information as a dataset
Doctors.dbml LINQ to SQL Classes file

Module 01-Overview of the Microsoft .NET Framework página 25


Demonstration - The Lab Solution
Saturday, September 06, 2008
12:13 AM

Instructor Notes (PPT Text)


The lab application is an ASP.NET Web application named Coho Winery. Coho Winery is a fictitious
company that offers several benefits to its employees. The benefits proposed are Life Insurance,
Retirement, Medical, and Dental benefits.
The lab application is composed of the following:
• Several Web Forms
• A component
• Two user controls
• An XML Web service.
There are also two main databases: one that contains the list of doctors that are used for the medical
benefit and another that contains the list of dentists and is used by the XML Web services.
Note: This demonstration requires the AjaxControlToolkit.dll file that targets the official release
of .NET Framework 3.5 and Visual Studio 2008. Download the latest version of the
AjaxControlToolkit.dll file from the www.codeplex.com Web site and copy it to the E:\Democode\Lab
Solution\Benefits\Bin folder in the virtual machine.
To run the demonstration:
1. Click Start, point to All Programs, expand the Microsoft Visual Studio 2008 folder,
expand the Visual Studio Tools folder, and then click Visual Studio 2008
Command Prompt.
A Command Prompt window opens.
2. At the command prompt, type the following command, and then press ENTER.
aspnet_regsql -S LONDON\SQLExpress -E -ssadd
You must perform this step because the ASPState database does not exist in the virtual
machine for this lab.
3. Close the command prompt window.
4. In Visual Studio 2008 open the Benefits Web site from the E: \Democode\Lab Solution
folder.
5. Add the DentalService Web service to the solution.
6. In the Benefits Web site, delete and then recreate the DentalWebRe f Web reference
that points to the DentalService Web service.
7. Save and build the web site.
8. View the Default.aspx file in the browser.
9. Click Register New User.
10. Fill in the details of a user. Use Pa$$word as the password.
11. Click Create User
12. In the Default.aspx page, click the life insurance link.
13. Fill in a name, date of birth, and coverage and click one or both of the check boxes.
14. Click Save.
15. In the Default.aspx page, click the medical link.
16. On the medical page, use the link to select a doctor and then save the changes.
17. In the Default.aspx page, click Dental.
18. Click Get All Dentists.
19. Click Retirement account.
20. View one or more of the prospectus's.
21. Click Home.
22. Close Internet Explorer.
23. Close Visual Studio 2008.

Module 01-Overview of the Microsoft .NET Framework página 26


Student Book Content

Module 01-Overview of the Microsoft .NET Framework página 27


Overview of Visual Studio 2008
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 1
Overview of Visual Studio 2008
The Visual Studio 2008 integrated development environment (IDE) is the common user interface (UI) and set of
tools that you can use for all of the different project types and programming languages that Visual Studio 2008
supports. This lesson introduces the Visual Studio 2008 IDE.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 28
Why Visual Studio 2008
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


The key point regarding Microsoft® Visual Studio® 2008 is that it provides the tools to make students
better, faster, and more accurate programmers.
Mention several of the new features that Visual Studio 2008 provides. For example, mention multi-
targeting support and the inclusion of Windows Presentation Foundation (WPF), Windows
Communication Foundation (WCF), and Workflow designer and project support.

Student Book Content


Why Visual Studio 2008?
Key Points
Visual Studio 2008 simplifies the development of powerful and reliable enterprise Web solutions and increases
developer efficiency by providing a familiar, shared development environment. Visual Studio 2008:
Provides an IDE with a consistent look and feel, regardless of the programming language or application type.
Supports multiple languages and the development of multiple project types.
Supports debugging from your initial code through to the application release and customization at the window and
application level.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 29
Available Project Templates
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Emphasize that a solution contains multiple related projects and these projects contain multiple Web
pages called Web Forms. This is a critical concept for the organization of Web applications.
Do not spend more than the allotted time on this information.
Note: Open Visual Studio 2008 before you display this slide and show the New Project dialog box.
Also, the creation of test projects may be available only with specific editions of Visual Studio such as
Team Foundation Suite Edition. Ensure that students are aware of this; test project availability can be
verified only after the product is officially released.

Student Book Content


Available Project Templates
Key Points
Visual Studio 2008 provides templates that support the creation of a number of common project types. These
templates contain all of the required files and ensures that the IDE has the correct configuration for the selected
project.
When you create a project in Visual Studio 2008, you also create a larger container called a solution that can also
contain multiple projects.
Visual Studio 2008 includes multiple project templates in different languages.
Question: What project templates does Visual Studio 2008 provide?

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 30
Integrated Development Environment
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information, especially if the
Visual Studio 2008 integrated development environment (IDE) is familiar to your students or they
have used previous versions of Visual Studio.
Explain the environment settings that are available when you open Visual Studio for the first time.
Note: Do not go into too much detail demonstrating the Object Browser; a quick look is all that is
required. You can come back to this later in this module to examine the hierarchy of namespaces if
required.
Alternative delivery: You can open Visual Studio 2008 and show the screens as you talk about what
each screen does. If so, demonstrate the environment settings that are available when you open
Visual Studio for the first time. Demonstrate features such as autohide, docking, floating, closing, and
opening of windows. If time permits, also point out the window layout options and tabbed documents
versus multiple documents. You can also briefly discuss other useful options here; for example,
discuss the default HTML designer view and full screen mode (developers that use multiple monitors
can take advantage of these options).

Student Book Content

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 31
Creating an ASP.NET Web Application Project
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content

The following table lists the additional project templates that are available in Visual Studio 2008.
Template Description
Group
Visual C++ Visual Studio 2008 includes templates for ATL projects, managed applications, managed class
Projects libraries, and managed Web services.
Other Projects Visual Studio 2008 includes templates for setup and deployment projects, database projects,
extensibility projects, and blank solutions.
Test Projects Visual Studio 2008 provides a template for a test project.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 32
The Development Process
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


The goal of this topic is to show how much of the development process is supported by Visual Studio
2008.
This is an additional opportunity to highlight the content that will be covered in this course, as shown
in the following list:
• Create a new project: Modules 2 and 4
• Create the interface and write code: Modules 2, 3, and 4,
• Build: All modules
• Test and Debug: Modules 2 and 6
• Deploy: Module 13 (XML Web services) and Module 16 (Web applications)
Note that some design features are available in Visual Studio 2008 (for example, class diagrams).

Student Book Content


The Development Process
Key Points
Visual Studio 2008 contains everything you require to build your own ASP.NET Web application from start to finish.
To create an ASP.NET Web application by using Visual Studio 2008, you must perform the following basic steps:
1. Create a design specification.
2. Create a new project.
3. Create the interface and write code.
4. Build.
5. Test and debug.
6. Deploy.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 33
Web Application Types and File Structure
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


The goal of this topic is to explain the two project templates for the creation of Web applications and
to show the students where the files are located.
Remind the students that this can be a good resource for later in the course when they are trying to
identify where the files are located.
Note: The choice of project template can be a good point to generate some discussion on your choice
of project. Discussion will enable the students to gain a deeper understanding of how to choose a
particular template to start a project. For more information about the differences between the two
templates, see http://go.microsoft.com/fwlink/?LinkId=110685
Alternative delivery: You can open Visual Studio 2008 and show the screens as you talk about what
each screen does. If time permits, show the use of both templates, show the hidden folders in
Solution Explorer, and open Microsoft Windows® Explorer to show the files that are created.

Student Book Content


Web Application Types and File Structure
Key Points
In Visual Studio 2008, you can create a Web application by using two different templates:
ASP.NET Web Application project template. Provides a Web project model that is similar to the Visual Studio 2003
Web project model.
ASP.NET Web Site project template. Provides a Web project model with more features and additional flexibility in
the management of Web applications.

The choice of project template depends on your requirements and your preferred development workflow.
Question: When you create a Web application, what files does Visual Studio provide?

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 34
Web Application Files
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


This slide lists only the most important file types. The two most important file extensions for the
students are .aspx (Web Form) and .aspx.vb or .aspx.cs (code-behind page). To avoid later confusion,
emphasize the difference between a solution, a project, and a Web Form.
Alternative delivery: You can open Solution Explorer and show the files with extensions.

Student Book Content


Web Application Files
Key Points
In Visual Studio 2008, you can create a number of files that support the development of your Web application:
Web application files. Visual Studio 2008 supports a number of application file types and extensions such as
ASP.NET Web Forms (.aspx), ASP.NET Web services (.asmx), and classes and code-behind pages (.vb or .cs).
Other files. Any files that are not based on a programming language will have their own extensions. For example, a
Crystal Report file uses the .rpt extension and a text file uses .txt.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 35
Demonstration - Creating a Web Application Project
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Explain to the students that the goal of this demonstration is to show the files and default code that
are created when they start a new project.
This demonstration also shows how to add controls to the application.
• Populate the ASP.NET Web Form
1. Create a new ASP.NET Web Application project.
2. Open the Default.aspx file in Design view.
3. Add a Button control and a Label control.
4. Select the label and in the Properties window, change the ID property to
messageLabel.
5. Double-click the Button control to open the code-behind page for the Web Form, and
then add the following comment to the event procedure.
[Visual C#]
//TODO: Write Hello World
[Visual Basic]
'TODO: Write Hello World
A new task is automatically added to the Task List because of the TODO token.
• Add a new ASP.NET Web Form
• Add a new Web Form named login.aspx to the Web application project.
• Add a new project
• Add a new ASP.NET Web Service project named MyFirstWebService to the solution.
• Write code for the Button control
1. In the Task List window, in the Categories list, click Comments, and then double-click
the TODO: Write Hello World task.
The correct file is opened and the cursor is placed at the correct spot in the code.
2. Write the following code.
[Visual C#]
messageLabel.Txt = "Hello World!";
[Visual Basic]
messageLabel.Txt = "Hello World!"
Note: This is a syntax error because the code sets the Txt property instead of the Text property. This
error is there to show the students what happens when the build fails.
3. Remove the TODO from the TODO: Write Hello World comment.
The TODO task disappears automatically from the Task List.
• Build and debug the solution
1. Verify that the Web application is the startup project.
2. Build the solution and verify that an error message is added to the Task List because Txt
is not a member of System.Web.UI.We bControls.Label.
3. Double-click the error message in the Task List. The cursor jumps to the correct spot in
the code.
4. Correct the syntax error.
[Visual C#]
messageLabel.Text = "Hello World!";
[Visual Basic]
messageLabel.Text = "Hello World!"
5. Rebuild the solution and verify that it succeeds.
6. View the Web Form in a browser and ensure it displays the message Hello World when
you click the Button control.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 36
Student Book Content
Demonstration: Creating a Web Application Project
Question: How can you can build and browse a Web Form in one step?
CD Content
In this demonstration, the instructor will show you how to create a Web application and implement some simple
functionality.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 37
Overview of the Microsoft .NET-Based Languages
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Overview of the Microsoft .NET-Based Languages
The .NET Framework supports many programming languages; it is designed to support an unlimited number of
development languages, assuming that those languages conform to .NET Framework requirements. The .NET
Framework class library is an object-oriented library that is composed of namespaces which are reusable types that
reduce development time.
This lesson describes the programming languages that are supported by the .NET Framework. It also introduces
namespaces, which are a fundamental feature of the .NET Framework and the .NET Framework-based languages.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 38
Multiple Language Support
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Multiple Language Support
Key Points
The .NET Framework supports a theoretically infinite number of development languages. The design of the .NET
Framework enables developers to use their preferred language when they develop .NET applications and provides
benefits such as reusable code modules.
CD Content
The .NET Framework supports a theoretically infinite number of development languages. The design of the .NET
Framework enables developers to use their preferred language when they develop .NET applications. Currently,
the .NET Framework supports many languages. The following table lists some of these languages.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 39
The Common Language Runtime
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


List some of the supported languages.
Briefly explain the concept of Microsoft intermediate language (MSIL). Explain that all .NET Framework
languages are compiled to MSIL and then to native code. Do not go into detail because this concept is
covered in a later slide.

Student Book Content

The Common Language Runtime


Key Points
The common language runtime (CLR) is the runtime engine of the .NET Framework. The CLR manages application
threading and garbage collection. The CLR ensures that a .NET application is secure and will run properly.
The CLR ensures that the correct version of the dynamic-link library (DLL) is available for the application. Thus, the
CLR allows multiple versions of a DLL to exist and run at the same time.
CD Content
The common language runtime (CLR) is the runtime engine of the .NET Framework. The CLR also provides several
other services; for example, it provides code security and solves DLL versioning problems.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 40
Runtime Compilation and Execution
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Explain the role and importance of the CLR.
Talk briefly about several of the different components.
The available components are as follows:
• .NET Framework class library support
• Thread support
• Type checker
• Exception manager
• Debug engine
• Garbage collector
• Class loader
• MSIL to Native compilers
• Code manager
• COM marshaler

Student Book Content


Runtime Compilation and Execution
Key Points
Each .NET-compatible language provides its own compiler to compile code to Microsoft intermediate language
(MSIL).
After the code is compiled to MSIL, the CLR compiles the MSIL to native code by using a just-in-time (JIT) compiler
and then runs the application.
After the application is JIT-compiled, it is cached so that it does not have to be recompiled for each request.
After the application is compiled, the CLR executes the application on the Web server and then generates the HTML
and script that is returned to the client.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 41
What Are Namespaces
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Explain how a Web page is complied to MSIL. Also explain JIT compilation and application execution.
Mention that if any code file is changed, the whole process begins again. Point out the difference for a
precompiled Web application.

Student Book Content


What Are Namespaces?
Key Points
Namespaces provide a logical grouping of classes that can be used by all .NET-compatible development languages.
Each namespace contains types that you can use in your application.
CD Content
The .NET Framework class library is an object-oriented library that is composed of namespaces. The library is a
collection of reusable types (classes, structures, enumerations, delegates, and interfaces) that reduces development
time and increases cross-language support.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 42
Comparison of the Microsoft .NET-Based Languages
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Check if the students are familiar with the concept of namespaces.
Open the Object Browser to show that the namespaces are hierarchical.

Student Book Content


Comparison of the Microsoft .NET-Based Languages
Key Points
The choice of development language for your Web application mainly depends on your previous development
experience.
Browser compatibility is not a consideration when you choose a .NET Framework-based development language
because ASP.NET code runs only on the server.
CD Content
The CLR is used for JIT compilation from MSIL to native code and provides an environment to run that code. Specific
language compilers are used to compile to MSIL code, for example, CSC for Visual C# and VBC for Visual Basic. The
choice of development language for your Web application mainly depends on your previous development
experience.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 43
Creating a Component by Using Visual Studio 2008
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Explain why it is important to know both the Microsoft Visual C#® and Microsoft Visual Basic®
languages.
You can emphasize that there can be situations, for example, when Visual Basic developers may have
to read Visual C# source code (similarly for Visual C# developers).
Highlight the fact that there is a possibility that developers may have to work on a solution that
contains projects in both languages.

Student Book Content


Lesson 4
Creating a Component by Using Visual Studio 2008
When you use an object-oriented language to develop an application, you can use existing classes and components.
You can use Visual Studio 2008 to create a component and use it in other applications.
This lesson introduces classes and components. It explains how to create a component by using Visual Studio 2008
and how to use that component in other applications.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 44
What Are Classes and Components
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


What Are Classes and Components?
Key Points
When you use an object-oriented language (such Visual C# or Visual Basic) to develop an application, you can use
existing classes and components:
Classes are groups of code statements that provide functionality in an application.
Components are classes that are compiled into a DLL file. Because the component is its own file, you can reuse it in
different parts of an application.

CD Content
When you use an object-oriented language (such Visual C# or Visual Basic) to develop an application, you can use
existing classes and components. For example, the .NET Framework class library consists of many classes.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 45
Creating a Class
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Key terminology:
• Class
• Property
• Method
• Object
• Component
Ensure that the students can confidently explain the difference between each of these concepts.

Student Book Content


Creating a Class
Key Points
When you create a class in a project, the class file is compiled into the application DLL and cannot be reused by
other applications. If you create a class library, you create a component that you can reuse.
CD Content
In object-oriented languages, the concept of abstraction is important. Abstraction is a form of organization in which
methods, data, and functions that serve a common purpose are grouped together. A fundamental component of
abstraction is the creation and use of classes.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 46
Accessing Components in an ASP.NET Web Form
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Briefly explain how to creating a class. Also explain the default code that is generated.

Student Book Content


Accessing Components in an ASP.NET Web Form
Key Points
Classes that you create in a component are available to other programs. First, you must reference the compiled
assembly of the component (DLL). Then, to access the methods in the class, you instantiate the class object by
referencing its namespace and class name. All of the public methods in the class are available for use.
CD Content
Classes that you create in a component are available to other programs. First, you must reference the component
(DLL). The component does not necessarily have to be a .NET Framework component; it can be another project in
your solution or a COM DLL. Then, to access the methods in the class, you instantiate the class object by referencing
its namespace and class name.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 47
Demonstration - Creating a Class in Visual Studio 2008
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Ensure that the students are familiar with the concept of referencing a DLL.
Explain the code required to instantiate and use the object.
Note: Explain the use of the namespace keyword. In Visual C#, the root namespace is in code; in
Visual Basic, the root namespace is in the project properties. Identify that CompanyA is the root
namespace here.

Student Book Content


Demonstration: Creating a Class in Visual Studio 2008
Question: When you compile a class, where is the .dll file stored?
CD Content
In this demonstration, the instructor will show you how to create a component and call it from a Web application.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 48
Lab - Creating Web Applications by Using Microsoft Visual Studio
2008 and Microsoft .NET-Based Languages
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Explain to the students that the goal of this demonstration is to show how to create a class library and
call a class from an ASP.NET page. This demonstration also briefly explains the ASP.NET folders.
• Create a new Class Library project
1. Create a new ASP.NET Web Site project in Visual C# or Visual Basic.
2. Add a new Class Library project named HelloWorld.
3. A default class, Class1, is created. Show the Class1.cs or Class1.vb file.
4. Rename the class to Hello.
• Create a method that returns a string
1. Create a SayHello method that returns a string.
[Visual C#]
public string SayHello()
{
return "Hi from C# component.";
}
[Visual Basic]
Function SayHello() As String
Return "Hi from Visual Basic .NET component."
End Function
2. Build the project.
3. In the Web site, add a reference to the HelloWorld component.
4. Expand the Bin folder in the Web application project and show that the HelloWorld.dll
file has been copied there. Ensure that Show All Files is selected in Solution Explorer.
• Call the class from an ASP.NET page
1. In the Web application, open Default.aspx in Design view.
2. Place a Button control on the page and create a Click event procedure for it.
3. Add the following code to the Click event procedure, showing the Microsoft IntelliSense
for the HelloWorld component and the myHelloClass variable.
[Visual C#]
HelloWorld.Hello myHelloClass = new HelloWorld.Hello();
Button1.Text = myHelloClass.SayHello();
[Visual Basic]
Dim myHelloClass As New HelloWorld.Hello()
Button1.Text = myHelloClass.SayHello()
4. Build and browse Default.aspx, and then click the button.
• Create a class in the App_Code folder
1. Visual Studio prompts you to place the class in the App_Code folder.
2. Explain the App_Code and Bin shared code folders. When you store compiled
assemblies in the Bin folder, other code anywhere in a Web application can automatically
reference it. When you store source code in the App_Code folder, and it will be
automatically compiled at run time. Also, you can configure your Web application to
regard subfolders of the App_Code folder as separate compilable units, enabling you to
use Visual C# and Visual Basic in different sub folders of the App_Code folder.
3. If time permits, explain the ASP.NET folders and how to add them:
• Bin. Contains compiled assemblies (.dll files) for controls, components, or other code that you
want to reference in your application.
• App_Code. Contains source code for utility classes and business objects (for example, .cs, .vb,
and .jsl files) that you want to compile as part of your application.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 49
Student Book Content
Lab: Creating Web Applications by Using Microsoft Visual Studio
2008 and Microsoft .NET-Based Languages
Exercise 1: Creating an ASP.NET Web Site
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits. The list of benefits that Coho Winery offers is
displayed on several pages in the Web site. Rather than code the list on every Web page that displays the offered
benefits, you have been asked to develop a component that returns the benefit names.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 50
Exercise 1 - Creating an ASP.NET Web Site
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)

Student Book Content

CD Content
Review Questions
1. How would you select a .NET-based language to create a new Web application project?
Based on the developer's experience with existing languages.
2. What role does the common language runtime play in running an ASP.NET page?
The common language runtime compiles the MSIL to native code and then runs the native code on
the server.
3. What is the role of the JIT compilation?
The runtime uses a JIT compiler to compile the MSIL to native code. The runtime uses a JIT
compiler to compile the MSIL to native code. The runtime uses a JIT compiler to compile the MSIL
to native code.
4. List three languages that are currently supported by .NET.
Examples include Visual Basic, Visual C#, C++, Perl, and Cobol.
5. Why would you create a component for a Web application?
To share business logic code with other applications.

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 51
Exercise 2 - Creating a Class
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


In this lab, students will create a component that contains an array that holds the name of a benefit
and the name of the Web page that implements that benefit. Make students aware of the differences
between debugging and viewing a page in the browser. Point out that the Web.config file requires
modification to enable debugging; Visual Studio 2008 prompts for this. Debugging is presented in a
later module.
Exercise 1
In this exercise, students will create an ASP.NET Web Site named Benefits.
Exercise 2
In this exercise, students will create a class named Benefits that returns a string of names.
Exercise 3
In this exercise, students will write code to test the Benefits class in a Web page and extend the
Benefits class to display an extra benefit.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 52
Exercise 3 - Calling the Component
Saturday, September 06, 2008
12:15 AM

Instructor Notes (PPT Text)


Coho Winery offers several benefits to its employees. In this lab, students will create a Microsoft
ASP.NET Web Site project for a Benefits Web site that enables employees to select and set up their
chosen benefits.
The list of benefits that are offered by Coho Winery is displayed on several pages in the Web site.
Rather than code the list on every Web page, students have been asked to develop a component that
returns the benefit names. Students will create a component that contains an array that holds the
benefit name and the name of the Web page that implements that benefit.

Student Book Content

Module 02-Creating Web Applications by Using Microsoft Visual Studio 2008 and Microsoft .NET-Based Languages página 53
Creating Web Forms
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 1
Creating Web Forms
This lesson describes how to create a Web Form. It also explains how to identify the key characteristics of Web
Forms.

Module 03-Creating a Microsoft ASP.NET Web Form página 54


What Is a Web Form
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)

Student Book Content


What Is a Web Form?
Key Points
The Web Form generates HTML and sends it to the browser.
The supporting code and controls that run the UI stay on the Web server.
This UI/code split increases the range of supported browsers and the security and functionality of the Web Form.

Question: What are the key differences in the @ Page attributes for the two types of Web Forms (single file and
two file)?
CD Content
Web Forms consist of a combination of markup, code, and controls that execute on a Web server that is running
Microsoft Internet Information Services (IIS). To display a UI, Web Forms generate HTML and send it to the browser,
and the supporting code and controls that run the UI stay on the Web server. This split between client-side interface
and server-side code is a crucial difference between Web Forms and traditional Web pages. With a traditional Web
page, all of the code is processed at the browser. However, Web Forms send only the interface controls to the
browser, and the page processing remains on the server. This UI/code split increases the range of supported
browsers and the security and functionality of the Web page.
.aspx Extension
Web Forms are commonly referred to as ASP.NET pages or ASPX pages. Web Forms have an .aspx extension and are
the containers for the text and controls that you want to display on the browser.
ASP.NET (.aspx) pages and Active Server Page (ASP) pages can coexist on the same server. The file extension
determines if ASP or ASP.NET processes the page.
Web Forms often consist of two separate files: the .aspx file contains the UI for the Web Form and the .aspx.vb
or .aspx.cs file, which is called a code-behind page, contains the supporting code.

Module 03-Creating a Microsoft ASP.NET Web Form página 55


Creating a Web Form by Using Visual Studio 2008
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Use a brief demonstration to illustrate the different ways to create a Web Form.

Student Book Content


Creating a Web Form by Using Visual Studio 2008
Key Points
To add an additional Web Form to an application, perform the following steps:
1. In Solution Explorer, right-click the project or Web site name, and then click Add New Item.
2. In the Add New Item dialog box, click Web Form, type the name of the Web Form, and then click Add.
CD Content
You can use two main methods to create a Web Form.

Module 03-Creating a Microsoft ASP.NET Web Form página 56


Adding Server Controls to a Web Form
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 2
Adding Server Controls to a Web Form
This lesson describes how to use ASP.NET server controls such as buttons, text boxes, and lists. These server
controls are different from HTML controls in that the supporting logic runs on the server and not on the user's
browser.

Module 03-Creating a Microsoft ASP.NET Web Form página 57


What Is a Server Control
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Again, the key point is the runat="server" attribute. Highlight the round trip to the server that the
runat="server" attribute requires.
During the discussion of the browser-specific HTML, mention that it is possible to detect the browser
capabilities in the page request and then run appropriate code. For example you can use this
technique to redirect to a mobile Web application when a mobile device is detected.

Student Book Content


What Is a Server Control?
Key Points
ASP.NET server controls are components that run on the server and encapsulate UI and other related functionality.
They include buttons, text boxes, and lists.
The following is the XHTML that you would write to create a text box with the default text Enter your Username.
<asp:TextBox id="TextBox1" runat="server" Width="238px" Height="25px">Enter your
Username</asp:TextBox>

CD Content
ASP.NET server controls are components that run on the server and encapsulate UI and other related functionality.
You use server controls in ASP.NET pages and in ASP.NET code -behind classes. Server controls include buttons, text
boxes, and lists.
The following is an example of a Button server control.
<asp:Button id="Button1" runat="server" Text="Submit" />

Runat="server"•
Server controls have a runat="server" attribute, the same attribute as Web Forms. This means that the logic in
the control runs on the server and not on the user's browser. Server controls are different from HTML controls,
which run only on the client's browser.
Another feature of server controls is that the view state, the settings, and the user input of the control are
automatically saved when the page is sent back and forth between the client and the server. Traditional HTML
controls are stateless and revert to their default settings when the page returns from the server to the client.
Built-in Functionality
The functionality of a control is what happens when the user clicks a button or a list box. These processes are called
event procedures. As the Web Form programmer, you determine which event procedures to implement for each
server control.

Module 03-Creating a Microsoft ASP.NET Web Form página 58


Types of Server Controls
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information. Each option will be reviewed in context
in later modules in this course.
Mention that students can modify both server-side control types to run client-side code, which gives
them additional flexibility.

Student Book Content


Types of Server Controls
Key Points
There are many types of sever controls that are available in ASP.NET. These are broadly divided into HTML server
controls and Web server controls.
HTML elements on a Web Form are not available to the server.
Web server controls include form-type controls such as buttons and text boxes and also special-purpose controls
such as calendars.

Question: What types of server controls does your company use in its Web applications?

Module 03-Creating a Microsoft ASP.NET Web Form página 59


Saving View State
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Do not spend more that the allotted time on this information. Saving state is covered in depth in
Module 14, Managing State.

Student Book Content


Saving View State
Key Points
View state records the state of controls on a Web Form.
View state can be disabled at the page level and enabled for individual controls.
ASP.NET 2.0 introduced control state in addition to view state.

Question: Why is it important to save the state of controls?


CD Content

Module 03-Creating a Microsoft ASP.NET Web Form página 60


HTML Server Controls
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Explain that students can convert HTML controls to HTML server controls to make them available to
the server.

Student Book Content


HTML Server Controls
Key Points
HTML server controls can be exposed as elements to your server-side code. This conversion enables you to use the
controls to trigger events that are handled on the server.
HTML server controls include the runat="server" attribute.

CD Content
HTML controls on a Web Form are not available to the server. By converting HTML controls to HTML server controls,
you can expose them as elements to your server-side code. This conversion enables you to use the controls to
trigger events that are handled on the server.

Module 03-Creating a Microsoft ASP.NET Web Form página 61


Web Server Controls
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Cover the different types of controls: intrinsic, validation, rich, list -bound and login.
Explain that all controls share common attributes, for example the id attribute.
Cover several of the key standard controls such as text box, button and list box. If you have time,
perform a quick demonstration of some of these controls. Add some of the more common intrinsic
controls to a page. Display the page in the browser and view the source of the page.
Do not go into too much detail when you present the sections on validation controls and list -bound
controls because these are covered in more depth in later modules.

Student Book Content


Web Server Controls
Key Points
Intrinsic Web server controls correspond to simple HTML elements.
Validation controls are hidden controls that validate the user's input against predetermined patterns.
Rich controls provide a rich functionality to your Web Form by inserting complex functions into your Web Form.
List-bound controls can display data from a data source.

Module 03-Creating a Microsoft ASP.NET Web Form página 62


Discussion - Selecting the Appropriate Control
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Discuss with the students situations where they might use HTML or Web server controls.
During the discussion, emphasize that the best practice is to avoid HTML server controls. Discuss
which of the reasons to use HTML controls might be the most important (for example, the use of the
HTML document object model (DOM).) However, as stated in the module the HTML DOM is not as
capable as the programming model behind ASP.NET Web server controls.
If students express an interest in how to add client script to Web server controls, use the code
provided in the article at http://go.microsoft.com/fwlink/?LinkId=110688 to provide a brief
demonstration.

Student Book Content

Validation Controls
Validation controls are hidden controls that validate the user's input against predetermined patterns. The following
table describes some of the commonly used validation controls.
Control Function
CompareValidator Requires that the input matches a second input or existing field.
CustomValidator Requires that the input match a condition such as prime or odd numbers.
RangeValidator Requires that the input match a specified range.
RegularExpressionV Requires that the input matches a specified format such as a U.S. telephone number or a
alidator strong password with numbers and letters.
RequiredFieldValidat Requires that the user enters some value before the control is processed.
or
ValidationSummary Collects all of the validation control error messages for centralized display.

Module 03-Creating a Microsoft ASP.NET Web Form página 63


Creating Master Pages
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content

Rich Controls
Rich controls provide a rich functionality to your Web Form by inserting complex functions into your Web Form. The
following table describes several of the presently available rich controls.
Control Function
AdRotator Displays a sequence (predefined or random) of images.
Calendar Displays a graphic calendar on which users can select dates.
Menu Displays both static and dynamic menus.
TreeView Displays hierarchical data (such as a table of contents or file directory) in a tree structure.
Wizard Provides navigation and a UI to collect related data across multiple steps.

List-Bound Controls
List-bound controls can display data from a data source. The following table describes some of the commonly used
list-bound controls.
Control Function
BulletedLi Displays a list of items in a bulleted format.
st
CheckBox Displays data as a column of check boxes.
List
Repeater Displays information from a data set by using a set of HTML elements and controls that you specify.
The Repeater control repeats the element once for each record in the data set.
DataList Displays information from a data set. Similar to the Repeater control but with more formatting and
layout options, including the ability to display information in a table. The DataList control also
allows you to specify editing behavior.
DropDown Displays data as a drop-down list.
List
GridView Displays information from many different kinds of data sources, including databases, XML files, and
business objects that expose data.
ListBox Displays data in a window.
ListView Displays data in a format that you define by using templates and styles. Implicitly supports edit,
insert, and delete operations in addition to sorting and paging functionality.
RadioButt Displays data as a column of option buttons.
onList

Module 03-Creating a Microsoft ASP.NET Web Form página 64


Module 03-Creating a Microsoft ASP.NET Web Form página 65
What Are Master Pages
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Discuss the key features of master pages. Ensure that the students understand that the purpose of
master pages is to simplify the process of creating a Web site that has a consistent layout.

Student Book Content

Module 03-Creating a Microsoft ASP.NET Web Form página 66


Content Pages
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Explain how the content page references a master page and describe the steps required to create a
content page.

Student Book Content


The child master page contains content controls that map to content placeholders on the parent master page. In
addition, the child master page also has its own content placeholders. These placeholders display content supplied
by the child's content pages or further child master pages.

To create a master page


To create a master page, use the following steps.
1. In Solution Explorer, right-click the project, and then click Add New Item.
2. In the Add New Item dialog box:
a) In the Templates pane, click Master Page.
b) In the Name box, type a name for the new page, and then click Add.

Module 03-Creating a Microsoft ASP.NET Web Form página 67


Runtime Behavior of Master Pages
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Describe the process that takes place when a user requests a content page from a browser.

Student Book Content


Runtime Behavior of Master Pages
Key Points
The full process of the runtime behavior of master pages is as follows:
1. The user types the URL of the content page to request the page.
2. ASP.NET reads the @ Page directive of the content page. If the directive contains a MasterPageFile
attribute, ASP.NET retrieves the master page.
3. ASP.NET merges the master page content into the control tree of the content page.
4. ASP.NET renders the final merged page to the browser.

CD Content

Module 03-Creating a Microsoft ASP.NET Web Form página 68


Discussion - Advantages of Master Pages
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Discuss the advantages of master pages.

Student Book Content


Discussion: Advantages of Master Pages
Key Points
There are several advantages of master pages.
Question: What are some of the advantages of master pages?
CD Content
There are several advantages of master pages. By using master pages you can:
Improve the maintenance of Web sites because you can make updates in one place that affect all of the pages in
that Web site.

Module 03-Creating a Microsoft ASP.NET Web Form página 69


Lab - Creating a Microsoft ASP.NET Web Form
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


In this lab, students will create a Microsoft ASP.NET Web Form.
Exercise 1
In this exercise, students create a Microsoft ASP.NET Web Form and populate it with Web controls.
Exercise 2
In this exercise, students create a master page for the Benefits Web application.
Exercise 3
In this exercise, students create the life.aspx Web Form.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Creating a Microsoft ASP.NET Web Form
Exercise 1: Creating the Default.aspx Web Form
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.

Module 03-Creating a Microsoft ASP.NET Web Form página 70


Exercise 1 - Creating the Default.aspx Web Form
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Coho Winery offers several benefits to its employees. In this lab, students will create the user
interface (UI) of the default.aspx and life.aspx Web Form pages in the Benefits Web application. The
default.aspx Web Form is the home page for the Benefits Web site. The default.aspx Web Form
displays the list of benefits that are offered by the company. The life.aspx Web Form allows users to
enter life insurance information such as their name, birth date, and coverage amount .

Student Book Content

5. Click OK to close the ListItem Collection Editor dialog box and save the new items.
6. Save the Default.aspx Web Form.
7. View the Default.aspx page in the browser.
8. Ensure that the items in the CheckBoxList control are correctly displayed.
9. Close the browser window.

Results:After this exercise, you have added a user control, a list-bound control, a Button control, and a Label
control to the Default.aspx page.

Module 03-Creating a Microsoft ASP.NET Web Form página 71


Exercise 2 - Creating the benefitsMaster Master Page
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. What categories of server controls are used in the lab?
Intrinsic and rich.
2. What content in the life.aspx page comes from the master page?
The header control and the red wine logo.
3. Which other pages in the application can use the master page?
Default and medical.

Student Book Content


Exercise 2: Creating the benefitsMaster Master Page
Scenario
In this exercise, you will create a master page for the Benefits Web site. This page contains a header and a logo,
which must be displayed on several pages in the Web site.
The main tasks for this exercise are as follows:
1. Create the master page.
2. Add items to the master page.

Task1: Create the master page


Create a new master page named benefitsMaster.master.

Task2: Add items to the master page


The master page will contain a header and a logo. You will place these items inside a table on the master page. The
logo is stored in the file RedWine.jpg, which you must add to the Benefits Web site.
1. Open the benefitsMaster.master page in Design view.
2. In the benefitsMaster.master page, click at the very start of the page, before the ContentPlaceHolder
container on the page.
3. Use the Table menu to insert a one row, two column HTML table on the master page.
4. Create a subfolder named Images in the Benefits Web site.
5. Add the file E:\Labfiles\Starter\RedWine.jpg to the Images folder in the Benefits Web site.
6. In Solution Explorer, use a drag-and-drop operation to place the file RedWine.jpg in the left hand cell of the
table on the benefitsMaster page.
7. In the Accessibility Properties dialog box, in the Alternate text box, type Coho Winery logo and then
click OK.
8. Set the height and width of the RedWine.jpg image to 35 pixels wide and 60 pixels high.

Module 03-Creating a Microsoft ASP.NET Web Form página 72


Exercise 3 - Creating the life.aspx Web Form
Saturday, September 06, 2008
12:17 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• You want to add a Web Form to your Web site. How can you do this?
In Solution Explorer, right-click the project or Web site name, click Add New Item, and then
use the Add New Item dialog box to add a new Web Form to your Web site.
• You want to share content among multiple pages in a Web application. What is the best approach
and why?
Use a master page because it gives your application a consistent layout.
Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.

Student Book Content


Exercise 3: Creating the life.aspx Web Form
Scenario
In this exercise, you will create the UI for the life.aspx page. This page implements the life insurance benefit for your
company. The life.aspx page will use the file benefitsMaster.master as its master page.
The main tasks for this exercise are as follows:
1. Create the life.aspx Web Form
2. Add controls to the life.aspx Web Form

Task1: Create the life.aspx Web Form


Create a new Web Form named life.aspx that uses the benefitsMaster file as its master page.

Task2: Add controls to the life.aspx Web Form


You will use a table to define the layout of the controls on the life.aspx Web Form.
1. Open the life.aspx page in Design view.
2. In Design view, click the life.aspx Web Form, inside the ContentPlaceHolder1 container.
3. In the ContentPlaceHolder1 container, insert a carriage return.
4. On the Table menu, click Insert Table.
5. Create a table that has 9 rows and 3 columns.
6. In the Toolbox, drag controls into the table as follows:
a) In the first column of the table, drag Label controls into the third, fourth, and fifth rows. Drag a CheckBox
control into the seventh row and a Button control into the ninth row.
b) In the second column of the table, drag a Label control into the first row. Drag TextBox controls into the

Module 03-Creating a Microsoft ASP.NET Web Form página 73


b) In the second column of the table, drag a Label control into the first row. Drag TextBox controls into the
third, fourth, and fifth rows. Drag a CheckBox control into the seventh row.
c) In the third column of the table, drag a Label control into the third row.
d) In the third column of the table, select the cells in rows 4 to 8.

Module 03-Creating a Microsoft ASP.NET Web Form página 74


Implementing Code-Behind Pages
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 1
Implementing Code-Behind Pages
You can add code to your Web Form in the same file as the Web content, in a separate SCRIPT section of the same
file, or in a separate file. Code-behind pages contain all of the programming logic for a single Web page. Inline code
uses HTML and code in separate sections of a single .aspx file.
This lesson explains how to implement code with Visual Studio 2008. It also explains how to use code -behind pages
and how they are different from inline code.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 75


Methods for Implementing Code
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


This topic focuses on the difference between inline code and code-behind pages.

Student Book Content


Methods for Implementing Code
Key Points
You can add code to your Web Form in the following three ways:
Mixed code. The code is in the same file as the Web content.
Inline code. The code is in a separate SCRIPT section of the same file as the HTML content.
Code-behind. The code is in a separate file from the HTML content.

Question: .What are the advantages and disadvantages of each method?

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 76


Writing Inline Code
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


This slide provides a contrast between inline code and code-behind pages.
Emphasize that if the students write inline code, the code is directly inserted in the .aspx Web Form.
Also explain that the separation in the file is for clarity only.

Student Book Content


Writing Inline Code
Key Points
You may encounter pages that use inline code, especially pages that were developed for ASP.
Inline code places HTML and code in separate sections of a single .aspx file. This separation is for clarity; the code
and HTML can exist anywhere on the page.

CD Content
Although the default method for implementing server-side code in Visual Studio 2008 is to use a code-behind page,
you may encounter pages that use inline code, especially pages that were developed for ASP.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 77


What Are Code-Behind Pages
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Emphasize that the use of code-behind pages is the default way to write code for ASP.NET Web Forms.

Student Book Content


What Are Code-Behind Pages?
Key Points
Visual Studio 2008, by default, uses code-behind pages to implement server-side code. The programming logic for a
Web page is in a separate file than the visual elements of the page, enabling developers and designers to work
simultaneously.
Each Web page in a Web application has its own code-behind page. The code-behind page has an .aspx.vb
or .aspx.cs extension.
CD Content

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 78


How Code-Behind Pages Work
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Explain that the association between the files is important and that a code-behind page must be
compiled before it is run.
Ensure students are comfortable with the difference between pre-compilation and just-in-time (JIT)
compilation.
You must you the Src attribute in conjunction with the @Register directive for user controls, which
implies they are JIT compiled. This point can be made and expanded on in Module 7, "Creating and
Implementing User Controls."

Student Book Content


How Code-Behind Pages Work
Key Points
For code-behind pages, each .aspx page must be associated with a code-behind page, and that code-behind page
must be compiled before information is returned to a requesting client browser. The .aspx page and the code -
behind page form a single unit when the Web application is run.
Visual Studio 2008, by default, precompiles code-behind pages; this saves considerable processing and simplifies the
deployment of the Web site.
Question: What are the benefits and drawbacks of JIT and precompilation?

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 79


Adding Event Procedures to Web Server Controls
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 2
Adding Event Procedures to Web Server Controls
You can use event procedures to handle user interactions on a Web Form. There are two types of event procedures:
client-side and server-side. Client-side event procedures are events that are handled on the computer that requests
the Web Form. Server-side event procedures require information to be sent to the Web server for processing and
are much more powerful than client-side event procedures.
This lesson describes event procedures and explains how to add them to Web server controls. It enables you to
distinguish between the two types of events (server-side and client-side) and decide when it is appropriate to use
each type.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 80


What Are Event Procedures
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Explain event handling so that students can understand why it is important.

Student Book Content


What Are Event Procedures?
Key Points
Dynamic, interactive Web Forms typically react to user input. Event procedures handle user interactions on a Web
Form.
An event procedure is the action that occurs in response to the generated event.
CD Content
Dynamic, interactive Web Forms typically react to user input. You can use event procedures to handle user
interactions on a Web Form.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 81


Client-Side Event Procedures
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Client-side event procedures are useful for events that must happen immediately, for example,
validation events. Explain that the language for client script can be either Javascript or VBScript.
Note: When you ask the question in the student workbook, don't be tempted to launch into a
discussion on ASP.NET AJAX at this point.

Student Book Content


Client-Side Event Procedures
Key Points
Client-side event procedures are events that are handled on the computer that requests the Web Form (the client).
When an event is generated, no information is sent to the server.
Client-side event procedures are useful for events that you want to happen immediately because they do not
require a round trip to the Web server.
You can specify a client-side event procedure by creating a <SCRIPT> block in the Web page.
Question: What are the advantages and disadvantages of client-side event procedures?

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 82


Server-Side Event Procedures
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Client-side event procedures are more powerful than client-side event procedures. The key difference
is runat="server".

Student Book Content


Server-Side Event Procedures
Key Points
Server-side event procedures are much more powerful than client-side event procedures, consist of compiled code
that resides on the Web server, and require information to be sent to the Web server for processing.
You can use server-side event procedures to handle events that are generated from both Web and HTML server
controls.
Server-side event procedures cannot support events that occur frequently such as mouse-key events.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 83


Multimedia - Client-Side and Server-Side Events
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)

Student Book Content


Multimedia: Client-Side and Server-Side Events
Key Points
In this animation, you will see how client-side and server-side event procedures are processed on the client and on
the server.
CD Content
In this animation, you will see how client-side and server-side event procedures are processed on the client and on
the server.
1. The client requests an ASP.NET page from the Web server.
2. The server returns a page containing HTML and script to the client. The page includes a text box control and a
Submit button. The page also contains client-side script that validates the contents of the text box.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 84


Creating Event Procedures
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


The answer to the topic question can be simple or quite complex; there are significant differences
behind the scenes, but the process is essentially the same.

Student Book Content


Creating Event Procedures
Key Points
To create a server-side event procedure in Visual Studio 2008, you must perform two steps:
1. Create the control that generates the event on the Web Form.
2. Provide the code on the code-behind page that handles the event.

When you double-click a control in Visual Studio 2008, Visual Studio 2008 creates an event procedure template:
In Microsoft Visual C# ®, the onclick attribute is set to the name of the event procedure.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 85


Demonstration - Creating an Event Procedure
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


You can use this demonstration throughout the lesson to illustrate the different topics to students as
you talk about them.
In this demonstration, students will see how to add an event procedure to a Web control by using
Visual Studio 2008. You can perform this demonstration by using either Visual C# or Microsoft Visual
Basic®.
• Create a Web Form by using Visual Studio 2008
1. Open Visual Studio 2008.
2. Create a Web site.
3. Add a Web Form to the Web site or use the Deafult.aspx page which is automatically
added.
• Add controls to the Web Form
1. Add a Button and a Label control to the form.
2. In the Properties window, examine the default properties of the controls.
• Add a Click event procedure
1. In Design view, double-click the Button control to open the code-behind page and
create a Click event procedure.
2. In the code-behind page, notice the event procedure template that is created by Visual
Studio 2008.
[Visual C#]
protected void Button1_Click(object sender, System.EventArgs e)
{
}
[Visual Basic]
Sub Button1_Click(ByVal s As Object, ByVal e As EventArgs) Handles Button1.Click
End Sub
3. Add the following code in the Click event procedure.
[Visual C#]
Label1.Text = "You clicked the button";
[Visual Basic]
Label1.Text = "You clicked the button"
4. For a Visual Basic demonstration, notice the Handles keyword in the Button1_Click
event procedure. For a Visual C# demonstration, the procedure is bound to the event
procedure by adding the attribute onclick to the markup. The following code illustrates
this.
[Visual C#]
...

...
• Browse the page
1. In Solution Explorer, right-click the Web Form, and then click View in Browser.
2. In the browser, click the button on the form.
3. The text of the label changes.
4. In the browser, view the source of the page to show that there is no client -side code.
There is just server-side code.
5. Close the source view of the page.

Student Book Content

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 86


Student Book Content
Demonstration: Creating an Event Procedure
Question: How can you create a default event procedure for a control?
CD Content
In this demonstration, the instructor will show you how to create an event procedure for a button on a Web page
that changes the text of a label.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 87


Interacting with Controls in Event Procedures
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)

Student Book Content


Interacting with Controls in Event Procedures
Key Points
In many Web applications, you must read from and write to controls on a form. You can do this in server-side event
procedures.
In a server-side event procedure, you can read information from a server control.
You can output information directly to a Web server control by using the control's properties.
Question: What are some key properties of a Web server control?

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 88


Handling Page Events
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Explain to the students that it is common to read from and write to controls on a form. Explain that
they can accomplish this with event procedures.

Student Book Content


Lesson 3
Handling Page Events
The page event life cycle is the series of page events that occur when an ASP.NET page is requested. Postbacks are
when ASP.NET Forms post information back to the sending ASP.NET page for processing. You can use the
Page.IsPostBack property to control which code executes only when the page is initially requested. You can also
link one control to the contents of another, for example, to display values from list boxes or drop-down lists.
This lesson explains how to use page events. It introduces the page event life cycle and describes the postback
process and event order. You will also see how to work with the Page_Load event and link controls together.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 89


The Page Event Life Cycle
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


The Page Event Life Cycle
Key Points
When an ASP.NET page is requested, there are a series of page events that occur. These events always occur in the
same order, which is referred to as the page event life cycle.
1. Page_Init. Initializes the page by creating and initializing the Web server controls.
2. Page_Load. Runs every time the page is requested.
3. Control events. Consist of change events, and then action events.
4. Page_Unload. Occurs when the page is closed or when the control is passed to another page.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 90


Multimedia - The PostBack Process
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


The slide does not list all of the available page events.
Cover several of the key events.
Make students aware that page events may not come back in the order that they were coded.

Student Book Content


Multimedia: The PostBack Process
Key Points
In this animation, you will see how Forms work in ASP.NET, how you can code the Page_Load event, and how you
can make controls post immediately to the server.
CD Content
In this animation, you will see how Forms work in ASP.NET and how the Page_Load event can be coded to run
only the first time a page is displayed, and how controls can be made to post immediately to the server.
The first time that a user requests a page from the server, the test for Page.IsPostBack in the Page_Load event
succeeds and the code in the block runs. In this example, the code populates a list box.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 91


Demonstration - Handling Events
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


This multimedia explains how Forms work in ASP.NET.

Student Book Content


Demonstration: Handling Events
Question: How can you change an HTML control to a Web server control?
CD Content
In this demonstration, the instructor will show you how HTML and Web server controls can support both client-side
and server-side events.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 92


Handling Page.IsPostback Events
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how link a Label control to a ListBox control and bind data to
the Label control. You can perform this demonstration by using either Visual C# or Visual Basic.
Note: The EventOrderFinal.aspx file in the E:\Labfiles\Democode\CS or E:\Labfiles\Democode\VB
folder contains a complete solution for this demonstration.
• View the page
1. In Visual Studio 2008, create a Web site in Visual C# if you do not already have one
open.
2. Add the EventOrderStart.aspx page from the E:\Labfiles\Democode\CS or
E:\Labfiles\Democode\VB folder to the Web site.
3. View the page in a browser.
4. Type a name in the Name box, click a value in the Profession list, select the check box,
and then click Save. The page has client-side and server-side event procedures for the
text box, list box, check box, button, and the page.
5. Close the browser.
• Change a check box to a Web server control
1. In the EventOrderStart.aspx page, add a Text attribute to the HTML code of the check
box to change it into a Web server control. The following code illustrates this.
<asp:checkbox onclick="checkClick()"
onserverclick="checkServerClick"
onserverchange="checkServerChange"
runat="server"
id="Checkbox1"
Text="Certified Professional"/>
Note: Although the onclick, onserverclick, and onserverchange attributes are not recognized by
the syntax checker, you can leave them in the code.
2. View the page in the browser again.
3. Type a name in the Name box, click a value in the Profession list, select the check box,
and then click Save.
The check box fires only client-side events now. Although the client event still runs
because generates , the server event does
not run because the name of the server event is oncheckedchange, not
onserverchange.
4. Edit the page in HTML view and change the name of the server-side event procedure
attribute from onserverchange to oncheckedchanged. The following code illustrates
this.

onserverclick="checkServerClick"
oncheckedchanged="checkServerChange"
runat="server"
id="Checkbox1"
Text="Certified Professional"/>
5. View the page in the browser again.
6. Enter a name in the Name box, click a value in the Profession list, select the check box,
and then click Save.
7. Both client and server event procedures run again.
• Implement a Page.IsPostBack test
1. Edit the page and set the AutoPostBack attribute to true for the check box.
2. View the page in the browser again.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 93


2. View the page in the browser again.
3. When you select the check box, the client-side event fires and then the server-side event
fires.
4. In the browser, view the source of the page to see how AutoPostBack is implemented.
5. Close the source view page.

Student Book Content


Handling Page.IsPostback Events
Key Points
The Page_Load event runs on every request for a page, whether it is the first request of the page or a postback.
When you use postback events, if you do not want all of the code to execute again, you can use the
Page.IsPostBack property to control which code executes only when the page is initially requested.
Cross-page posting is the process of posting one Web page to another page.
CD Content
The Page_Load event runs on every request for a page, whether it is the first request of the page or a postback.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 94


Linking Two Controls Together
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)

Student Book Content


Linking Two Controls Together
Key Points
You can link one control to the contents of another. Linking controls is particularly useful when you want to display
values from list boxes or drop-down lists.
You can use the DataBind method of either the entire page or just a control.
CD Content
You can link one control to the contents of another. Linking controls is particularly useful when you want to display
values from list boxes or drop-down lists.
The following code example demonstrates how to link a Label control to the contents of a drop-down list. You can
use the linking tags <%# and %> to set the Text attribute of a Label control to the SelectedItemof the list box.
<asp:Label id="selectedValueLabel" runat="server"

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 95


Demonstration - Linking Controls Together
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


The key point for students to understand is that their application must check if the page is being
loaded in response to a client postback or is being loaded and accessed for the first time.
Cross-page posting can be considered an advanced topic that is beyond the scope of this course. A
suitable reference is provided, so direct students to this resource for further information.

Student Book Content


Demonstration: Linking Controls Together
Question: Why is the label updated every time you select a profession?
CD Content
In this demonstration, the instructor will show you how to link controls together.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 96


Lab - Adding Functionality to a Web Application
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


Discuss with the students when it is useful to link controls together.
Use the following demonstration to illustrate the key points as you talk about them.

Student Book Content


Lab: Adding Functionality to a Web Application
Exercise 1: Creating a Page_Load Event Procedure
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.
In the first lab, you created a component that returned a list of all the benefits that are offered by your company. In
this lab, you will call that component from the Default.aspx page of your company's Web site, display the
information in a CheckBoxList control, and implement a Submit button on the form to display which benefits are
selected.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 97


Exercise 1 - Creating a Page_Load Event Procedure
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how HTML and Web server controls can support both client-
side and server-side events.
Note: The BindingF inal.aspx file in the E:\Labfiles\Democode\CS or E:\Labfiles\Democode\VB folder
contains a complete solution for this demonstration.
• View the controls
1. In Visual Studio 2008, create a Web site if you do not already have one open.
2. Depending on the language chosen, add the BindingStart.aspx page from the
E:\Labfiles\Democode\CS or E:\Labfiles\Democode\VB folder to the Web site.
3. There is a DropDownList and a Label control on this page.
4. View the HTML for the page. Note the AutoPostBack attribute for the DropDownList
control.
• Link a Label to a ListBox control
• Link the Label control to the DropDownList control by setting the Text attribute of the
Label control. The following code example illustrates this.
Text=" runat="server"/>
• Bind data to the Label control
1. Create a Page_Load event procedure for the page.
2. In the Page_Load event procedure, call listValueLabel.DataBind(). The following code
example illustrates this.
[Visual C#]
listValueLabel.DataBind();
[Visual Basic]
listValueLabel.DataBind()
• Build and browse
1. Build the Web site and view the BindingStart.aspx page in a browser.
2. When you select an item in the DropDownList, the value is reflected in the Label
control.
3. Delete the code that you added to the Page_Load event procedure.
4. Create a SelectedIndexChanged event procedure for the titleList control. If the
demonstration is in Visual C#, note that the onclick attribute is added automatically.
5. In the titleList_SelectedIndexC hanged event procedure, call
listValueLabel.DataBind(). The following code example illustrates this.
[Visual C#]
listValueLabel.DataBind();
[Visual Basic]
listValueLabel.DataBind()
6. Build the Web site and view the BindingStart.aspx page in a browser.
7. When you select an item in the DropDownList, the value is again reflected in the Label
control, but the data is bound in the titleList_SelectedIndexChanged event procedure.

Student Book Content


4. Why would you want to set up your code-behind pages to be precompiled instead of JIT compiled?
If you precompile all the code for a Web application, it saves time and resources on the Web server
because the server does not have to compile the pages as they are accessed.
5. When does a form post back to itself?
When the user clicks a button on a server form or a control with AutoPostBack set to True.

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 98


Module 04-Adding Code to a Microsoft ASP.NET Web Form página 99
Exercise 2 - Creating a Click Event Procedure
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


In this lab, students will add functionality to a Web application by using event procedures.
Exercise 1
In this exercise, students create a Page_Load event procedure for a Microsoft ASP.NET Web page.
Exercise 2
In this exercise, students create Click event procedures for Web controls on an ASP.NET Web page.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 100


Exercise 3 - (If Time Permits) - Implementing a Component in a User
Control
Saturday, September 06, 2008
12:19 AM

Instructor Notes (PPT Text)


In the first lab, students created a component that returned a list of all the benefits that are offered by
the Coho Winery company. In this lab, students will call that component from the Default.aspx page of
the company's Web site, display the information in a CheckBoxList control, and implement a Submit
button on the form to display which benefits are selected.

Student Book Content

Module 04-Adding Code to a Microsoft ASP.NET Web Form página 101


Tracing and the Trace Object
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Tracing and the Trace Object
Tracing is the process of receiving informative messages about the execution of a Web application at runtime. These
informative messages from the Web application can help you to diagnose problems or analyze performance. Visual
Studio 2008 offers two objects for gathering such information at run time: the Debug object and the Trace object.
This lesson describes how to use the Trace object to implement tracing in a Web application.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 102


Run Time Information
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Check that the students are familiar with the concept of debugging. Refer them to the additional
content provided on the Course Companion CD if they want to refresh their knowledge.
Ensure that the students understand the difference between the Trace and Debug objects.
A note at the end of the topic mentions that students must import the System.Diagnostics
namespace to use the Debug object. It is important to make this point because the students may
already be familiar with debugging features and the use of the Debug object for Microsoft®
Windows®-based application development, where the reference is added automatically.

Student Book Content


Run Time Information
Key Points
You can collect information while your Web application runs by using the Debug and Trace objects.
The Trace object in Microsoft ASP.NET enables you to display information on a Web page or save it in
memory.
Statements that use the Debug object run only when they are compiled in debug mode and when the Web
application is run in the debugger.
Question: When have you used tracing or debugging in your own applications?
CD Content
You can collect information while your Web application runs by using the Debug and Trace objects.
Types of Information
You can perform the following steps during runtime:
Output values of variables.
Determine if certain conditions have been met. For example, the Trace.WriteIf method outputs a message if a
condition is met.
Follow the execution path of the application. You can follow the programming logic of a Web Form while it executes
to ensure that processing occurs properly.

Run Time Objects


You can use two objects to display debugging information during runtime. Those objects are:
The Trace object. The Trace object in Microsoft ASP.NET enables you to display information on a Web page or
save it in memory.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 103


Enabling Tracing
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Discuss the web.config file with this slide; ensure you mention that it is in XML format and is case
sensitive. It is important for you to establish the importance of camelCase.

Student Book Content


Enabling Tracing
Key Points
When you use tracing, you can write trace statements directly to the page or to a storage object.
When you use page-level tracing, all trace messages are appended to the end of the Web page.
With application-level tracing, you can write trace messages to the page or to memory. The pageOutput
attribute of the trace element specifies where the messages are written.
Question: Why may you want trace statements to be visible only on the local computer?

Module 05-Tracing in Microsoft ASP.NET Web Applications página 104


The Trace Object
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Mention Trace.Warn and explain that it works identically to Trace.Write but displays messages in
red.

Student Book Content


The Trace Object
Key Points
To write trace messages on a page (or in memory), you use the Trace.Write and Trace.Warn methods.
To use the Write and Warn methods, you provide a message to be written and optionally a corresponding
category for the message.
To check whether tracing is enabled or to turn tracing on and off, you can use the Trace.IsEnabled
property.

CD Content

Module 05-Tracing in Microsoft ASP.NET Web Applications página 105


Viewing Trace Results
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Briefly discuss the different categories of trace results that may appear on a Web page.

Student Book Content

The resulting trace messages appear as shown in the following illustration.

Trace.IsEnabled
There are situations when you may want to generate trace messages only when tracing is enabled for a Web page
or Web application. For these situations, the Trace object has a Boolean property named IsEnabled that enables
you to call the Write and Warn methods only when tracing is enabled. The following code illustrates this.
[Visual C#]
if (Trace.IsEnabled)
{
message = "Tracing is enabled!";
Trace.Write("myTrace", message);
}

[Visual Basic]
If Trace.IsEnabled Then
message = "Tracing is enabled!"
Trace.Write("myTrace", message)
End If

You can also use the IsEnabled property to change the state of tracing for a page dynamically. The following code
illustrates this.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 106


Application-Level Trace
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


To summarize the trace settings, advise the students that page-level tracing overrides any other trace
setting.
Inform the students that if they are particularly concerned about security, they should disable the
trace viewer.

Student Book Content


Application-Level Trace
Key Points
You enable application-level tracing in the web.config file. After application-level tracing is enabled, you can
view trace statements on individual pages or in the trace viewer.
You can disable the trace viewer for a Web server by editing the web.config file that is in the machine
configuration folder.
Question: What is the advantage of the application-level trace viewer over displaying trace information on the
page?
CD Content

Module 05-Tracing in Microsoft ASP.NET Web Applications página 107


Demonstration - Tracing Through a Web Application
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


You can run this demonstration by using either Microsoft C#® or Microsoft Visual Basic®.
You can run this demonstration during the lesson while you discuss each of the previous topics.
Alternatively, you can run the whole demonstration at the end of the lesson.
Explain that the localOnly attribute specifies who can see the trace and that when the pageOutput
attribute is set to false, the trace can be viewed from a different computer.
To run the demonstration
1. In Microsoft Visual Studio® 2008, open the CallClassCS or CallClassVB Web site in the
Democode\CS or DemoCode\VB folder.
2. In the project, turn tracing on in the Default.aspx page, by including the Trace
attribute in the @ Page directive.
3. Add two custom trace messages to the end of the click event procedure for Button2 in
the Default.aspx code-behind page. The following code illustrates this.
[Visual C#]
Trace.Write("Shipping", "price = " + Convert.ToString(TextBox1.Text));
Trace.Warn("Shipping", "shipping cost = " + Convert.ToString(shippingCost));
[Visual Basic]
Trace.Write("Shipping", "price = " & CStr(TextBox1.Text))
Trace.Warn("Shipping", "shipping cost = " & CStr(shippingCost))
4. Build and browse the Default.aspx page.
Trace information is shown on the page.
5. Enter a price, and then click Calculate Shipping.
Point out the custom trace messages and then close the browser window.
6. Disable tracing for the page, and then view the page again.
No trace messages are shown on the page.
7. Turn tracing on at the application level by adding the trace tag to the web.config file
in the System.Web element. Set the pageOutput attribute to true. The following
code illustrates this.

Notice that the localOnly attribute is set to true (this is also the default value). This allows only local
browsers to see trace information.
8. Refresh the view of the Default.aspx page and note that trace messages are not
displayed because trace is explicitly turned off for this page.
9. View the Numbers.aspx page in the browser. This page does not have tracing turned
on, but the trace results are displayed anyway because application-level tracing is
turned on.
10.Close the browser window.
11.Add the following trace statement to the Numbers.aspx page in the click event
procedure for Button1.
[Visual C#]
Trace.Warn("Double It", "Value to double " + TextBox1.Text);
[Visual Basic]
Trace.Warn ("Double It", "Value to double " & TextBox1.Text)
12. View the Numbers.aspx page in the browser again. Enter a number into the box and
then click Double It.
The trace results, including the custom message you just added, are shown.
13. Close the browser window.
14. Change the trace tag in the web.config to turn off pageOutput.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 108


Student Book Content

Displaying Trace Messages


You can display application-level trace messages in two places: on the page itself or in the trace viewer. To
determine how trace results are displayed, you set the pageOutput attribute of the trace element in the
web.config file. A setting of true displays the results on the page, and a setting of false keeps the trace messages in
memory. The following code shows an example of disabling output to the page.
<configuration>
<system.web>
<trace enabled="true" pageOutput="false"/>
</system.web>
</configuration>

If page output is disabled for application-level tracing, the trace messages are stored in memory. You can then view
the trace messages by using the trace viewer, which is a Web page that is included with each Web application. You
use the trace viewer by viewing the trace.axd page in a browser:
http://servername/projectname/trace.axd
For security reasons, you may want to disable the trace viewer. You can disable the trace viewer for a Web server by
editing the web.config file contained in the machine configuration folder. You can locate the machine configuration
folder in the following directory:
%systemroot%\Microsoft.NET\Framework\v2.x\Config\
In the web.config file in this folder, the reference to trace.axd (the trace viewer) is in the httpHandlers section.
This web.config file, in conjunction with the other configuration files in the folder, is inherited by all web.config files
for all web applications on the machine.
<httpHandlers>
<add verb="*" path="trace.axd"
type="System.Web.Handlers.TraceHandler"/>
</httpHandlers>

Module 05-Tracing in Microsoft ASP.NET Web Applications página 109


Tracing into a Component
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)

Student Book Content


Tracing into a Component
Key Points
If you have a component that is called from a Web Form, you can add trace statements to that component, which
then enables you to generate trace messages for both the Web Form and the component.
Trace messages in a component will appear in any trace-enabled page that calls the component if trace is not
intentionally disabled in the component.
Question: Why may you want to trace into a component?
CD Content

Module 05-Tracing in Microsoft ASP.NET Web Applications página 110


Remote Debugging
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Explain that it may be necessary to add trace statements to a component because components are
often called from Web Forms.
Emphasize the importance of context and the use of the HttpContext.Current property.
Use the table in the topic to explain and summarize tracing into a component.

Student Book Content


Lesson 2
Remote Debugging
You use debugging to catch errors when you create a Web application. For most debugging operations, you run the
Visual Studio 2008 debugger on the computer that hosts the Web application. Remote debugging enables you to
debug a Web application that runs at a remote location. This lesson describes how to perform remote debugging.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 111


Remote Debugging Overview
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)

Student Book Content


Remote Debugging Overview
Key Points
Remote debugging is the process of debugging Web applications that runs on a separate server. When you perform
remote debugging, you use the Remote Debugging Monitor (msvsmon.exe). The Remote Debugging Monitor can
run as a Microsoft Windows ®-based application or as a Windows service.
Question: When may you want to use remote debugging with an ASP.NET application?
CD Content
Remote debugging is the process of debugging Web applications that runs on a separate server. Remote debugging
enables you to debug Web applications on numerous disparate servers from a single workstation. You may want to
use remote debugging if you cannot run your Web application locally or you want to test the application while it is
deployed on a Web server.
Remote Debugging Monitor
When you perform remote debugging, you use the Remote Debugging Monitor (msvsmon.exe), which is a small
application to which Visual Studio 2008 connects. You can either install the Remote Debugging Monitor on the
remote computer or run the monitor remotely from a shared folder.
By default, the Remote Debugging Monitor runs as a Microsoft Windows ®-based application. To debug in ASP.NET
or another server environment, you can also configure the monitor to run as a Windows service by using the Visual
Studio 2008 Remote Debugger Configuration Wizard. You start this wizard from the Visual Studio Tools folder on
the Start menu.
Before you start remote debugging, you must configure the environments on both the debugger host and the
remote computer. You must also consider security features; for example, the remote server must grant access to
the user who performs the debugging.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 112


Performing Remote Debugging
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Explain that the easiest option is to run the Remote Debugging Monitor from a file share.
However, mention that if students want to run the remote debugger from a share the must perform a
manual attach to the server process. This process also has security implications because the student
must be logged on as the same user on both machines.

Student Book Content


Performing Remote Debugging
Key Points
Before you perform remote debugging, you must carry out several configuration steps. These include:
Enabling debugging in the ASP.NET application.
Enabling remote debugging on the remote server.
Configuring security for the remote debugging environment.

CD Content
Before you perform remote debugging, you must carry out several configuration steps.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 113


Lab - Tracing in Microsoft ASP.NET Web Applications
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Describe the steps required to configure and perform remote debugging.
If you have time, demonstrate how to enable debugging in an ASP.NET application by using the Start
with Debugging menu option.
Mention that the worker process for the remote application differs between environments. The process
can be one of the following: W3SVC on Microsoft Windows Server® 2003, aspnet_wp on Windows XP,
and WebDeb.WebServer.exe on the Visual Studio 2008 development server.

Student Book Content


Lab: Tracing in Microsoft ASP.NET Web Applications
Exercise 1: Implementing Trace Statements
Scenario
Coho Winery offers several benefits to its employees. You will create a Web site that enables employees to select
and set up their chosen benefits. In this lab, you will trace through the execution of the Benefits Web application.
In this exercise, you will enable and disable tracing and add custom messages to the trace output.
The main tasks for this exercise are as follows:
1. Open the Benefits Web site.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 114


Exercise 1 - Implementing Trace Statements
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


In this lab, students will perform tracing in a Microsoft ASP.NET Web application
Exercise 1
In this exercise, students add trace statements to a Microsoft ASP.NET Web Form
Exercise 2
In this exercise, students trace into a component
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

If trace information is displayed on the page, which custom trace messages are displayed? Why?
A. Only the trace messages from the component, because trace is turned off in the page.

5. Close the browser window.


6. View the code for the Benefits class in the App_Code folder.
In Solution Explorer, expand App_Code, and then double-click Benefits.cs or Benefits.vb.
7. Comment out the trace messages in the GetBenefitsList method.
8. View the code- behind file for the Default.aspx page.
9. Comment out the trace messages in the Page_Load event procedure.
10. View the code- behind file for the life.aspx page.
11. Comment out the trace message in the Page_Load event procedure.
12. Save your changes.

Results: After this exercise, you have enabled tracing in a component and disabled tracing.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 115


Exercise 2 - Tracing into a Component
Saturday, September 06, 2008
12:21 AM

Instructor Notes (PPT Text)


Students will use the existing Coho Winery Benefits Web site and will trace through the execution of
the application

Student Book Content


Messages written to the Debug object will only be displayed when you run the Web application in
the debugger. Messages written to the Trace object will be displayed to the Web page as long as
trace is enabled.
2. What is the difference between page-level tracing and application-level tracing?
When you turn on page-level tracing for one page, trace information will only be displayed for that
page. When you enable application-level tracing, trace information will be displayed on all pages in
the Web application.
3. How do you enable application-level tracing?
Set the enabled attribute of the trace element to true in the Web.config file.
<trace enabled="true"/>
4. Read the following scenarios and determine whether trace messages will be displayed.
a. Tracing is turned on in page1.aspx, but off in web.config. You view page1.aspx.
Trace statements are displayed.
b. Tracing is turned off in page1.aspx, but on in web.config. You view page1.aspx.
Trace statements are not displayed.
c. Tracing is turned on in page1.aspx, but off in web.config. You view page2.aspx.
Trace statements are not displayed.
d. Tracing is turned on in page1.aspx, and on in web.config. You view page2.aspx.
Trace statements are displayed.
e. Tracing is turned off in page1.aspx, but on in component A. You view page1.aspx and click a button that calls
component A.
Trace statements from component A are displayed, but page Trace.write statements are not
displayed.

Module 05-Tracing in Microsoft ASP.NET Web Applications página 116


Overview of User Input Validation
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Lesson Overview

Student Book Content


Lesson 1
Overview of User Input Validation
Input validation verifies that the user has correctly filled in input controls on a Web Form before a request is
processed on the server. There are several different types of input validation controls available in ASP.NET.
This lesson introduces input validation, explains client-side and server-side validation, and describes the function of
the ASP.NET validation controls.

Module 06-Validating User Input página 117


What Is Input Validation
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information. Each topic will be reviewed in context in
later topics in this module.
Emphasize that input validation always runs on the server and runs on the client if the client browser
supports validation. To illustrate this, if time permits, enable and disable client-side scripting in the
demonstrations for this module.
Another example of a malicious code attack is pasting XML directly into input controls, which can have
an effect similar to a SQL injection attack. For example, it is possible to send an XML Updategram or
XQuery string into a password box in an attempt to compromise a system. There are many security
tips that you can provide here; for example, you can advise students that they must always perform a
server-side check, only access data through stored procedures, and never dynamically construct SQL
strings from user input.

Student Book Content


What Is Input Validation?
Key Points
Input validation is the process of verifying that a user's input on a Web Form matches the expected data value,
range, or format.
This validation reduces the wait time for error messages and the likelihood of incorrect returns or Web site crashes
due to problems with user input.
ASP.NET server-side validation controls protect Web Forms against spoofing and malicious code.
Questions:
1. Why do ASP.NET validation controls protect against spoofing and malicious code attacks?
2. Can you think of any spoofing or malicious code examples?

Module 06-Validating User Input página 118


Client-Side and Server-Side Validation
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


To avoid spoofing, the validation is always repeated on the server side.

Student Book Content

CD Content
Input validation is the process of verifying that a user's input on a Web Form matches the expected data value,
range, or format. Input validation improves a user's experience with the Web site by reducing the wait time for
error messages and the likelihood of incorrect returns or Web site crashes due to problems with the user's input.
When combined with understandable and useful error messages, input validation controls can greatly improve the
usability of a Web application; this improves the customer's perception of the Web site's overall quality.
Input validation controls act to verify that the user has correctly filled in an input control, such as a TextBox
control, before the request is processed on the server. The input validation controls on a Web Form act as data
filters before the page or server logic is processed.
In ASP.NET, input validation always runs on the server side; it can also run on the client side if the client browser
supports validation. If the browser supports client-side validation, the input validation controls perform error
checking on the client before posting the data to the server. Users receive immediate feedback on whether the data
that they entered is valid. For security reasons, any input validation that is run on the client side is then repeated on
the server side.
Verifying Control Values
Input validation works by comparing user input against a predetermined input format. These predetermined input
formats can include the number of characters, the use of alphanumeric characters, the value range, a specific
character string, or a mathematical formula.
For example, a user input control that requests users to enter their telephone number can have an attached input
validation control that verifies that users have entered only numbers in a telephone number format. Entering letters
or too few numbers triggers the input validation control to display an error message and require users to re -enter
the data.
Prevents Page Processing
User input that matches the predetermined format is processed by the Web Form. User input that does not match
the predetermined format triggers an error message and stops the Web Form from processing. Further processing
of the page is blocked until the user input is corrected to meet the expected format and the page has been
resubmitted for processing.

Module 06-Validating User Input página 119


ASP.NET Validation Controls
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information.
Each control will be reviewed in context in the next lesson.
Note: In Microsoft® Visual Studio®, create a new Web site and point out the six validation controls in
the Validation group in the Toolbox. Add a TextBox and Button control to the Default.aspx page in
preparation for the demonstration.

Student Book Content


ASP.NET Validation Controls
Key Points
ASP.NET provides six validation controls that are grouped together in the Validation group in the Toolbox:
CompareValidator. Compares an input control to another input control, a fixed value, a data type, or a file.
CustomValidator. Allows you to write your own code to create the validation expression.
RangeValidator. Verifies that the user input is between two values or the values of other input controls.
RegularExpressionValidator. Verifies that the entry matches a pattern that has been defined by a regular
expression.

Module 06-Validating User Input página 120


Validation Controls
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Lesson Overview

Student Book Content

Additional Reading: For more information about ASP.NET validation controls, see "Types of Validation for
ASP.NET Server Controls" at http://go.microsoft.com/fwlink/?LinkId=110692.

Module 06-Validating User Input página 121


Adding Validation Controls to a Web Form
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


The main point is that validation controls share a common object model so they all have the same
properties. On the slide, use the highlighter tool to show the common validation control attributes.
Alternative delivery: In Visual Studio, display the typical properties of validation controls.

Student Book Content


Lesson 2
Validation Controls
Validating user input used to be a tedious and time-consuming process. For each input control, you first had to write
validation code for the server in one language. Then, if you were going to perform client-side validation, you had to
write the equivalent client-side validation for each expected browser in a different script.
This lesson demonstrates how ASP.NET and Visual Studio 2008 enables you to easily validate user input by providing
input validation controls that provide server-side and client-side code when you add them to your Web Form.

Module 06-Validating User Input página 122


Positioning Validation Controls on a Web Form
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Explain that it is important to position validation controls correctly to make it clear to the user which
control contains the error.
Explain the difference between the ErrorMessage and Text error message properties.
Explain that you can use different characters instead of an asterisk. For example, you can use a large
red bullet or even an image (by nesting an tag in the text attibute). The asterisk is shown here for
simplicity.
Alternative delivery: In Visual Studio, show the static and dynamic display modes by implementing
two validation controls and testing the page with either mode. Place a RegularExpressionValidator
and then a RequiredFieldValidator on a form next to a text box. Adjust the display property of the
RequiredFieldValidator to demonstrate the behavior. Also, show what Display="none " does for
the control and the effect that it has on validation processing.

Student Book Content


Positioning Validation Controls on a Web Form
Key Points
Input validation controls can display an error message when an input violation has occurred. It is important to
position input validation controls so that it is clear to the user which control has the incorrect input.
ASP.NET validation controls contain ErrorMessage and Text properties that can display invalid input messages at
the location of the validation control.
The Display property sets the spacing of error messages from multiple validation controls on a Web Form.
Question: What is the distinction between the ErrorMessage and Text properties?

Module 06-Validating User Input página 123


Combining Validation Controls
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Discuss why multiple validation controls may be required for a single control on a Web Form (for
example, a text box may be required content and also may require a specific format).
Explain that you can use the supplied default patterns as a template for validation expressions.
Alternative delivery: In Visual Studio, link several validation controls to a single text box and test.

Student Book Content


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; for example, a telephone field that must conform to a certain pattern and be checked against
database.
You can associate multiple validation controls to a single input control so that you can check user input for more
than one validation requirement.
Question: Why is it sometimes necessary to validate user input by using multiple validation controls?

Module 06-Validating User Input página 124


Input Validation Controls
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Ensure that the students understand when they can use each type of control.
Mention validation groups but explain that they will be covered in the next lesson.
Point out that a check on the date format of a CompareValidator control is dependent on your
regional settings.
Alternative delivery: In Visual Studio, display and explain the key properties of the three validation
controls. Create the controls and validate input with the code provided on the Course Companion CD.

Student Book Content


Input Validation Controls
Key Points
The simplest validation controls are the RequiredFieldValidator, CompareValidator, and RangeValidator
controls. All of these validation controls validate against fixed values or a second input control.
RequiredFieldValidator. Forces a user to provide input in an input control. Any character is a valid response with
this validation control.
CompareValidator. Tests a user's input against a specific value or against a second input control.
RangeValidator. Verifies that the value entered matches an expected range.

Module 06-Validating User Input página 125


RegularExpressionValidator Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information. This topic focuses on the use of the
RegularExpressionVa lidator control; the expressions themselves are additional information.
Alternative delivery: In Visual Studio, display the preset regular expressions by clicking the ellipsis
(...) button for the ValidationExpression property.

Student Book Content


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 or e-mail address.
Visual Studio 2008 provides a set of preset regular expression patterns that include e-mail addresses and telephone
numbers. You can build your own custom regular expressions by using the set of control characters.
You can use the RegularExpressionValidator control to verify simple and complex expressions.
Question: What are some common regular expression characters?

Module 06-Validating User Input página 126


CustomValidator Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Unlike the other validation controls, you have to write the client -side code when you use the
CustomValidator control.

Student Book Content

Note: For more information about control characters, see "Introduction to Regular Expressions" in the online
JScript reference.
Example of a Simple Expression
The following code example shows 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="*">
</asp:RegularExpressionValidator>
The following table describes the specific pattern that the RegularExpression control checks in the previous
example.
Characters 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.

Module 06-Validating User Input página 127


Demonstration - Implementing the CustomValidator Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how to use a CustomValidator control to check on the server
and client side if a TextBox control contains an odd or even number. You can perform this
demonstration by using either Microsoft Visual C#® or Microsoft Visual Basic®. Also, if time permits,
you can demonstrate the effect of disabling client script.
• Add a CustomValidator control
1. Open Visual Studio 2008.
2. Create a Web site.
3. In the Design view of Default.aspx, add the following controls:
• TextBox
• Button
• CustomValidator
4. In the Properties window, set the following properties for the CustomValidator control:
• Text: It's an odd number
• ControlToValidate: TextBox1
• Write the server-side code
• Double-click the CustomValidator control to open the server-side event procedure and
add the following code.
[Visual C#]
int value = Convert.ToInt16(args.Value);
if (value % 2 == 0)
args.IsValid = true;
else
args.IsValid = false;
[Visual Basic]
Dim value As Integer = args.Value
If value mod 2 = 0 Then
args.IsValid = True
Else
args.IsValid = False
End If
Visual Studio 2008 automatically creates the server-side event procedure with the name
CustomValidator1_ServerValidate. This procedure contains two parameters: source type object)
and args (type ServerValidateEventArgs).
• Write the client-side code
1. In the Design view of Default.aspx, select the CustomValidator control.
2. In the Properties window, set the ClientValidationFunction property to
MyClientValidation.
3. In the Source view of Default.aspx, add the following Microsoft Jscript® code to the
end of the file.

function MyClientValidation(source, arguments)


{
alert("I am running on the client! ");
var value = arguments.Value;
if (value % 2 == 0)
{
arguments.IsValid = true;
} else {

Module 06-Validating User Input página 128


} else {
arguments.IsValid = false;
}
}

• Test the result


1. Ensure that the EnableClientScript property of the CustomValidator control is set to
True.
2. If EnableClientScript is set to True and the client browser supports client-side
scripting, the client-side script runs before the server-side code to avoid a server round
trip for the page.
3. Build the Web site and browse the Default.aspx page.

Student Book Content


CustomValidator Control
Key Points
You can use the CustomValidator control when you want to use your own customized validation logic to check
the user's input against a variable, formula, or second source.
The CustomValidator control validates on the server side; it can also validate on the client side if the browser
supports validation. You must write the validation scripts for the CustomValidator control.
The CustomValidator includes two properties:
ClientValidationFunction. The name of the script to run on the client side.
OnServerValidate. The name of the script to run on the server side.

Module 06-Validating User Input página 129


Page Validation
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Page Validation
You can use the Page.IsValid property and the ValidationSummary control to verify that all validation controls
on an ASP.NET Web Form are valid before processing is initiated.
This lesson explains the Page.IsValid property and how to implement the ValidationSummary control.

Module 06-Validating User Input página 130


The Page.IsValid Property
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Lesson Overview

Student Book Content


The Page.IsValid Property
Key Points
You can determine if all of the validation controls on a page are currently valid by checking the IsValid property of
the page at run time. If any one validation control is not valid, the IsValid property returns false.
Validation controls do not bypass your code if a user input error is detected so you must test the state of your
controls and prevent code from running if an error is detected.
Question: Where do you normally perform the Page.IsValid check?

Module 06-Validating User Input página 131


Implementing the ValidationSummary Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Mention that ASP.NET 2.0 introduced validation groups. Also, indicate that the Validate method now
has an overload that accepts the name of a validation group and validates only the controls that
belong to the specified group.

Student Book Content


Implementing the ValidationSummary Control
Key Points
The ValidationSummary control displays when the Page.IsValid property returns false. Each of the validation
controls on the page is polled and the ErrorMessage messages are aggregated by the ValidationSummary
control.
If client scripting is enabled, the ValidationSummary control can display a message box or a text area, with a
header and a list of errors.
The Text property of a ValidationSummary control is displayed at the location of the validation control and
warns the user that the input is invalid. The ErrorMessage property is displayed in the ValidationSummary
control and contains a description of the input error.
Question: What symbol is normally used for the Text property to locate errors?

Module 06-Validating User Input página 132


Lab - Validating User Input
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


To reinforce content, repeat the earlier comments about the Validation control Text property that is
displayed next to the input control and the Errormessage property that is displayed in the
ValidationSummary control.
Explain that you can use the * symbol is for simplicity or other characters of your choice. If time
permits, you can demonstrate the use of an embedded tag or other character by using the lab
solution.
Alternative delivery: In Visual Studio, display and explain the key properties of this validation control.

Student Book Content


Lab: Validating User Input
Exercise 1: Implementing RequiredFieldValidator Controls
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.
The Benefits Web application has a Web Form named life.aspx. This page is used for the life insurance benefit and
asks for a name, a birth date, and a coverage amount from the user. In this lab, you will add validation controls to
validate the entries in these text boxes. You will also add a summary validation control to summarize the invalid
entries on the page.

Module 06-Validating User Input página 133


Exercise 1 - Implementing RequiredFieldValidator Controls
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


In this lab, students will validate user input by using validation controls.
Exercise 1
In this exercise, students implement the RequiredFieldValidator control.
Exercise 2
In this exercise, students implement the ValidationSummary control.
Exercise 3
In this exercise, students implement the CompareValidator control.
Exercise 4
In this exercise, students implement the RegularExpressionValidator control.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

When you change the Text property of the controls, you will change the text that appears in Design view. Your
page should resemble the following illustration.

4. Save all files.


5. View life.aspx in a browser.
6. In the browser, leave the Name, Birth Date, and Coverage boxes blank, and then click Save.
Red asterisks appear next to each box because a blank entry is invalid.
7. In the browser, enter values for the Name, Birth Date, and Coverage boxes, and then click Save.
The red asterisks disappear because there is input in the boxes.
8. Close Microsoft Internet Explorer ®.

Results:After this exercise, you have added RequiredFieldValidator controls for the Name, Birth Date, and
Coverage boxes on the life.aspx Web Form.

Module 06-Validating User Input página 134


Exercise 2 - Implementing the ValidationSummary Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


The Benefits Web application has a Web Form named life.aspx. This page is used for the life insurance
benefit and asks for a name, a birth date, and a coverage amount from the user. In this lab, students
will add validation controls to validate the entries in these text boxes. Students will also add a
summary validation control to summarize the invalid entries on the page.

Student Book Content


Exercise 2: Implementing the ValidationSummary Control
Scenario
In this exercise, you will use a ValidationSummary control to summarize the validation errors for the life.aspx
page.
The main tasks for this exercise are as follows:
1. Add a ValidationSummary control to the life.aspx page.
2. Test if the page is valid.

Task 1: Add a ValidationSummary control to the life.aspx page


1. Use the Toolbox to add a ValidationSummary control to the last cell of the second column of the table in the
life.aspx Web Form.
2. In the Properties window, set the following properties for the control:
ID: textBoxValidationSummary
HeaderText: These errors were found:
Your page should resemble the following illustration.

Module 06-Validating User Input página 135


Exercise 3 - Implementing the CompareValidator Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. What are the properties that you should set for a RequiredFieldValidator control?
ErrorMessage: Displays text in the ValidationSummary control
Text: Displays validation message for the input control
ControlToValidate: The control to validate
2. What are the properties that you should set for a ValidationSummary control?
HeaderText: Displays introduction to the validation summary.
3. What are the properties that you should set for a CompareValidator control?
Same as the RequiredFieldValidator control, but you must also set Operator and Type
properties. Operator: Specifies the comparison operator to use for validation; Type:
Specifies the data type to validate.
4. What are the properties that you should set for a RegularExpressionValidator control?
Same as the RequiredFieldValidator control, but you must also set the ValidationExpression
property. ValidationExpression: Specifies the regular expression for validation.

Student Book Content


Exercise 3: Implementing the CompareValidator Control
Scenario
In this exercise, you will use a CompareValidator control to validate the user entry into the Birth Date box.
The main task for this exercise is as follows:
Add a CompareValidator control.

Task 1: Add a CompareValidator control


1. Open the life.aspx page in Design view.
2. Use the Toolbox to add a CompareValidator control to the life.aspx Web Form, next to the birthValidator
control.
3. Set the following properties for the CompareValidator control.
Property Value
ID birthCompareValidator
ErrorMessage Birth date format is invalid
Text *
ControlToValidate birthTextBox
Operator DataTypeCheck
Type Date

Your page should resemble the following illustration.

Module 06-Validating User Input página 136


Exercise 4 - Implementing the RegularExpressionValidator Control
Saturday, September 06, 2008
12:23 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• Users have added malicious text to a page on your Web site. The page contains a registration
form for new users. Why can users add text to a page on your Web site and what problems can
this cause?
Users can add unlimited text to a Web page through user input controls that do not have
input validation. This lack of validation can cause a number of problems, including:
Creating a buffer overrun and crashing the server by entering a name with several
thousand characters.
Creating and authenticating a new user account.
Adding privileges to their own account and removing privileges from other accounts.
Sending an SQL query to your customer database and downloading all of the data that is
present, including user names, addresses, passwords, and credit card numbers.
• Your Web site is authorizing more users than are currently registered. How can users make it
appear that they have entered valid data or passed an authorization check?
Users can modify the HTML page that is sent to them and then return values that make it
appear that they have entered valid data or passed an authorization check. Validation is
only susceptible to spoofing on the client side, because users can turn off client-side script
by changing browser options and not run the client-side validation code, which creates a
false level of authorization. You must perform server-side validation to ensure spoofing is
not an issue.

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.

Student Book Content


Exercise 4: Implementing the RegularExpressionValidator Control
Scenario
In this exercise, you will use a RegularExpressionValidator control to validate the user entry in the Coverage
box.
The main task for this exercise is as follows:
Add a RegularExpressionValidator control.

Task 1: Add a RegularExpressionValidator control

Module 06-Validating User Input página 137


1. Use the Toolbox to add a RegularExpressionValidator control to the life.aspx Web Form, next to the
coverageValidator control.
2. Set the properties for the RegularExpressionValidator control as shown in the following table.
Property Value
ID coverageRegexValidator
ErrorMessage Coverage must be a currency value
Text *
ControlToValidate coverageTextBox
ValidationExpression \d+(\.\d{2})?

Your page should resemble the following illustration.

Module 06-Validating User Input página 138


Adding User Controls to an ASP.NET Web Form
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Lesson overview

Student Book Content


Lesson 1
Adding User Controls to an ASP.NET Web Form
A user control is a Microsoft ® ASP.NET page that other Web Forms can import as a server control. Similar to Web
server controls, which are components that run on the server, user controls provide UI and other related
functionality. After you create a user control, other Web pages in the same Web application can then use the
control.
This lesson describes user controls and explains why they are a useful addition to your Web applications. It also
describes how to reference a user control from an ASP.NET Web Form and how to access the properties in a user
control.

Module 07-Creating and Implementing User Controls página 139


What Is a User Control
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Ensure that the students understand that user controls and Web server controls are not the same.
Students can easily confuse the two terms. Components provide logic only and are precompiled. Web
server controls are a special type of component that have a user interface.
Also, inform the students that user control, Web Forms user control, and Web user control are three
different terms that are used to refer to the same thing.
It is possible to precompile user controls because they can be incorporated into the Web application
Dll. However, avoid this discussion during the current module and revisit this issue in the deployment
module (module 15).

Student Book Content


What Is a User Control?
Key Points
User controls enable you to reuse code and common UI components. User controls have the following features:
A user control resides in a Web Forms page.
A user control participates in the event life cycle for the Web Form.
A user control has its own page logic.

Question: How can user controls be useful in your own applications?


CD Content
User controls can simplify the reuse of code and common UI components. You must therefore understand what
they are and how they work before you can develop effective ASP.NET applications
Definition
User controls are ASP.NET pages with an .ascx file extension. User controls offer you an easy way to partition and
reuse common UI functionality across your ASP.NET Web applications. Similar to a Web Forms page, you can author
these controls by using any text editor or develop them by using code-behind classes. In addition, similar to a Web
Forms page, user controls are typically compiled when first requested and then stored in server memory to reduce
the response time for subsequent requests. Unlike Web Form pages, however, user controls cannot be requested
independently; user controls must be included in a Web Forms page to work.

Note: The Microsoft .NET Framework prevents files with the .ascx file extension from being viewed in a Web
browser. This security measure ensures that you cannot view the user control as a stand-alone ASP.NET page.

Module 07-Creating and Implementing User Controls página 140


Why Use User Controls
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Establish the importance of user controls and explain that user controls are self-contained, that
students can reuse them across the pages of an application, and write them in a different language
from the rest of the application.
Mention that copying a user control to the root of multiple Web applications will have implications for
source code control.

Student Book Content


Why Use User Controls?
Key Points
User controls have several advantages, including the following:
User controls are self-contained. None of the methods and properties of the user control conflict with the methods
or properties of the hosting page.
User controls can be used more than once in a hosting page without causing property and method conflicts.
User controls can be written in a different language from the main hosting page.

CD Content

Module 07-Creating and Implementing User Controls página 141


Creating User Controls
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Creating User Controls
After you create a user control, other pages in the same Web application can use it. This lesson describes how to
create and implement user controls.

Module 07-Creating and Implementing User Controls página 142


Creating a User Control
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Inform the students that when they create a new user control, an .ascx file is created.
Describe the methods that they can use to create a user control.
If the students are not familiar with property procedures in Microsoft Visual C#®, clarify that the input
parameter, value, for the set part of the procedure is automatic.

Student Book Content


Creating a User Control
Key Points
You can create a user control by using either of the following two methods:
Create a new user control by using the Add New Item dialog box in Visual Studio 2008.
Convert an existing ASP.NET page to a user control by changing the file extension of the page to .ascx and modifying
the markup in the source of the control.

Question: What properties may be required for a user control that contains a check box?

Module 07-Creating and Implementing User Controls página 143


Adding a User Control to a Web Form
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Naming is an area that can create confusion for students. Ensure that students are clear about the
difference between the following attributes:
• TagPrefix
• TagName
• Src
Mention that in Microsoft Visual Studio® 2008, students can now display the graphical interface of the
control in Design view from the hosting page.

Student Book Content


Adding a User Control to a Web Form
Key Points
The @ Register directive includes a user control in an ASP.NET page. This directive includes the following
attributes:
TagPrefix. Unique namespace for the user control to differentiate multiple user controls that have the same
name.
TagName. Unique name for the user control.
Src. Virtual path to the user control file.

CD Content

Module 07-Creating and Implementing User Controls página 144


Demonstration - Creating and Implementing a User Control
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


Use this demonstration to illustrate the previous topics as you cover them.
In this demonstration, students will see how to create and implement a user control by using Visual
Studio 2008.
To run this demonstration
1. In Visual Studio 2008, open the UserControlCS or UserControlVB Web site in the
Democode\Starter\CS or Democode\Starter\VB folder.
2. Examine the HTML source of the Default.aspx page in the application.
The HTML uses the same combination of controls (a text box and two validation controls) in two
places.
3. In Design view, select and copy the first set of text box and validation controls on the
Default.aspx page.
4. Add a new Web User Control to the project. Name the user control numberBox.ascx.
5. Show the HTML for the page and point out the @ Control directive that was created by
Visual Studio 2008.
6. In Design view, paste the text box and validation controls onto the user control.
7. Open the code-behind page for the new user control.
8. In the code-behind page named numberBox.ascx.cs or numberBox.ascx.vb, in the
numberBox class, create a public property for the value of the text box. The following
code example illustrates this.
[Visual C#]
public int pNum
{
get
{
return Convert.ToInt32(number1TextBox.Text);
}
set
{
number1TextBox.Text = Convert.ToString(value);
}
}
[Visual Basic]
Public Property pNum() As Integer
Get
Return CInt(number1TextBox.Text)
End Get
Set(ByVal Value As Integer)
number1TextBox.Text = Value.ToString()
End Set
End Property
Point out that when you enter the header for the pNum property, Visual Studio 2008 creates a
template for the Get and Set properties.
Point out that the Set property does not take any arguments. The value that is passed is
automatically placed into a variable called value, which is accessible to the Set property.
9. Create an event handler for the Text_Changed event of the text box in the user
control.
10. In the Default.aspx code-behind file, copy the code from the
number1TextBox_TextChanged event handler to the
number1TextBox_TextChanged event handler in the user control.

Module 07-Creating and Implementing User Controls página 145


number1TextBox_TextChanged event handler in the user control.
11. In the code-behind file for the numberBox user control, import the
System.Drawing namespace.
12. Save your changes to the numberBox.ascx page.
13. View the Default.aspx page in Design view.
14. Delete the two sets of text boxes and validation controls (six controls in all).
15. In Solution Explorer, drag the numberBox.ascx user control onto the Web Form at
the location of the first set of controls that you deleted.
16. View the HTML for the page; the @ Register directive was added by Visual Studio
2008, along with the tag for the user control.

Student Book Content

[Visual Basic]
sumLabel.Text = (num1.Number + num2.Number).ToString()

The following example calls the Set property of the num1 and num2 user controls to display the constants 5 and 7
in the user control.
[Visual C#]
num1.Number = 5;
num2.Number = 7;

[Visual Basic]
num1.Number = 5
num2.Number = 7

Module 07-Creating and Implementing User Controls página 146


Lab - Creating and Implementing User Controls
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


21. Save and build the Web application.
22. View the Default.aspx Web Form in the browser.
23. View the HTML source in the browser.
24. Describe how the user controls are rendered in HTML and then close the browser
window.
25. In the numberBox.ascx user control, add initialization code to the Page_Load
event procedure.
[Visual C#]
if (!Page.IsPostBack)
number1TextBox.Text = "0";
[Visual Basic]
If Not Page.IsPostBack Then
number1TextBox.Text = "0"
End If
26. Save your changes and then view the Default.aspx page in the browser again.
Point out that the user control now has an initial value of 0.
27. Close the browser window, and then close the application.

Student Book Content


Lab: Creating and Implementing User Controls
Exercise 1 Creating a User Control
Scenario
In many pages of the Coho Winery Benefits Web site, you collect the name and birth date from the user. In this lab,
you will create a user control to collect that information and then use this control on the medical.aspx page of the
Web site.
In this exercise, you will create a user control from the Name and Birth Date controls on the life.aspx page.
The main tasks for this exercise are as follows:

Module 07-Creating and Implementing User Controls página 147


Exercise 1 - Creating a User Control
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


In this lab, students will create and implement a user control
Exercise 1
In this exercise, students create a user control.
Exercise 2
In this exercise, students implement a user control.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

Write down the HTML that is created by Visual Studio 2008 for the user control.

4. Open the medical.aspx page in Design view.


5. On the medical.aspx page, double-click Save to create a Click event procedure.
6. In the Click event procedure, write code to output the name and birth date values from the user control into
the Label2 control on the medical.aspx page
Your code should resemble the following example.
[Visual C#]
protected void saveButton_Click(object sender, EventArgs e)
{
Label2.Text = nameDate1.EmpName + " born on " +
nameDate1.EmpDOB.ToLongDateString();
}

[Visual Basic]
Protected Sub saveButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles saveButton.Click
Label2.Text = nameDate1.EmpName & " born on " & _
nameDate1.EmpDOB.ToLongDateString()
End Sub

7. Save the medical.aspx code-behind file.


8. View the medical.aspx page in the browser.
9. In the browser, enter a name and birth date, and then click Save.
10. Verify that the name and birth date values appear in the Label control next to Save.
11. Close the browser window.

Module 07-Creating and Implementing User Controls página 148


Module 07-Creating and Implementing User Controls página 149
Exercise 2 - Implementing a User Control
Saturday, September 06, 2008
12:24 AM

Instructor Notes (PPT Text)


In many pages of the Coho Winery Benefits Web site, students collect the name and birth date from
the user. In this lab, students will create a user control to collect that information and then use this
control on the medical.aspx page of the Web site.

Student Book Content


5. Can you use two different user controls with the same name in the same ASP.NET page? Why or why not?
Yes. You can use the TagPrefix and TagName attributes of the @ Register directive to distinguish
each user control.

Module 07-Creating and Implementing User Controls página 150


Overview of ADO.NET
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Overview of ADO.NET
Because of the importance of data storage in Web applications, you must have a thorough understanding of the
data access methods that ADO.NET provides for ASP.NET Web Forms. This lesson explains what ADO.NET is and
how it works.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 151
What Is ADO.NET
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this information. Each option will be reviewed in context
in later topics in this lesson.
Note: Depending on the knowledge of the students, you may have to explain what ADO is. A brief
history lesson may be required; however, do not emphasize the topic.

Student Book Content


What Is ADO.NET?
Key Points
ADO.NET has the following attributes:
Consists of a set of classes that you can use to connect to and manipulate data sources.
Transfers data in XML format between the database and your Web application.
Contains numerous improvements over the previous version of ADO.

You can easily connect your Web application to a database by using ADO.NET.
Question: Why is ADO.NET more compatible and flexible than ADO?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 152
The ADO.NET Object Model
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Mention that there are also data providers for ODBC and Oracle.

Student Book Content


The ADO.NET Object Model
Key Points
The ADO.NET object model provides an infrastructure that you can use to access data from different data sources.
There are two main components of the ADO.NET object model:
DataSet. Contains one or more DataTables and is designed for data access, regardless of the data source.
.NET Data Provider. Links the data source and DataSet.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 153
DataSets and DataReaders
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


The key point is that DataReader provides fast read-only access to data.

Student Book Content


DataSets and DataReaders
Key Points
DataSet objects are complex objects that enable you to store multiple DataTables of data from a data source.
DataSet objects consume a lot of resources.
DataReader objects are lightweight objects that you can use for read-only access to the data in a database.
Because most of the data on a Web page must only be read, you typically use more DataReader objects than
DataSet objects if you require a higher performance.

Question: When should you use a DataReader object instead of a DataSet object?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 154
Accessing Data with ADO.NET
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


This is an animated slide. The numbered items and matching arrows appear in sequence.

Student Book Content


Accessing Data with ADO.NET
Key Points
There are typically three stages in data access:
1. Accessing the data from a data source and displaying it on an ASP.NET Web Form.
2. Manipulating the data.
3. Sending the data updates back to the database.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 155
Connecting to a Database
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Connecting to a Database
ADO.NET is used to connect a Web Form to a database. This lesson explains how to connect to different types of
databases by using ADO.NET objects. It also explains how to store data in a DataSet.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 156
Generating a Connection by Using Server Explorer
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Use a brief demonstration to illustrate how simple and quick it can be to create a connection to a
database.
Note: The server name indicates the named instance of SQL Express installed by default on the
virtual computer. This server does not have to be the local computer and is typically changed to the
production server after deployment (by storing connection strings in the Web.config file). The use of
SQLExpress for development is an excellent option if the application is eventually deployed to
Microsoft® SQL Server® because typically only the server name must be adjusted; for example, you
do not have to change Multiple Active Result Sets (MARS) settings. If you perform a demonstration,
you can show the advanced options of the Add Connection dialog box.

Student Book Content


Generating a Connection by Using Server Explorer
Key Points
In the Visual Studio integrated development environment (IDE), you can use Server Explorer to add a connection to
a database. The Add Connections dialog box enables you to configure the connection. You can also add a
connection to a database by using code.
Server Explorer displays all connections in Data Connections. You can also use Server Explorer to create database
objects, investigate the properties of existing objects, and preview data.
Question: How can you change the data source type for a connection?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 157
The DataAdapter Object Model
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Explain that the DataAdapter is used to populate a DataSet with data from an existing data source.
Explain that DataSet objects can be typed or untyped:
• Typed. Typed DataSet objects are derived from the base DataSet class and use information
in an XML schema file (an .xsd file) to generate a new class. The information from the
schema (such as tables and columns) is generated and compiled into this new DataSet
class as a set of objects and properties.
• Untyped. Unlike typed DataSet objects, untyped DataSets have no corresponding built-in
schema. However, similar to typed DataSet objects, untyped DataSet objects include
tables and columns that are only exposed as collections.
Note: For the topic question, you can provide the following hint: "What SQL DML statements do you
know about?"

Student Book Content


The DataAdapter Object Model
Key Points
When a DataAdapter connects to a database, it uses a Connection object to connect to a database and
Command objects to retrieve data and resolve changes to the database.
The DataAdapter object has four command-type properties that contain SQL statements or call stored procedures
in the database.
Question: What are the four command-type properties?
CD Content
When a DataAdapter connects to a database, it uses several other objects to communicate with the database.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 158
Generating a DataSet
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Briefly mention the points in this topic because the content is covered in more detail in the next
lesson.
Note: You may want to point out to the students that you can create a typed DataSet to represent
the schema of a data store. You can add a new DataSet object (XML schema file) to the App_Code
folder and use it to programmatically create a DataSet object.

Student Book Content


Generating a DataSet
Key Points
To populate a DataSet, perform one of the following:
Add code to the Page_Load event procedure.
Add code to an event procedure of a control that uses a DataAdapter object.

Question: How can you fill a DataSet with data?


CD Content
To populate a DataSet, you typically add code to the Page_Load event procedure or to an event procedure of a
control that uses a DataAdapter object.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 159
Creating a Connection Programmatically
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Emphasize that the Persist Security Info parameter is useful when you build an administration tool
or debug an application.
Note: To create the connection string, you can also use Server=localhost;
Database=MyDatabase; Trusted_Connection=true. Also point out that connection strings have
many other parameters and they are typically dependent on the provider. You can find a more
comprehensive list in the documentation for the provider.

Student Book Content


Creating a Connection Programmatically
Key Points
To create a connection to a database, you must identify the name of the database server, the name of the database,
and the required login information. You can pass these settings as parameters to the constructor of a connection
object or save the connection string in the web.config file.
You can use a SqlConnection object to connect to SQL Server databases and the OleDbConnection objects to
connect to all other databases.
Question: Which connection string parameter is the name of the database?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 160
Accessing Data
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Briefly make comparisons between the DatSet and DataReader objects and typical usage scenarios.
For example, use DataSets for read and write access and use DataReaders for fast read-only
access. Explain that you can use a combination of both objects.

Student Book Content

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 161
Binding Data to Controls by Using the IDE
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Continue with the demonstration from the previous topic and show the students how to use Solution
Explorer to add a control to a Web Form and bind the properties of the control to a data source. In the
Properties window, set the properties of the GridView control to provide formatting, editing, and
other common functionality.
Note: Ask the topic question before you continue with the demonstration from the previous topic.
Also, explain that you can use Common GridView Tasks window to set most of the useful properties of
a GridView control, for example, Autoformat.

Student Book Content


Binding Data to Controls by Using the IDE
Key Points
You can use Server Explorer to add data directly to a Web Form.
When you add data in this manner, Visual Studio creates a GridViewcontrol and a SqlDataSource control and
sets the properties of the controls accordingly.
Question: How can you implement paging or sorting in a GridView control?
CD Content
The Visual Studio 2008 IDE enables you to create database connections, automatically create a GridViewcontrol
and a SqlDataSource object from a database table, and set properties of connections and data controls.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 162
Creating a Command Object
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Ensure that the students understand that each data provider has its own command object (such as
SqlCommand or OleDbCommand).
Explain the code required to use each of the command methods.
Explain that if a method returns a result as a boxed object, it is good programming practice to unbox
or cast the value to the expected type.
Emphasize that the ExecuteScalar method returns an object.

Student Book Content


Creating a Command Object
Key Points
You can use a Command object to retrieve and modify data. A Command contains a database query and is
represented by the provider-specific classes SqlCommand, OleDbCommand, OdbcCommand, and
OracleCommand.
You can use the methods of a Command object to obtain a DataReader object, retrieve a single scalar value, or
execute a stored procedure.
CD Content
You can use a Command object to retrieve and modify data. A Command contains a database query and is
represented by the provider-specific classes SqlCommand, OleDbCommand, OdbcCommand, and
OracleCommand. The SqlCommand class provides four different methods to execute a command.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 163
Creating a Data Reader
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Remind the students that a DataReader provides read-only, forward-only access to data.
Explain that the key steps are to create an instance of the Command object and then create a
DataReader by calling Command.ExecuteReader.
Explain that for performance reasons, you open the connection as late as possible and close it as soon
as possible. Because this is a connected operation, you must manage the connection yourself.
ADO.NET is designed to operate in a disconnected way. Therefore, if you want to perform connected
operations, you must write extra code to provide that functionality.

Student Book Content


Creating a Data Reader
Key Points
To use a SqlDataReader object, you must create a SqlCommand object.
The SqlCommand object exposes an ExecuteReader method that returns a SqlDataReader object.
You can create a Command object from a SQL statement and a connection, but you must also explicitly open and
close the Connection object.
Question: Why must you always explicitly close the Connection object?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 164
Retrieving Data by Using a DataReader
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Explain that it is possible to access each column of a returned row by passing the name or ordinal
reference of the column to the DataReader. However, for best performance, the DataReader
provides a series of methods that you can use to access column values in their native data types (for
example, GetDateTime and GetDouble).

Student Book Content

// Close DataReader and connection.


myDataReader.Close();
connection.Close();

[Visual Basic]
' Open connection and create command.
Dim connection As New SqlConnection _
("data source=localhost;integrated security=true;" & _
"initial catalog=myDatabase")
Dim authorsSqlCommand As New SqlCommand _
("select * from Authors", connection)
connection.Open()

' Create DataReader and display data.


Dim myDataReader As SqlDataReader
myDataReader = authorsSqlCommand.ExecuteReader()
Do While myDataReader.Read()
namesListBox.Items.Add(myDataReader("LastName") + ", " + _
myDataReader("FirstName"))
Loop

' Close DataReader and connection.


myDataReader.Close()
connection.Close()
Error Handling with DataReader Objects
When you use connections with the DataReader object, you must always use a Try"¦Catch"¦Finally statement to
ensure that if anything fails, the connection will close. Otherwise, the connection may be left open indefinitely.
The following code for a DataReader object catches errors and closes the connection.
[Visual C#]
try
{
connection.Open();
myDataReader = authorsSqlCommand.ExecuteReader();
// Use the returned data in the DataReader.
}

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 165
// Use the returned data in the DataReader.
}
catch(Exception e)
{
// Handle the error.
}
finally
{

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 166
Creating a DataSet
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Refer the students back to the DataAdapter object model in the second lesson. Explain that they can
programmatically create a DataTable, DataRelation, and Constraint in a DataSet and populate the
tables with data. However, typically they will want to populate the DataSet with data from an existing
data source and for this they can use a DataAdapter.
In the code examples, explain that the second string parameter of the Fill method is the table name
associated with the DataTable object in the DataSet. For a typed dataset, exceptions can be thrown
if the results returned from executing the select command do not conform to the schema.
Note: To create a typed data set, add an .xsd file to the Web application and create an instance of the
class.

Student Book Content


Creating a DataSet
Key Points
To create a local copy of a database, you can create and populate a DataSet object by using DataTable objects.
Firstly, declare the DataSet object name, and then fill the DataTable objects by creating a DataAdapter object.
After you have placed data in a DataSet object, you can programmatically access the data.
Question: What does the SelectCommand property of the DataAdapter object contain?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 167
Displaying a DataSet in a List-Bound Control
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Use a simple demonstration to show students how to bind a DataSet to any list-bound control on a
Web Form.

Student Book Content

// Create the DataSet.


DataSet myDataSet = new DataSet();

// Create the DataAdapter.


SqlDataAdapter myDataAdapter = new SqlDataAdapter
("select * from Authors", connection);

// Fill the DataSet myDataSet.


myDataAdapter.Fill(myDataSet, "Authors");

[Visual Basic]
' Create a connection.
Dim connection As New SqlConnection _
("data source=localhost;initial catalog=pubs;" & _
"integrated security=SSPI;persist security info=True;")

' Create the DataSet.


Dim myDataSet As New DataSet()

' Create the DataAdapter.


Dim myDataAdapter As New SqlDataAdapter _
("select * from Authors", connection)

' Fill the DataSet myDataSet.


myDataAdapter.Fill(myDataSet, "Authors")
The second argument to the Fill method is a name for the DataTable object that is created. You use this name to
access the returned data.
Accessing a DataTable
After you have placed data in a DataSet object, you can programmatically access the data. As the following code
illustrates, each DataSet object consists of one or more DataTable objects that you can refer to by name or by
ordinal position.
[Visual C#]
myDataSet.Tables["Authors"];
-or-
myDataSet.Tables[0];

[Visual Basic]

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 168
[Visual Basic]
myDataSet.Tables("Authors")
-or-
myDataSet.Tables(0)

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 169
Handling Exceptions
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Ensure that the students understand the importance of error handling when you attempt to access
data.
Explain that the severity levels 1-10 are informational or warning errors and do not invoke the client
exception handler. To capture these messages, developers must enumerate the errors collection to
check for these specific class errors if necessary.
If an error with severity level 20-25 occurs, the server closes the connection. This may cause other
parts of your code to break if it relies on this connection. To minimize the impact of this, it is always
good practice to check for the connection state before you open or close the connection.

Student Book Content

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 170
Accessing Multiple Tables
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 4
Accessing Multiple Tables
One of the strengths of DataSet objects is that they can contain multiple DataTable objects, and each DataTable
object can come from a different data source.
This lesson explains how to store multiple tables of data in a DataSet object. It also explains how to display that
data in GridView controls.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 171
Storing Data From Multiple Tables
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


A best practice for storing multiple tables is to use one DataAdapter for each table in the DataSet.

Student Book Content


Storing Data From Multiple Tables

Key Points
To fill a DataSet object with multiple DataTable objects that come from one or more data sources, you can use
multiple DataAdapter objects.
You can control the order in which updates are written to and from the database because the order of the
DataAdapter objects controls the order of implementation.
You must use a new DataAdapter object for each DataTable object in a DataSet object.
Question: How can you preserve referential integrity between related tables in a database?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 172
Creating Relationships
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Explain that a DataRelation enables navigation from one DataTable to another in a DataSet.

Student Book Content

'Create the first DataTable.


customersDataAdapter = New SqlDataAdapter _
("select CustomerID, CompanyName from Customers", _
pubsConnection)
customersDataAdapter.Fill(myDataSet, "Customers")
Adding Subsequent Tables
After the first DataTable object is loaded, you can fill additional DataTable objects and define the relationships
between the objects based on the initial DataTable object. You must define the relationships to enforce referential
integrity.
The following code continues from the preceding example and populates the Orders DataTable object by using a
DataAdapter object named ordersDataAdapter.
[Visual C#]
// Create the second DataTable.
ordersDataAdapter = new SqlDataAdapter
("select CustomerID, OrderID, OrderDate, ShippedDate " +
"from Orders", pubsConnection);
ordersDataAdapter.Fill(myDataSet, "Orders");

[Visual Basic]
' Create the second DataTable.
ordersDataAdapter = New SqlDataAdapter _
("select CustomerID, OrderID, OrderDate, ShippedDate " & _
"from Orders", pubsConnection)
ordersDataAdapter.Fill(myDataSet, "Orders")

Note: You must use a new DataAdapter object for each DataTable object in a DataSet object, particularly if you
want to submit changes back to a data store.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 173
Programmatically Navigating Between Tables by Using
Relationships
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Briefly explain the code required to navigate between tables by using a DataRelation.
Note: You can use the CreateChildView method to visually navigate from one DataTable object to
another DataTable object in a DataSet object. For more information about the CreateChildView
method, see "DataRowView.CreateChildView Method (DataRelation)" at
http://go.microsoft.com/fwlink/?LinkId=111442.

Student Book Content


Programmatically Navigating Between Tables by Using Relationships
Key Points
When you want to work with data from related tables, you can use the DataSet object.
The DataSet object enables you to work with multiple DataTable objects and define a relationship between
them.
You can use the relationship to navigate between related records in the tables.
Question: What functionality do the GetChildRows and GetParentRowmethods of a DataRowobject provide?

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 174
Lab - Accessing Data with Microsoft ADO.NET and Visual Studio
2008
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


In this lab, students will access data with Microsoft ADO.NET and Microsoft Visual Studio® 2008.
Exercise 1
In this exercise, students display data from a SQL Server database on a Web Form.
Exercise 2
In this exercise, students implement paging and selection in a GridView control.
Exercise 3
In this exercise, students retrieve data from a SQL Server database by using a SqlDataReade r.
Exercise 4
In this exercise, students implement an All option and reset functionality in a Web page.
Note: In Exercise 3, a database request is sent every time that the user selects a new item in the list.
Explain that if you view static data in the GridView control, it is not best practice to request the data
every time you view the data. Emphasize this point so that students think about optimizing their data
access code. At this stage, students are becoming aware that they must consider performance for
many facets of ASP.NET development.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Accessing Data with Microsoft ADO.NET and Visual Studio 2008
Exercise 1: Connecting to the Doctors Database
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 175
Exercise 1 - Connecting to the Doctors Database
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


One benefit that is offered by Coho Winery is medical insurance. When users apply for medical
insurance, they must select a primary care physician. The doctors that are approved by Coho Winery
are all listed in a SQL Server database. In this lab, students will create a page to display all of the
doctors in the database and enable a user to select one of the doctors as their primary care physician.
The doctors' addresses are also in the database. Students will enhance the doctors.aspx page to
enable users to list doctors that are in specific cities.

Student Book Content

Results:After this exercise, you have implemented paging for the DataGrid control on the doctors.aspx page and
enabled the user to select a doctor from the DataGrid.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 176
Exercise 2 - Paging and Selection in a GridView Control
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. How can you add a connection to a database?
In Server Explorer, right-click the Data Connections folder, and then click Add Connection.
In the Add Connection dialog box, configure the connection, and then click OK.
2. What control is created when you drag a table from Server Explorer to a Web page?
Visual Studio creates a GridView object and a SqlDataSource object and sets the properties
of the objects.
3. How can you enable paging for a GridView control?
When the control is selected, in the Properties window, set the AllowPaging property to
True.
4. How can you add a select column to a GridView control?
In the Columns property of the control, add a Select CommandField.
5. When you use Connection and SqlDataReader objects, what must you do?
To minimize the impact on system resources, call the Close method on the objects when
they are no longer required.

Student Book Content


Dim myDataSet As New DataSet()
3. What code creates a connection to a database named Coho, on the local computer running SQL Server, by using
integrated security?
[Visual C#]
connection = new SqlConnection("data source=localhost;" +
"integrated security=true; initial catalog=coho");

[Visual Basic]
connection = New SqlConnection("data source=localhost;" & _
"integrated security=true;initial catalog=coho")
4. What is the difference between a DataSet and a DataReader object?
The DataSet object is designed to handle the actual data from a data store. The DataSet class
represents a cache of data and has database-like behavior. The DataSet object contains tables,
columns, relationships, constraints, and data. After the connection to the database is closed, the
DataSet continues to exist. The DataReader class is designed to produce a read-only, forward-only
stream that is returned from the database. The DataReader is destroyed when the connection to
the database is closed.
5. How do you create a relationship between two DataTable objects in a DataSet object?
Create a new DataRelation object from the two related DataColumns of the DataTable objects, and
then add the DataRelation object to the Relations collection of the DataSet object.

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 177
Exercise 3 - Implementing a SqlDataReader
Saturday, September 06, 2008
12:28 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• You want to combine tables from three databases. Can you use a DataSet object or a
DataReader object?
You can only use a DataSet object. DataReader objects are based on a single or multiple
SQL statements from a single database.
• You require high-speed access to your data source. Why must you use a DataReader object
instead of a DataSet object?
DataSet objects access data from a database more slowly than DataReader objects because
DataSet objects store the data in an object on the Web server. There is also more overhead
when you create a DataSet object
• You intend to both read from and write to your data source. Why must you use a DataSet object
instead of a DataReader object?
If you intend to both read from and write to your data source, you must use a DataSet
object. DataReader objects are read-only connections and you must use them only when
the data will be used in a read-only situation.

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.

Student Book Content

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 178
Exercise 4 - (If Time Permits) Viewing Doctors from All Cities
Saturday, September 06, 2008
12:28 AM

Student Book Content

Module 08-Accessing Data with Microsoft ADO.NET and Visual Studio 2008 página 179
Overview of Stored Procedures
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Overview of Stored Procedures
One alternative to direct database access from your Web application is to call a stored procedure that accesses the
database for you. Stored procedures have several advantages over direct database access; these include efficiency,
security, and the protection of the database.
This lesson describes stored procedures and explains the reasons why you call stored procedures when you access a
database.

Module 09-Accomplishing Complex Data Access Tasks página 180


What Is a Stored Procedure
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Check to see how familiar your students are with stored procedures. You may be able to skim this first
lesson.

Student Book Content


What Is a Stored Procedure?
Key Points
You create stored procedures for use with a specific database and store them in that database. Stored
procedures that you create in a SQL Server database consist of one or more sequences of Transact-SQL
statements and can have input and output parameters.
Question: What stored procedures do you use in your own applications?
CD Content
A stored procedure is a database procedure that a database developer writes for use with a specific database. Other
Web applications can then call these stored procedures to access and manipulate data in the database.
Programmatic Access to a Database
Stored procedures enable you to call an existing procedure to access a database, rather than writing your own SQL
statements. You build stored procedures in a SQL Server database from sequences of Transact-SQL statements.
Stored procedures function similarly to procedures in a Web application in that your code calls them by name, and
the stored procedures can have both input and output parameters.
The three types of stored procedures are:
Return records stored procedures. You use return records stored procedures to find specific records, sort and filter
those records, and then return the result to a data set or to a list-bound control. These stored procedures are based
on SQL Select statements.
An example of a return records stored procedure is a request for the amount, date, and recipient of the last three
checks that were processed in a bank account. You can load this data into a DataSet object for further processing
or display it directly to the user in a ListBox control.
Return value stored procedures, also known as scalar stored procedures. You use return value stored procedures to
run a database command or function that returns a single value. Because only one value is returned, you often use
return value stored procedures in code and then display the result to users.

Module 09-Accomplishing Complex Data Access Tasks página 181


Why Use Stored Procedures
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Discuss the advantages of stored procedures over manual queries.

Student Book Content


Why Use Stored Procedures?
Key Points
Stored procedures have several advantages over direct Transact -SQL statements. For example, they can provide
increased security, faster performance, flexibility, and a reduction in network traffic.
Question: How can stored procedures improve the security or performance of your own applications?
CD Content

Module 09-Accomplishing Complex Data Access Tasks página 182


Calling Stored Procedures
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Calling Stored Procedures
Before you can call a stored procedure, you must identify the procedure name and the available parameters. After
you identify the stored procedure, you can call the procedure, pass any input parameters that are required to
process your request, and handle the output parameters that are included in the response.
This lesson describes how to call stored procedures, pass input parameters, and handle output parameters.

Module 09-Accomplishing Complex Data Access Tasks página 183


Calling Stored Procedures
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Mention that the lesson starts with simple stored procedures and then explains more complex stored
procedures with parameters.
Explain that you can identify the stored procedure type in Microsoft® Visual Studio® 2008 by using
Server Explorer and also create, modify and debug stored procedures. You can briefly show this in the
demonstration; in particular, show the students how to read the output data types and names of
stored procedures. (Also mention that stored procedures must not start with sp_.)

Student Book Content


Calling Stored Procedures
Key Points
The method that you call to run the stored procedure varies depending on the type of stored procedure that you
want to call, as shown in the following list:
Return records stored procedures. Call the Fill method of the DataAdapter to place the records in a DataSet or
call the ExecuteReader method of the Command object to place the records in a DataReader.
Return value stored procedures. Call the ExecuteScalar method of the Command object and save the result in a
variable of the appropriate data type.
Perform action stored procedures. Call the ExecuteNonQuerymethod of the Command object.

CD Content
To call a stored procedure, you must identify its type and then choose the method that you want to use to call the
stored procedure.
Identifying the Stored Procedure
When you call a stored procedure, the first step is to identify the type and name of the stored procedure.
You can use a DataAdapter object or a DataReader object to call all three types of stored procedures. The
method that you call to run the stored procedure varies depending on the type of stored procedure that you want
to call, as shown in the following list:
Return records stored procedures. When you call a stored procedure that returns a set of records, you can store
that set of records in a DataSet or use a DataReader to place the records directly into a list-bound control. If you
want to use a DataSet, you use a DataAdapter and the Fill method. If you want to use a DataReader, you use a
Command object and the ExecuteReader method and then bind the returned record into a list-bound control.
Return value stored procedures. When you call a stored procedure that returns a single value, call the
ExecuteScalar method of the Command object, and save the result in a variable of the appropriate data type.

Module 09-Accomplishing Complex Data Access Tasks página 184


Parameters in Stored Procedures
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Ensure that the students are familiar with the concept of parameters and specifically with the
difference between output parameters and the return value of a stored procedure. Emphasize that the
Direction property of a ReturnValue parameter must be set to ParameterDirection. ReturnVa lue.

Student Book Content


Parameters in Stored Procedures
Key Points
Parameters enable you to pass information into a stored procedure and receive information back from it.
The names of the parameters that you add to the Parameters collection of the SqlCommand object must match
the names of the parameters that are in the stored procedure; however, the order of the parameters is flexible.
Question: What is the difference between an output parameter and a return value parameter?
CD Content

Module 09-Accomplishing Complex Data Access Tasks página 185


Passing Input Parameters
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Step through the code required to create a parameter and add it to the Parameters collection.
Explain to the students that they can use the workParam1 variable shown in the code example to
create additional parameters; these include input, output, or return value parameters.

Student Book Content


Passing Input Parameters
Key Points
To create an input parameter, use the following steps:
Create a new SqlParameter object with the name and data type of the parameter.
Set the Direction property of the new parameter.
Use the Add method of the Parameters collection to save the new parameter.

CD Content
After you identify the parameters that a stored procedure supports, you must then add the parameters that you
require to the Parameters collection of the Command object.

Module 09-Accomplishing Complex Data Access Tasks página 186


Accessing Output Parameters
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Step through the code required to read the value of an output parameter.

Student Book Content


Accessing Output Parameters
Key Points
To read the value of an output parameter or to read a returned value from a return records stored procedure, you
access the value of the output parameter in the Parameters collection after the stored procedure has run.
CD Content
To read the value of an output parameter or to read a returned value from a return records stored procedure, you
access the value of the output parameter in the Parameters collection after the stored procedure has run.
Example of Output Parameters

Module 09-Accomplishing Complex Data Access Tasks página 187


Demonstration - Passing Parameters
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


You can use the demonstration to illustrate the topics in this lesson as you discuss them.
In this demonstration, students will see how to call a stored procedure with one input parameter and
then bind the results to a GridView control.
To run the demonstration
1. In the Democode\CS or Democode\VB folder, open the Parameters Web site.
2. View the default.aspx page in the browser.
3. In the available list, select a specialty.
4. Click Get Data.
5. A GridView control is bound to the DentistsBySpecialty stored procedure in the
Dentists database.
6. In Visual Studio 2008, view the code -behind page for the default.aspx page.
7. In the getDataButton_Clic k event procedure, point out the code that does the
following:
a. Creates the SqlConnection.
b. Creates the SqlDataAdapter and sets properties of the SelectCommand object to
call the DentistsBySpecialty stored procedure.
c. Creates the input parameter.
d. Creates a new DataSet and fills the DataSet from the DataAdapter.
8. Comment out the code underneath the "Call a stored procedure by using a
DataAdapter"• comment.
9. Uncomment the code underneath the "Call a stored procedure by using
ExecuteReader"• comment.
10.View the default.aspx page in the browser.
11.In the available list, select a specialty.
12.Click Get Data.
13.In Visual Studio 2008, view the code -behind page for the default.aspx page.
14.In the getDataButton_Clic k event procedure, point out the code that does the
following:
a. Creates the Command object.
b. Adds the input parameter and set its properties.
c. Executes the DataReader.
If you have time, extend the demonstration to show how to read a return value from a stored
procedure. Add a Return @@rowcount statement to the stored procedure in the database, and
construct the appropriate code to read this value and display it in a label control on the page. Ensure
that you include code to close the reader first before you access the return value.

Student Book Content


Demonstration: Passing Parameters
In this demonstration, you will see how to call a stored procedure that has two input parameters and then bind the
results to a GridView control.

Module 09-Accomplishing Complex Data Access Tasks página 188


Data Access by Using LINQ to SQL
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Data Access by Using LINQ to SQL
Microsoft Visual Studio ® 2008 and the .NET Framework 3.5 introduce Language-Integrated Query (LINQ), which
provides a way for you to query data by using Microsoft Visual C# ® or Microsoft Visual Basic ®. This lesson
introduces LINQ and describes how to use Visual Studio 2008 to query a SQL Server database by using LINQ to SQL.

Module 09-Accomplishing Complex Data Access Tasks página 189


What Is LINQ
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Mention that Language-Integrated Query (LINQ) is a part of the .NET Framework 3.5. Explain that this
version of the Framework includes libraries that provide LINQ support for data stores that include
DataSets, objects, relational databases, and XML.

Student Book Content


What Is LINQ?
Key Points
Language-Integrated Query (LINQ) provides a programming model that you can use to retrieve and update data
from a variety of sources by using Visual C# and Visual Basic syntax.
Visual Studio 2008 provides designer tools that you use to create an object-relational mapping to the objects in the
data store that you want to query.
Question: What are the advantages of a model that enables you to use Visual C# or Visual Basic to query a
database?
CD Content
Visual Studio 2008 and the .NET Framework 3.5 introduce Language-Integrated Query (LINQ). LINQ provides a
programming model that you can use to retrieve and update data from a variety of sources by using Visual C# and
Visual Basic syntax. This capability gives you a simplified method to write queries because you can make use of your
current Visual C# or Visual Basic knowledge. LINQ also provides a unified syntax that you can use to query any data
source that supports LINQ.
Visual Studio 2008 provides designer tools that you use to create an object-relational mapping to the objects in the
data store that you want to query. You can also use the Microsoft IntelliSense ® and debugging support of Visual
Studio 2008 to catch and resolve errors at compile time.
LINQ Implementations
Visual Studio 2008 includes LINQ provider assemblies that enable you to use LINQ with several different types of
data, including the following:
LINQ to DataSet. A LINQ technology that enables you to query data cached in a DataSet object.
LINQ to Objects. A LINQ technology that enables you to query in-memory data such as arrays and lists.
LINQ to SQL. A LINQ technology that enables you to query data in relational databases.

Module 09-Accomplishing Complex Data Access Tasks página 190


Creating a LINQ to SQL Object Model
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Mention that the Object Relational Designer (O/R Designer) supports SQL 2000, SQL 2005, and SQL
Express.
Explain that students can open the O/R Designer by adding a new LINQ to SQL Classes item to a
project.
Use a simple demonstration to illustrate the topics of this lesson as you discuss them.

Student Book Content


Creating a LINQ to SQL Object Model
Key Points
You define the object model for a database in a LINQ to SQL Classes file, which has a .dbml extension.
To open the Object Relational Designer (O/R Designer), you add a LINQ to SQL Classes file to your application by
using the Add New Item dialog box.
CD Content

Module 09-Accomplishing Complex Data Access Tasks página 191


The DataContext Class
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Explain to the students that they can use DataContext methods to run stored procedures and
functions in a database.
Mention that it is also possible to add new methods to the DataContext class.
If students are interested, show the designer-generated entity classes in the Class View window.

Student Book Content


The DataContext Class
Key Points
Visual Studio 2008 creates an entity class for each database table in the O/R Designer. In addition, Visual Studio
2008 creates a DataContext class. This class contains properties that represent each table that you add to the O/R
Designer and methods that represent each stored procedure or function.
Question: What is the purpose of the DataContext class?
CD Content

Module 09-Accomplishing Complex Data Access Tasks página 192


Querying a Database
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Explain that after you create the object model, you can manipulate data through the model by using
the objects and properties that the model contains.

Student Book Content


Querying a Database
Key Points
After you model a database by using the O/R Designer, the next step is to write code that uses the model to run
queries against the database.
A query expression must always begin with a fromclause and end with either a select or a group clause. Other
optional clauses include join, where, let, and orderby.
CD Content
After you model a database by using the O/R Designer, the next step is to write code that uses the model to run
queries against the database.

Module 09-Accomplishing Complex Data Access Tasks página 193


Calling a Stored Procedure
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Explain the steps required to call a stored procedure by using LINQ to SQL.

Student Book Content

In addition, a query expression can contain a further query clause, which is often called a subquery.
Example of a LINQ to SQL Query
In the following code example, the data source consists of the reference to the DataContext class. The query
expression contains the three clauses from, where, and select, and the expression is stored in the variable
doctorNames. Finally, the for each clause runs the query and iterates through the results.
[Visual C#]
DoctorsDataContext context1 = new DoctorsDataContext();
var doctorNames = from docs in context1.doctors
where docs.city == "Seattle"
select docs.dr_fname + " " + docs.dr_lname;
foreach (var doc in doctorNames)
{
ListBox1.Items.Add(doc);
}

[Visual Basic]
Dim context1 As New DoctorsDataContext
Dim doctorNames = From docs In context1.doctors _
Where (docs.city = "Seattle") _
Select docs.dr_fname + " " + docs.dr_lname
For Each doc In doctorNames
ListBox1.Items.Add(doc)
Next

Module 09-Accomplishing Complex Data Access Tasks página 194


Binding a Data Model by Using the LinqDataSource Control
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


If you have time, use a simple demonstration to illustrate the use of the LinqDataSource control.
You can use the following high-level steps for this demonstration:
1. Create a new Web site and then add a LINQ to SQL Classes file to the Web site.
2. Add a data connection to the doctors database.
3. Drag the doctors table onto the O/R Designer.
4. Save the .dbml file.
5. Add a LinqDataSource control to the default.aspx Web page.
6. Set the data source property of the LinqDataSource control to the DataContext
class that represents the doctors data model.
7. Specify the doctors table and select several columns from the table as the data
selection for the LinqDataSource control.
8. Add a list-bound control such as a GridView to the Web page.
9. Set the data source property of the list-bound control to the LinqDataSource
control.
10. View the default.aspx page in the browser.
If you have time, you can also demonstrate how to create a method by using the right pane of the
O/R Designer.

Student Book Content


Binding a Data Model by Using the LinqDataSource Control
Key Points
The LinqDataSource control enables you to display data from a database by using LINQ to SQL but without
writing any code at all.
You can use a LinqDataSource control to bind to a LINQ data model and then set the DataSourceID of a list-
bound control to the LinqDataSource control.
Question: Describe a scenario when you may use a LinqDataSource control.
CD Content

Module 09-Accomplishing Complex Data Access Tasks página 195


Lab - Accomplishing Complex Data Access Tasks
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


In this lab, students will accomplish complex data access tasks from a Web application.
Exercise 1
In this exercise, students retrieve data from a Microsoft SQL Server™ database by using a stored
procedure.
Exercise 2
In this exercise, students access a stored procedure that contains a parameter and bind a
SqlDataReader object to a list.
Exercise 3
In this exercise, students retrieve data from a Microsoft SQL Server database by using LINQ to SQL.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Accomplishing Complex Data Access Tasks
Exercise 1: Get Unique City Names
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.
One benefit that is offered by Coho Winery is medical insurance. When users apply for medical insurance, they must
select a primary care physician. The doctors that are approved by your company are all listed in a SQL Server
database that is named doctors. The doctors' specialties are also in the database. In this lab, you will enhance the
doctors.aspx page on the Coho Winery Web site to enable users to view the list of specialties for a selected doctor.

Module 09-Accomplishing Complex Data Access Tasks página 196


Exercise 1 - Get Unique City Names
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


One benefit that is offered by Coho Winery is medical insurance. When users apply for medical
insurance, they must select a primary care physician. The doctors that are approved by your company
are all listed in a SQL Server database that is named doctors. The doctors' specialties are also in the
database. In this lab, students will enhance the doctors.aspx page on the Coho Winery Web site to
enable users to view the list of specialties for a selected doctor.

Student Book Content

11. Save the changes to the code-behind file.


12. View the doctors.aspx page in the browser.
The citiesList list displays the list of cities where the doctors are located. There are no duplicate cities listed.
13. Close the browser window.

Results: After this exercise, you have bound the citiesList list on the doctors.aspx page so that the list displays only
unique city names from the doctors database.

Module 09-Accomplishing Complex Data Access Tasks página 197


Exercise 2 - Get Doctor Specialties
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. What is the purpose of the GetUniqueCities stored procedure that you call in Exercise
1?
To enable the citiesList list on the doctors.aspx page to display a unique list of
the available cities.
2. What method can you use to fill a SqlDataReader object from a SqlCommand object?
ExecuteReader
3. What steps are required to call the getDrSpecialty stored procedure by using LINQ to
SQL?
a. Create a new instance of the DoctorsDataContext class.
b. Call the getDrSpecialty method of the doctorsContext object and set the
DataSource property of the specialtiesListBox control to the result of the
method. Pass the drID variable as an argument to the getDrSpecialty
method.
c. Set the relevant properties of the specialtiesListBox control and call the
DataBind method of the control.

Student Book Content


Exercise 2: Get Doctor Specialties
In this exercise, you will display a doctor's specialties in a list. When the user selects a doctor in the
doctorsGridViewcontrol, your code will call the getDrSpecialtystored procedure and display the results in the
specialtiesListBox control.
The main tasks for this exercise are as follows:
1. Call the getDrSpecialtystored procedure.
2. Bind the specialtiesListBox control to the specialtiesSqlDataReader object and make the list visible.

Task 1: Call the getDrSpecialty stored procedure


1. In the doctors.aspx page, create a SelectedIndexChanged event procedure for the doctorsGridView
control.
2. In the SelectedIndexChanged event procedure, call the CreateDateSet procedure to initialize the
connection string for the database.
3. Create a string variable named drID to hold the value of the dr_id column for the row that was selected by the
user.
4. Read the value of the dr_id field and store it in the drID variable by using the Cells collection of the
SelectedRowof the doctorsGridView.
Your code should resemble the following example.
[Visual C#]
CreateDataSet();
string drID;
drID = doctorsGridView.SelectedRow.Cells[1].Text;

Module 09-Accomplishing Complex Data Access Tasks página 198


[Visual Basic]
CreateDataSet()
Dim drID As String
drID = doctorsGridView.SelectedRow.Cells.Item(1).Text

5. Create a new SqlCommand object named specialtiesSqlCommand that uses the doctorsConnection
object to call the getDrSpecialtystored procedure.
6. Set the specialtiesSqlCommand command type to a stored procedure.

Module 09-Accomplishing Complex Data Access Tasks página 199


Exercise 3 - Get Doctor Specialties by Using LINQ to SQL
Saturday, September 06, 2008
12:30 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• You must access a database. Why must you use stored procedures instead of accessing the
database directly?
Direct access and manipulation of data can be a very inefficient use of resources and can
create security risks. One way to improve the efficiency and security of database access is
to create stored procedures on the database server and then call these stored procedures
from your Web Form.
• What types of data can you query with LINQ?
DataSet, in-memory data (arrays and lists), data in relational databases, and data stored in
XML documents.

Tools
Point out the location from which each key tool can be installed. Let students review the function and
usage of each tool on their own. Remind students that they can use this as a master list to help them
gather all the tools required to facilitate their application support work.

Student Book Content

11. Create a new SqlDataReader object named specialtiesSqlDataReader.


12. Open the doctorsConnection SqlConnection object.
13. Fill the specialtiesSqlDataReader object from the specialtiesSqlCommand object by calling the
ExecuteReader method of the specialtiesSqlCommand object.
Your code should resemble the following example.
[Visual C#]
SqlDataReader specialtiesSqlDataReader;
doctorsConnection.Open();
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader();

[Visual Basic]
Dim specialtiesSqlDataReader As SqlDataReader
doctorsConnection.Open()
specialtiesSqlDataReader = specialtiesSqlCommand.ExecuteReader()

Task 2: Bind the specialtiesListBox control to the specialtiesSqlDataReader object and make the list visible
1. In the SelectedIndexChanged event procedure, set the properties for the specialtiesListBox control as

Module 09-Accomplishing Complex Data Access Tasks página 200


1. In the SelectedIndexChanged event procedure, set the properties for the specialtiesListBox control as
shown in the following table.
Property Value
DataSource specialtiesSqlDataReader
DataTextField "Specialty"

2. Call the DataBind method of the list.


Your code should resemble the following example.
[Visual C#]
specialtiesListBox.DataSource = specialtiesSqlDataReader;
specialtiesListBox.DataTextField = "Specialty";
specialtiesListBox.DataBind();

Module 09-Accomplishing Complex Data Access Tasks página 201


Overview of XML Architecture in ASP.NET
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Overview of XML Architecture in ASP.NET
Microsoft ASP.NET provides various types of classes and objects that you can use to access and synchronize XML
data. These classes and objects represent low-level XML processing components that integrate XML into ASP.NET
Web applications.
This lesson explains what an XML document consists of. It also describes XML core technologies. Finally, it explains
the classes and objects that you use to read and write XML data.

Module 10-Reading and Writing XML Data página 202


What Is XML
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


This topic explains the content in all of the parts of an XML document. It then explains well-formed
and valid XML. There are examples provided to the students to help them understand the difference
between well-formed XML and XML that is not well-formed.
Point the students to these examples in the student notes and have a small quiz in the class. Ask
students to identify the errors in the example of XML that is not well-formed. Emphasize that XML is
case sensitive.

Student Book Content


What Is XML?
Key Points
XML is a universal format that you can use to describe and exchange structured documents and data on the
Internet.
Companies confront many problems when they organize data because they must fulfill requirements for the
content and structure of their data.
XML fulfills all of these requirements; this assists companies in the organization of data.
Question: How does XML enable you to transfer data across disparate systems?

Module 10-Reading and Writing XML Data página 203


XML Core Technologies
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


Emphasize the key features of each technology. Ensure students understand when to use each of
these technologies.
Point out the references to W3C.org; these references provide more detailed information about
recommendations and standards related to current and emerging XML technologies.

Student Book Content


XML Core Technologies
Key Points
XML has initiated other technological innovations and developments that work with XML to manipulate data.
These technologies enable you to define the structure of XML documents, transform XML data, reference elements
in XML documents, navigate and edit XML documents, and retrieve and interpret information from XML data
sources.
Question: How can you define an XML document as a schema?

Module 10-Reading and Writing XML Data página 204


XML and the DataSet Object
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
XML and the DataSet Object
XML and DataSet objects share a close connection with each other. DataSet objects are the basis for
disconnected storage and the manipulation of relational data. DataSet objects are also a container for one or more
data tables. XML is the standard format for data that is present in DataSet objects.
This lesson explains the relationship between XML and DataSet objects, and demonstrates how to create nested
XML data.

Module 10-Reading and Writing XML Data página 205


Why Use XML with DataSets
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


Students must understand the convenience of implementing XML with DataSets.

Student Book Content


Why Use XML with DataSets?
Key Points
A DataSet is a relational view of data that can be represented in XML. You can use DataSets to serialize XML data,
for example, to read and write XML data.
XML and XML schemas provide a convenient format that you can use to transfer the contents of a DataSet to and
from remote clients.
You can use different XML objects from the System.XML namespace to synchronize and transform data that is
represented by DataSets.
Question: How can you define the schema of a DataSet?

Module 10-Reading and Writing XML Data página 206


Overview of XML and DataSets
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


Ensure that you explain the picture on this slide. The students must understand this overview clearly
before they can understand the rest of the module.
Point out that the DataSet object is contained in the System.Data namespace and that
XmlDataDocument and XslTransform are from the System.Xml namespace.

Student Book Content


Overview of XML and DataSets
Key Points
The Microsoft .NET Framework uses the XML format to store and transmit all types of data.
DataSets can store and transmit data in XML format.
Question: How can you read an XML document or stream it into a DataSet?
CD Content

Module 10-Reading and Writing XML Data página 207


The XML-Based Methods of the DataSet Object
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


The XML schema is not included in this topic because the ReadXML method can handle well-formed
XML.

Student Book Content


The XML-Based Methods of the DataSet Object
Key Points
You can create the contents of a DataSet from an XML stream or document.
The .NET Framework provides great flexibility for loading XML data and creating the schema or relational structure
of a DataSet.
Question: How can you obtain the XML representation of the DataSet as a string?
CD Content
You can create the contents of a DataSet from an XML stream or document. In addition, the .NET Framework
provides great flexibility for loading XML data and creating the schema or relational structure of a DataSet.

Module 10-Reading and Writing XML Data página 208


Creating Nested XML Data
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


Ensure that the students understand that they must set the Nested property of the DataRelation to
true.

Student Book Content


Creating Nested XML Data
Key Points
You can implement the relationship between tables in a DataSet by using a DataRelation.
In the hierarchical representation of data that XML provides, the parent-child relationships are represented by
parent elements that contain nested child elements.
You can set the Nested property of a DataRelation to true to create nested XML data.
Question: What is the default value of the Nested property of a DataRelation?

Module 10-Reading and Writing XML Data página 209


Demonstration - Creating Nested XML
Saturday, September 06, 2008
12:32 AM

Instructor Notes (PPT Text)


Use this demonstration for further explanation about how to create nested XML. The lab contains an If
Time Permits exercise about nested data; therefore, students may not have a chance to practice this
activity for themselves. Mention that you can optionally write the schema to the output. Also mention
that the default option is to IgnoreSchema and not write the schema to the output.
In this demonstration, students will see how to create a nested XML document.
Note: This demonstration contains a complete solution.
• To run the demonstration
1. In Microsoft® Visual Studio® 2008, create a Web site.
2. Add the SaveNestedXML.aspx page from the E:\Labfiles\Democode\CS or
E:\Labfiles\Democode\VB folder to the Web site.
3. View the code-behind page, explain the code, and then point out the following:
• In the CreateDataSet function, a DataSet with two DataTables is created.
• In the MakeDataRelation function, a DataRelation is created between the two tables, setting
the Nested property to True or False depending on the argument to the function.
• In the saveXMLButton_Click event procedure, the DataRelation is created with Nested set to
false, and then the DataSet is written to an XML file.
• In the saveNestedXMLButton_Clic k event procedure, the DataRelation is created with the
Nested property set to true, and then the DataSet is written to an XML file.
4. Build and browse the SaveNestedXML.aspx page.
5. In the browser, click Save as XML.
This is the XML data that was created from the DataSet with the Nested property set to false.
Point out that the doctors elements are all listed, followed by the drspecialties elements.
6. In the browser, click the back button, and then click Save as Nested XML.
This is the XML data that was created from the DataSet with the Nested property set to True.
Point out that the doctors elements are nested inside the related drspecialties elements.
7. Close the browser.

Student Book Content


Demonstration: Creating Nested XML
Question: How can you tell that the XML data is nested?
CD Content
In this demonstration, the instructor will show you how to create a nested XML document.

Module 10-Reading and Writing XML Data página 210


Managing XML Data
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Managing XML Data
The XmlDataDocument class enables you to store, retrieve, and manipulate XML documents by using a relational
DataSet. XmlDataDocument provides a relational view of the loaded XML document and has a close affiliation
with the DataSet class. Any changes that are made to one object are reflected in the other. Similarly, to transform
the contents of a source XML document into another format such as XML or HTML, you can use XSL
transformations.
This lesson explains how to synchronize a DataSet with an XmlDataDocument. It also describes how to use
XmlDataDocument. Finally, it explains how to transform XML data by using the XslCompiledTransform
object.

Module 10-Reading and Writing XML Data página 211


Overview of Synchronizing a DataSet with an XmlDataDocument
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Students must understand that the ADO.NET DataSet is relational and the XML classes are
hierarchical. However, you can access both synchronously by using DataSet and XMLDataDocume nt
respectively.

Student Book Content


Overview of Synchronizing a DataSet with an XmlDataDocument
Key Points
The DataSet object enables real-time, synchronous access to the relational representations of data.
The XmlDataDocument object enables real-time, synchronous access to the hierarchical representations of data.
When a DataSet is synchronized with an XmlDataDocument, both objects work with the same single set of data.
Question: When you make a change to a DataSet, what happens to the XmlDataDocument if both objects are
synchronized?

Module 10-Reading and Writing XML Data página 212


Synchronizing a DataSet with an XmlDataDocument
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Ensure that the students understand how to use the XmlDataDocument object.

Student Book Content


Synchronizing a DataSet with an XmlDataDocument
Key Points
You can synchronize a DataSet with an XmlDataDocument by storing XML data in an XmlDataDocument or a
DataSet in an XmlDataDocument.
Question: How can you store a DataSet in an XmlDataDocument?
CD Content
There are two ways to synchronize a DataSet with an XmlDataDocument. You can:
Store XML data in an XmlDataDocument.
Store a DataSet in an XmlDataDocument.

Module 10-Reading and Writing XML Data página 213


Manipulating an XmlDataDocument
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Ensure that the students understand how to manipulate an XmlDataDocument instance.
Note: If you choose to demonstrate the content in this topic, ensure that you declare an XmlElement
and not an XElement; XElement is used by LINQ. Also ensure that you use the innerText property
to retrieve the data; do not use ToString.

Student Book Content


Manipulating an XmlDataDocument
Key Points
The XmlDocument implements the Document Object Model (DOM) in XML.
The XmlDataDocument unifies ADO.NET and XML by representing relational data from a DataSet and
synchronizing that data with the XML document model.
Question: How can you extract individual rows as XML from a DataSet?
CD Content

Module 10-Reading and Writing XML Data página 214


Transforming XML Data by Using XSLT
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Ensure that students understand the use of the XslCompiledTrans form object. Explain that
XslTransform has been depreciated.
The transform method can also contain an argument of type XsltArgumentList, where an object can
be passed to the transform method. It is more efficient to pass an object here than to rely on scripts
in the Xsl file by using tags, and it is easier to manage smaller Xsl files.

Student Book Content


Transforming XML Data by Using XSLT
Key Points
You can use XSL transformations to transform the content of a source XML document into another document that is
different in format or structure.
In the .NET Framework, the XslCompiledTransformclass is the XSLT processor that transforms one XML
document into another.
You can use the Transform method of an XslCompiledTransform object to transform the data.
Question: Why does the Transformmethod have several overloads?

Module 10-Reading and Writing XML Data página 215


Demonstration - Transforming Data by Using XSLT
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Use this demonstration to illustrate the topics from this lesson as you discuss them. In this
demonstration, students will see how to transform data by using the XslCompiledTransform object.
Note: This demonstration contains a complete solution.
• To run the demonstration
1. In Visual Studio 2008, create a Web site or continue with the Web site from the
previous demonstration.
2. Add the Transform.aspx and doctors_style.xsl files from the
E:\Labfiles\Democode\CS or E:\Labfiles\Democode\VB folder to the Web site.
3. Open the Transform.aspx page in Design view.
The two GridView controls display the two DataTables in the DataSet.
4. View the code-behind page.
5. Point out the code in the transformButton_Clic k event procedure and explain the
code:
• The DataSet is created by calling CreateDataSet to create the DataSet; the
DataSet then calls MakeDataRe lation to create the DataRelation. However, for
the XmlDataDocument mapping to work, you must first add the doctors parent
table to the DataSet, before the drspecialties table.
• An XmlDataDocument is created from the DataSet.
• An XslCompiledTransform object is created and loaded by using the
doctors_style.xsl style sheet.
• The Transform method of the XslCompiledTransform object is called to apply the
style sheet to the XmlDocument. Point out to the students that the Transform
method can only output to an XmlReader, a TextReader, or to XmlWriter
objects.
6. View the page in a browser.
7. In the browser, click Transform Data, and then click the View Transform Output
hyperlink. This is the HTML page that was created from the DataSet data.
8. Close the browser.
9. Open the doctors_style.xsl style sheet to show how it works.

Student Book Content


Demonstration: Transforming Data by Using XSLT
Question: What does the Transformmethod of the XslCompiledTransformobject perform?
CD Content
In this demonstration, the instructor will show you how to transform data by using the XslCompiledTransform
object.

Module 10-Reading and Writing XML Data página 216


Accessing XML Data by Using the XML Web Server Control
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 4
Accessing XML Data by Using the XML Web Server Control
Information in an XML file is raw; the file contains only the data and no indication about how to format or display
this information. To display XML data in a Web Forms page, you must provide formatting and display information.
This lesson explains how to display, load, and save XML data.

Module 10-Reading and Writing XML Data página 217


What Is the XML Web Server Control
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Explain that students can use the Xml Web server control to write an XML document or the results of
an XSLT transformation to a Web page. Also explain that the XML output appears in the Web page at
the location of the control.
Note: Use a simple demonstration as you discuss the topics in this lesson.
If time permits, add a new Web Form that contains the Xml control, save the nested DataSet from
the previous demonstration, and then set the DocumentSource and TransformSource attributes.
Point out to the students that this achieves the same results as the previous demonstration by using
the Xml control instead.

Student Book Content


What Is the XML Web Server Control?
Key Points
You can use the XSL Transformation language to specify the tags that display XML data and provide instructions
about how the data from an XML file fits into these tags.
The output is a new file with the XML information formatted according to the transformation file.
You can use the XML Web server control to write an XML document or the results of an XSL Transformation to a
Web page.
Question: Where does the XML output of the control appear on the Web page?

Module 10-Reading and Writing XML Data página 218


Loading and Saving XML Data
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Ensure that the students understand the two methods that you can use to add an XML Web server
control to a Web Form. Similarly, ensure that the students understand the three different methods
that they can use to load XML data into a Microsoft ASP .NET Web application.

Student Book Content


Loading and Saving XML Data
Key Points
You can create an Xml control by adding it from the Toolbox to a Web page or programmatically in code.
You can load XML data into a Web application by providing a path to an external XML document, loading an XML
document as an object, and including the XML content inline.
Question: How can you transform the XML document before its contents are written to the output stream?

Module 10-Reading and Writing XML Data página 219


Lab - Reading XML Data
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


In this lab, students will read, transform, and display XML data.
Exercise 1
In this exercise, students read an XML file and store it in a DataSet.
Exercise 2
In this exercise, students apply transformation to an XML file.
Exercise 3
In this exercise, students create nested XML data from a SQL Server database.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Reading XML Data
Exercise 1: Reading a List of Mutual Funds from an XML File
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.
One benefit that is offered by Coho Winery is the retirement benefit. When users apply for the retirement benefit,
they can view the prospectuses of several mutual funds that are offered by Coho Winery. In this lab, you will read
mutual fund data from an XML file and then read, transform, and display a prospectus for a specified mutual fund.
In this exercise, you will read a list of mutual funds from the mutual_funds.xml file and store them in a DataSet.
You will then display the DataSet in a GridViewcontrol.

Module 10-Reading and Writing XML Data página 220


Exercise 1 - Reading a List of Mutual Funds from an XML File
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


One benefit that is offered by Coho Winery is the retirement benefit. When users apply for the
retirement benefit, they can view the prospectuses of several mutual funds that are offered by Coho
Winery.

Student Book Content

[Visual Basic]
'myDataRelation2.Nested = True
16. On the File menu, click Save All.
17. In Solution Explorer, right-click nestedData.aspx, and then click View in Browser.
18. In the browser, analyze the XML data.

Tip: You may have to refresh the browser after the page loads to see the changes to the XML data.
In a change from the previous response, at the beginning of the file, all of the doctors are now listed sequentially,
then the specialties and drspecialtiesare nested (for every specialty, all of the drspecialtieschildren are
listed).

Note: You cannot use the two nested relationships at the same time because the same DataTable
(drspecialties) cannot be a child in two nested relations. For this reason, you have commented out the
nested property setting from the previous exercise.
19. Close the browser.

Results:After this exercise, you have experimented with nested XML data from a SQL Server database.

Module 10-Reading and Writing XML Data página 221


Exercise 2 - Reading, Transforming, and Displaying XML
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. Where is the information for the mutual funds stored?
The information for the mutual funds is stored in an XML file named mutual_funds.xml.
2. When you read data into the DataSet, why did you use the Server.MapPath method?
You can use the Server.MapPath method to return the physical file path that corresponds to
the specified virtual path that is on the Web server for the current request.
3. What is the prospectus_style.xsl file and what is its purpose?
The prospectus_style.xsl file is an XML style sheet that uses XSLT to display XML data. The
title of the prospectus page is Prospectus and the text General Description is in the color
brown.
4. Why did you use an Xml control?
The Xml control displays the content of the lgcap.xml prospectus as a continuous,
unformatted string of text.
5. How did you apply a transformation to the Xml control?
By Setting the TransformSource property of the Xml control to the correct .xsl file.

Student Book Content


The XmlDataDocument class enables structured data to be stored, retrieved, and manipulated by
using a relational DataSet object. You can also synchronize a DataSet object with an
XmlDataDocument object.

Module 10-Reading and Writing XML Data página 222


Exercise 3 - (If Time Permits) - Nested Data
Saturday, September 06, 2008
12:33 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• You want to reference elements in an XML document. What XML technology must you use?
XPath
• You want to retrieve and interpret XML information. What XML technology must you use?
XQuery
• You want to navigate and edit XML information. What XML technology must you use?
DOM

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.

Student Book Content

Module 10-Reading and Writing XML Data página 223


Introduction to ASP.NET AJAX
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Introduction to ASP.NET AJAX
ASP.NET AJAX uses client-script libraries and server components to implement Ajax features. This lesson introduces
the Ajax and ASP.NET AJAX technologies and describes the architecture of ASP.NET AJAX.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 224


What Is Asynchronous JavaScript and XML
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Briefly explain the background and history of Ajax. Do not spend too much time on this topic.
Mention that one of the key features of Ajax is the XMLHttpRequest object. This object enables
browsers to make asynchronous data requests without the requirement to reload pages.

Student Book Content


What Is Asynchronous JavaScript and XML?
Key Points
Ajax uses several technologies, including:
XMLHttpRequest object.
HTML, XHTML, and cascading style sheets.
XML and other data transfer formats such as JavaScript Object Notation (JSON).
Document Object Model (DOM).

CD Content
Ajax is a group of technologies that is designed to increase the responsiveness of Web pages. By using Ajax, you can
refresh parts of a page instead of the whole Web page when you must exchange data with the Web server. This
increases the speed and interactivity of the page.
Ajax works across multiple platforms and browsers and uses open standards such as JavaScript. The asynchronous
nature of Ajax means that your application can retrieve data from the server as a background task that does not
affect the current Web page display.
Ajax Technologies
AJAX makes use of several technologies, including the following:
XMLHttpRequest object, which you use to exchange data with the Web server asynchronously. This object
enables browsers to request data without a page reload and is one of the key features of Ajax.
HTML, XHTML, and cascading style sheets, which provide the markup and style information for a Web page.
XML and other data transfer formats such as JavaScript Object Notation (JSON), which you can use to transfer data
between a Web server and a client.
Document Object Model (DOM), which you use with a scripting language such as JavaScript to provide client-side
interaction with the data in a Web page.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 225


What Is ASP.NET AJAX
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


The key point is that the goal of ASP.NET AJAX is to improve the efficiency of Web applications and
therefore to enhance the user experience for users of an application.
Mention that ASP.NET AJAX consists of client-script libraries and server components. However, do not
go into detail because the next topic explains the architecture further.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111443

Student Book Content

Module 11-Creating a Microsoft ASP.NET AJAX Application página 226


Architecture of ASP.NET AJAX
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Explain that the client-script libraries and server components integrate to produce the development
environment.
References:
http://asp.net/ajax/documentation/live/overv ie w/de fault.aspx

Student Book Content


Architecture of ASP.NET AJAX
Key Points
The client architecture of ASP.NET AJAX is made up of client-script libraries that are composed of JavaScript files.
The server architecture of ASP.NET AJAX consists of ASP.NET Web server controls and components that you use to
create the User Interface (UI) and implement the functionality of an application.
CD Content
ASP.NET AJAX consists of client-script libraries and server components.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 227


Creating an ASP.NET AJAX Application by Using the ASP.NET AJAX
Extensions
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Creating an ASP.NET AJAX Application by Using the ASP.NET AJAX
Extensions
The ASP.NET 2.0 AJAX Extensions provide server-side controls and functionality that you use to implement ASP.NET
AJAX features in your Web applications. This lesson describes the Extensions and explains how to use several of the
available ASP.NET AJAX server controls.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 228


What Are the ASP.NET AJAX Extensions
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Emphasize that the ASP.NET AJAX Extensions is included with Microsoft® Visual Studio® 2008 but can
also be downloaded for Visual Studio 2005.

Student Book Content


What Are the ASP.NET AJAX Extensions?
Key Points
The ASP.NET 2.0 AJAX Extensions is included with Microsoft Visual Studio ® 2008 and is available as a separate
download for Visual Studio 2005.
The features of the ASP.NET AJAX Extensions are implemented in several namespaces, including
System.Web.Configuration and System.Web.UI.
CD Content
The ASP.NET AJAX Extensions contains the core server-side components of ASP.NET AJAX. Version 2.0 of the
Extensions is included with the .NET Framework 3.5 and Microsoft Visual Studio ® 2008. The Extensions extends
the server-side control framework of ASP.NET and provide several new controls that you use to implement Ajax
features in your Web applications. These controls appear in their own tab in the Visual Studio Toolbox.

Note: The ASP.NET 2.0 AJAX Extensions is available as a separate download for Visual Studio 2005.
Server Namespaces
The features of the ASP.NET AJAX Extensions are implemented in several namespaces. The following table describes
these namespaces.
Namespace Description
System.Web.Config Contains classes that enable you to configure the ASP.NET 2.0 AJAX Extensions
uration programmatically.
System.Web.Handle Contains HTTP Handler classes that process HTTP requests to a Web server.
rs
System.Web.Script. Contains classes that provide JSON serialization and deserialization for managed types. It
Serialization also provides extensibility features to customize serialization behavior.
System.Web.Script. Provides attributes to customize Web service support for the ASP.NET 2.0 AJAX
Services Extensions.
System.Web.UI Provides classes and interfaces that enable client-server communication and rich UIs
through the use of the ASP.NET 2.0 AJAX Extensions.
System.Web.UI.Desi Contains classes that you can use to extend design-time support for ASP.NET 2.0 AJAX
gn Extensions.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 229


ASP.NET AJAX Server Controls
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Give a brief overview of each of the most commonly used server controls. Explain that the
UpdatePanel and ScriptManager controls will be demonstrated in the next topic.

Student Book Content

Module 11-Creating a Microsoft ASP.NET AJAX Application página 230


Demonstration - Implementing the UpdatePanel Control
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


In this demonstration, students will see a simple example of how to use the UpdatePanel control to
provide partial-page rendering.
When you begin the demonstration, explain that the ScriptManager control is required because it
provides the support for partial-page rendering.
Also explain that partial-page rendering is a useful feature because it removes the requirement for the
whole page to be refreshed as the result of a postback.
Note: If you have time, extend the demonstration to include an example of how to use the
UpdateProgress control.
To run the demonstration
1. Create a new ASP.NET Web site.
2. Open the default.aspx page in Design view.
3. Add a ScriptManager and UpdatePanel to the page.
4. In the UpdatePanel, add a Button control to the form.
5. Set the Text property of the button to the value Inside Panel.
6. On the form, outside the UpdatePanel, add a second Button control.
7. Set the Text property of the second button to the value Outside Panel.
8. Save the default.aspx page, and then view the page in the browser.
9. Click each button in turn and verify that the button inside the UpdatePanel does not
cause a page postback but the button outside of the panel does cause a postback.
10.Close the browser window.
Explain to the students that you can also configure a control outside the UpdatePanel as a trigger
that refreshes just the UpdatePanel.
11.In the default.aspx page, delete the Inside Panel button.
12.On the form, inside the UpdatePanel, add a Label control.
13.Double-click Outside Panel to create a Click event handler.
14.Add code to the Click event handler to set the Text of the Label to the string
Current Time: followed by the current date and time.
[Visual C#]
Label1.Text = "Current Time: " + DateTime.Now.ToString();
[Visual Basic]
Label1.Text = "Current Time: " & DateTime.Now.ToString()
15.Switch to Design view of the default.aspx page.
16.View the properties of the UpdatePanel control.
17.On the Triggers property click the ellipsis.
18.In the UpdatePanelTrigger Collection Editor dialog box, click Add.
19.Set the ControlID property of the new trigger to Button2, and then click OK.
20.Save the Web site, and then view the default.aspx page in the browser.
21.Click Outside Panel several times and verify that the content in the label changes but
a page refresh does not occur.
22.Close the browser window.

Student Book Content


Demonstration: Implementing the UpdatePanel Control
In this demonstration, you will see how to implement an UpdatePanel control in a Web application.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 231


Managing Partial-Page Updates
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Mention that you do not create an instance of the PageRequestManager directly; it is available
automatically when you enble partial-page rendering.
Briefly explain the available events and step through the example code provided.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111444

Student Book Content


Managing Partial-Page Updates
Key Points
When you implement partial-page rendering on a Web page, an instance of the PageRequestManager class
becomes available to the page.
You use JavaScript in your Web page to handle the events raised by the PageRequestManager class. Get a
reference to the current instance of the PageRequestManager class by calling the getInstance method and
then create a function to handle the required event.
Question: What are some scenarios when you may want to handle the events of the PageRequestManager
class?
CD Content

Module 11-Creating a Microsoft ASP.NET AJAX Application página 232


Converting an ASP.NET Application to ASP.NET AJAX
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Emphasize that when you create a Web site by using Visual Studio 2008, it is already an ASP.NET
AJAX application.
Explain that the web.config file requires several new elements if you want to convert an application to
use ASP.NET AJAX.
Reference:
http://go.microsoft.com/fwlink/?LinkId=110717

Student Book Content

Implementing a PageRequestManager Event


You use JavaScript in your Web page to handle the events raised by the PageRequestManager class.
The following code example demonstrates how to get a reference to the current instance of the
PageRequestManager class by calling the getInstance method. The example also specifies a function to use to
handle the beginRequest event of the class.
<script type="text/javascript" language="javascript">

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest
(ReqHandler);

function ReqHandler(sender, args)


{
...
}
</script>

Module 11-Creating a Microsoft ASP.NET AJAX Application página 233


Extending an Application by Using the ASP.NET AJAX Control Toolkit
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Extending an Application by Using the ASP.NET AJAX Control Toolkit
The AJAX Control Toolkit provides more than 30 different controls and extenders that you can use to enhance your
Web applications. This lesson describes how to download, install, and use the Toolkit.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 234


Overview of the ASP.NET AJAX Control Toolkit
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Give a brief overview of the ASP.NET AJAX Control Toolkit and explain the components that it
provides.
Mention there are over 30 controls and extenders available and that the Toolkit has recently been
updated to target the official release of the Microsoft .NET Framework 3.5 and Visual Studio 2008.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111445
http://go.microsoft.com/fwlink/?LinkId=111446

Student Book Content


Overview of the ASP.NET AJAX Control Toolkit
Key Points
The Toolkit contains several folders of content, including the following:
AjaxControlToolkit folder. This folder contains source code for the controls that the Toolkit provides.
SampleWebsite folder. This folder contains demonstrations of the controls.
ToolkitTests folder. This folder contains automated tests for all controls.
AjaxControlExtender folder. This folder contains an installer file for templates to create new extender controls.

Question: What advantages does the AJAX Control Toolkit provide?


CD Content
The ASP.NET AJAX Control Toolkit is a shared-source project between the ASP.NET AJAX community and Microsoft.
The Toolkit is built on the ASP.NET AJAX Extensions and contains a collection of Web-client components that you
can use to enhance your Web applications. You can also use the infrastructure of the Toolkit to write reusable and
extensible ASP.NET AJAX extenders and controls.

Note: There is a difference between extenders and controls. Extenders add to an existing control but do not
change the core functionality of the control. Controls provide new functionality, typically by wrapping an
existing control.
AJAX Control Toolkit Content
You download the AJAX Control Toolkit in the form of a zip file. The Toolkit contains several folders of content,
including the following:
AjaxControlToolkit folder. This folder contains the source code for the set of sample ASP.NET AJAX controls that the
Toolkit provides.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 235


Accessing the ASP.NET AJAX Control Toolkit
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Briefly explain the steps required to download and install the Toolkit.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111447
http://go.microsoft.com/fwlink/?LinkId=111448

Student Book Content


Accessing the ASP.NET AJAX Control Toolkit
Key Points
You can download the Control Toolkit from the following location:
http://go.microsoft.com/fwlink/?LinkId=110718
The most recent version of the Toolkit targets the official release of the Microsoft .NET Framework 3.5 and Visual
Studio 2008.
CD Content
Before you can use the AJAX Control Toolkit, you must download it. You can then add the Toolkit controls to the
Toolbox in Visual Studio 2008 and install the provided templates.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 236


Demonstration - Implementing an ASP.NET AJAX Extender Control
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how to create a sample Web application that uses several
features and controls of the Control Toolkit.
Mention to the students that the techniques used here to extend the button will be used in the lab to
extend a textbox with a calendar.
Note: This demonstration requires the AjaxControlToolkit.dll file that targets the official release
of .NET Framework 3.5 and Visual Studio 2008. If the virtual machine does not contain the
AjaxControlToolkit.dll file, download it from the www.codeplex.com Web site and copy it to the E:
\Democode\ folder in the virtual machine. If you have time, extend the demonstration to show how to
install the the AJAX Control Toolkit templates. Use the steps in the topic Accessing the ASP.NET AJAX
Control Toolkit to perform the demonstration.
To run the demonstration:
1. Create a new ASP.NET Web site.
2. In the Toolbox, create a tab named AJAX Control Toolkit.
3. Add the items from the file E:\Democode\AjaxControlToolkit.dll to the AJAX Control
Toolkit tab.
4. Show the new Toolbox items.
5. Open the default.aspx Web form in Design view.
6. On the form, add a Label and Button control to the form.
7. Create a Click event handler for the button.
8. In the event handler, add code to set the Text property of the label to the string
Button click occurred.
9. View the default.aspx page in the browser, and then click the button on the page.
Verify that the label text changes, and then close the browser window.
10.In the Toolbox, on the AJAX Extensions tab, drag a ScriptManager and drop it at
the top of the form.
11.In the Toolbox, on the AJAX Control Toolkit tab, drag a ConfirmButtonExte nder
and drop it onto Button1 on the form.
12.In the Properties window, set the ConfirmText property of the
ConfirmButtonExtender control to Continue?.
13.View the default.aspx page in the browser.
14.Click the button and verify that the confirmation dialog box appears.

Student Book Content


Demonstration: Implementing an ASP.NET AJAX Extender Control
In this demonstration, you will see how to implement a ConfirmButtonExtender control in an ASP.NET Web
application.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 237


Lab - Creating a Microsoft ASP.NET AJAX Application
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


In this lab, students will create an ASP.NET AJAX application.
Note: Exercise 2 requires the AjaxControlToolkit.dll file that targets the official release of .NET
Framework 3.5 and Visual Studio 2008. Download this file from the www.codeplex.com Web site and
distribute the file to the students. Ensure the students copy the file to the E:\Labfiles\Starter\ folder in
the virtual machine.
Exercise 1
In this exercise, students implement partial-page rendering with the UpdatePanel control.
Exercise 2
In this exercise, students install the ASP.NET AJAX Control Toolkit and then use the
CalendarExtender control to enhance the nameDate user control.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Creating a Microsoft ASP.NET AJAX Application
Exercise 1 Implementing Partial-Page Rendering by Using the UpdatePanel
Control
Scenario
The doctors.aspx page on the Coho Winery Web site enables users to view the list of specialties of a selected
doctor. In this lab, you will use the ASP.NET AJAX Extensions to implement partial-page rendering when the user
selects a different doctor or moves to a new page in the list of doctors. You will also install the controls from the
AJAX Control Toolkit and use the CalendarExtender control to enhance the nameDate user control.
In this exercise, you will implement partial-page rendering.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 238


Exercise 1 - Implementing Partial-Page Rendering by Using the
UpdatePanel Control
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


The doctors.aspx page on the Coho Winery Web site enables users to view the list of specialties of a
selected doctor. In this lab, students will use the ASP.NET AJAX Extensions to implement partial-page
rendering when the user selects a different doctor or moves to a new page in the list of doctors.
Students will also install the controls from the AJAX Control Toolkit and use the CalendarExtender
control to enhance the nameDate user control.

Student Book Content


Tools
Tool Use for Where to find it
AJAX Control Built on the ASP.NET AJAX Extensions and contains a collection of Web-client Available for
Toolkit components that you can use to enhance your Web applications. download.

CD Content
Review Questions
1. What is the design goal of the AJAX group of technologies?
To increase the responsiveness of Web pages.
2. What features does the ScriptManager control provide?
Management of script resources and features such as partial-page rendering, localization, and
globalization.
3. How can you use the AJAX Control Toolkit to enhance your applications?
The Toolkit provides many prebuilt controls that you can add to your applications quickly. You can
also use the templates provided by the Toolkit to build your own controls and extenders.

Module 11-Creating a Microsoft ASP.NET AJAX Application página 239


Exercise 2 - Installing and Implementing the AJAX Control Toolkit
Saturday, September 06, 2008
12:34 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. What controls must you add to a page to implement partial-page rendering?
ScriptManager and UpdatePanel
2. What steps are required before you can use a control from the AJAX Control Toolkit?
Download the Toolkit and add the controls from the Toolkit to a new tab in
the Toolbox. You can then add a control from the Toolbox to your Web page.

Student Book Content

Module 11-Creating a Microsoft ASP.NET AJAX Application página 240


Overview of Microsoft Silverlight
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


It is important to stress that Microsoft® Silverlight™ in still in the early stages of development.

Student Book Content


Lesson 1
Overview of Microsoft Silverlight
Silverlight is a cross-browser, cross-platform plug-in that you can use to deliver media experiences and rich
interactive applications on the Internet by using XAML. Silverlight also offers powerful functionality that improve
the productivity of both designers and developers.
This lesson introduces the features of Silverlight, explains the component architecture of Silverlight, and describes
the main tools that you can use to develop Silverlight content.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 241


Key Features of Microsoft Silverlight
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Mention to the students that Silverlight is based on Windows Presentation Foundation (WPF) and
Extensible Application Markup Language (XAML) technology. Emphasize that familiarity with Silverlight
will be an advantage when they move on to the rest of WPF.
Mention that the extensions to Microsoft JScript® provide control over browser UIs.
Mention that media experiences include high quality video and audio.
References:
http://go.microsoft.com/fwlink/?LinkId=111449
http://go.microsoft.com/fwlink/?LinkId=111450

Student Book Content


Key Features of Microsoft Silverlight
Key Points
Silverlight offers numerous features that you can use to create truly immersive experiences.
You can publish media content that operates on different platforms and create video applications that have similar
functionality to DVD players.
Silverlight includes Windows Presentation Foundation (WPF) technology that enables you to create rich client
features that are not available with HTML alone. You can use XAML to create WPF elements.
Silverlight extends JScript to provide powerful control over browser user interfaces (UIs).

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 242


Tools for Designing and Developing Silverlight Applications
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Differentiate between the Microsoft Expression® applications, which you can use to design Silverlight
applications, and Microsoft Visual Studio®, which you can use to develop an application.
Note: Many of the Silverlight tools are in early release versions or previews.

Student Book Content


Tools for Designing and Developing Silverlight Applications
Key Points
You can use the professional design tools in Microsoft Expression Studio to create rich content and the
development environment of Visual Studio to generate interactive functionality.
By using these tools, designers and developers can collaborate more effectively to deliver Web solutions.
Question: What are the similarities and differences between Expression Studio and Visual Studio?

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 243


Architecture of Silverlight
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


The core presentation components for Silverlight are as follows:
• Input
• UI Rendering
• Media
• Controls
• DRM
• XAML
The .NET Framework components for for Silverlight are as follows:
• WPF
• Data
• Base Class Library
• Networking
• CLR
• DLR
Mention that the .NET Framework for Silverlight is a subset of the full .NET Framework.
Explain that full support for the .NET Framework languages became available with the Alpha 1.1
Refresh release. Briefly mention that the installer and updater control helps first-time users to install
the application and provides for subsequent low-impact, automatic updates. However, do not spend
too much time on this component.
Reference:
http://go.microsoft.com/fwlink/?LinkId=110698

Student Book Content


Architecture of Silverlight
Key Points
Silverlight is a browser plug-in for constructing graphics, animations, and timelines by using XAML. You can then
attach the XAML to JScript code to implement functionality.
Silverlight contains the codecs to play VC-1, Windows Media Video (WMV), Windows Media Audio (WMA), and MP3
multimedia content.
A Silverlight application first invokes the Silverlight control from the HTML page, which then loads a XAML file. The
plug-in provides mechanisms at run time to change the XAML content, retrieve objects by using JScript, and stream
multimedia content.
Question: How does AJAX relate to Silverlight?

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 244


XAML and Microsoft Silverlight
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Check if the students are familiar with XAML. Explain that you use XAML to design the UI of a WPF or
Silverlight application. Briefly cover the code samples provided but do not go into too much detail at
this stage.
Explain that the separation of the UI and the logic that drives it enables designers and developers to
work on a project independently. This is emphasized in the lab at the end of the module, where
students first design the UI and then add code to implement interactivity. It is also possible to identify
event procedures by using XAML. However, this technique produces a tighter coupling between UI and
code, which detracts from the initial point.
XAML files are simple because they are just plain text files. However, XAML files can become quite
extensive, hence the requirement for a more visual design tool like those available in Expression
Studio.
Note: XAML is a core component of the Windows Presentation Foundation that you can use to design
the UI of rich Microsoft Windows®-based applications. Therefore, this very powerful markup language
is applied to Silverlight to take full advantage of enhanced UI features. XAML is not tied to either just
WPF or just Silverlight.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111451

Student Book Content


XAML and Microsoft Silverlight
Key Points
XAML is a declarative markup language that you can use to define all aspects of the UI for your Silverlight
application. XAML is much richer than HTML; it enables you to incorporate vector images, video, and much more.
A XAML file typically contains a Canvas root element that you can use to contain objects and tags to define
objects.
Question: How does Silverlight relate to XAML?

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 245


Creating Silverlight-Based Applications with Visual Studio 2008
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Creating Silverlight-Based Applications with Visual Studio 2008
Visual Studio 2008 enables you to create Silverlight 1.1 applications by using managed code and JScript. When you
create a Silverlight application, Visual Studio creates a solution with a framework for the application.
This lesson explains how to create a Silverlight application in Visual Studio and describes the content files in a
Silverlight application. It also explains how to create XAML objects and handle events in the code-behind file.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 246


Creating a Silverlight Application
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Use a demonstration to illustrate the key points of this topic. Create a new Silverlight application by
using Visual Studio 2008. Use the Add New Item dialog box to add a new Silverlight page to the
application.
Explain that there are certain installation requirements before you can use Silverlight in Visual Studio.
First install the Silverlight runtime (Alpha 1.1 Refresh in this instance), and then install the templates
(Microsoft Silverlight Tools Alpha for Visual Studio 2008 Beta 2 in this instance).
Reference:
http://go.microsoft.com/fwlink/?LinkId=111452

Student Book Content


Creating a Silverlight Application
Key Points
Visual Studio 2008 provides templates that you can use to create Silverlight applications and class libraries.
Question: What types of files can you add to a Silverlight application?
CD Content
Visual Studio 2008 provides templates that you can use to create Silverlight applications. You can use the Silverlight
Project template to create a Silverlight application or the Silverlight Class Library template to create a Silverlight
class library.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 247


Content of a Silverlight Application
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Use the Silverlight application that you created in the previous topic to discuss the initial files that
Silverlight creates.
Show all files in Solution Explorer so that the students can see the associated JScript file. Avoid
showing the content of the .js files at this point.
When you add more XAML pages to your application, you must modify the TestPage.html.js file
accordingly. Open this file and show the source Page.xaml parameter in the createObjEx method that
is used to instantiate the page.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111452

Student Book Content


Content of a Silverlight Application
Key Points
When you create a Silverlight project in Visual Studio, the solution contains:
A Page.xaml file for the UI with an associated source code file in Microsoft Visual C# ® or Microsoft Visual Basic ®.
A Silverlight.js file to create a Silverlight control in the Web page.
A TestPage.html default file with an associated JScript file.
Question: What do the JScript and XAML files contain?

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 248


Implementing XAML Objects
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Mention that XAML objects define a hierarchical tree structure with a root object.
Step through the samples provided in the CD content and ensure that the students understand the UI
that is generated.
If you use a demonstration during this topic, you can paste the example XAML code into the
demonstration application.
Emphasize the reference to "Silverlight Overviews and How-to Topics" because it is a very good
reference for extra information on the fundamentals of how to implement Silverlight objects.
Point out to the students that text must be in the form . Also mention empty elements, for example, .
References:
http://go.microsoft.com/fwlink/?LinkId=111453
http://go.microsoft.com/fwlink/?LinkId=111454
http://go.microsoft.com/fwlink/?LinkId=111455

Student Book Content


Implementing XAML Objects
Key Points
You can define numerous objects in XAML. Each XAML object has a specific use.
XAML tags are similar to XML and HTML tags.
You can use a Canvas object as a drawing surface to contain other objects or embedded drawing surfaces.
Question: Can you nest Canvas objects to create a hierarchy of XAML objects?
CD Content
There are numerous object types that you can define in XAML and each has a specific use. To declare an object, you
use the following syntax.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 249


Handling Events
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


If students are familiar with WPF then this process will not be new to them.
Explain that the code for the handler is compiled into a library and the library is then referenced from
the XAML file.
Mention that it is also possible to write event handlers by using JScript or a dynamic language that
targets managed code such as IronPython or managed JScript. However, mention that these options
are beyond the scope of this course.
Note: It is recommended that you open the Microsoft MSDN® page references that are provided in
the CD content and have a quick look some of the details. In particular, point out the use of the
x:Name attribute, which is critically important when you want to dynamically wire up event
procedures by using code.
Reference:
http://go.microsoft.com/fwlink/?LinkId=111456

Student Book Content

You can also create a Polygon object and a Polyline object. These are most similar to the Path object, and in
many situations you can use the Path object to create the same shape.
There is no restriction to the number of objects that you can include in your Silverlight application. However, some
projects can become very complex, so it is often useful to utilize the Canvas object to group other objects. This
enables you to organize your application efficiently.

Additional Reading: For more information about XAML objects, see "Silverlight Overviews and How-to Topics"
at http://go.microsoft.com/fwlink/?LinkId=110700
Object properties are important because they define the actual appearance, position, and characteristics of an
object. You can declare an object (such as a Rectangle), but the object will not render until you define some
properties.
Each object type has a set of specific properties that you can use for that object, many of which are optional. You
can apply some general properties to many or all objects, particularly properties that you use to position objects.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 250


Demonstration - Displaying Video Files in a Silverlight Application
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how use a Silverlight application to display a video file. Explain
that the actual file extension of a media file is irrelevant; the MediaElement object determines the
encoding and plays the media file with the appropriate codec. You can extend this demonstration by
creating video player controls for the Web page.
The aim of the first three tasks of this demonstration is to show students how easy it is to incorporate
video capability into a Silverlight application by using Visual Studio 2008. The aim of the last task is to
show students the rich media capabilities of a Silverlight application. Point this out to the students.
Note: Do not watch the entire video when you view the transformations. Mention that the
MediaElement object supports many formats, for example, .MP3. For more information about the
formats that the MediaElement object supports, see "Supported Media Formats and Protocols in
Silverlight" at http://msdn2.microsoft.com/en-us/library/bb412386.aspx
• Add a video file to a Silverlight application
1. Open Visual Studio 2008.
2. Create a project that uses the Silverlight Project template.
3. In Solution Explorer, right-click the Silverlight project, point to Add, and then click
Existing Item.
4. In the Add Existing Item dialog box, browse to the E:\Democode folder, select the
video file, and then click Add.
• Add a MediaElement object to the Canvas
5. In Solution Explorer, double-click the Page.xaml file.
6. Add the following single line of code to the Canvas to create a MediaElement object
that displays the video.wmv video file.

...
Background="White">

• Watch the video in a browser


7. Build the project.
8. View TestPage.html in a browser to watch the video.
• Perform transformations on the video
9. Use Windows Explorer to browse to the E:\Democode folder.
10. Open the VideoTransform.txt file and copy its contents to the clipboard.
11. In Visual Studio, in the Page.xaml file, replace the line of code that you added in the
second task with the code from the VideoTransform.txt file.
12. Examine the code that you added. Note the following points:
• Setting the ScaleY property of ScaleTransform to -1 flips (reflects) the video.
• Applying the OpacityMask on the MediaElement object creates the trailing transparency.
5. Build the project.
6. View TestPage.html in a browser to watch a skewed and reflected version of the video.

Student Book Content

Additional Reading: For more information about the x:Name attribute, see the "x:Name Attribute" at

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 251


Additional Reading: For more information about the x:Name attribute, see the "x:Name Attribute" at
http://go.microsoft.com/fwlink/?LinkId=110701

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 252


Lab - Delivering Dynamic Content with Microsoft Silverlight
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


In this lab, students will create a Microsoft Silverlight-based application that delivers dynamic content.
Exercise 1
In this exercise, students create a new Microsoft Silverlight application.
Exercise 2
In this exercise, students add dynamic content to a Microsoft Silverlight application.
Important: Note the following points:
• In Exercise 2, the students remove the code that they added in Exercise 1. Point out that it
is typically best practice to comment out code before you delete it because it can save you
time and frustration later on.
• Ensure students know how to access the Lab Answer Key so that they can successfully
complete the required steps in the lab.
• If time permits, you can demonstrate debugging in a Silverlight application by using the
solution files.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Delivering Dynamic Content with Microsoft Silverlight
Exercise 1: Creating a Microsoft Silverlight-Based Application
Scenario
Coho Winery wants to upgrade its existing Benefits Web site to use richer and more dynamic content. In this lab,
you will investigate the features of Microsoft Silverlight and create a simple version of the Benefits Web site. The
new Web site will contain a default page that loads an associated picture and dynamic text that explains each
benefit when the user selects the benefit.
In this exercise, you will create a Silverlight project in Visual Studio and add some XAML objects to Page.xaml to
create a simple banner for the Web site.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 253


Exercise 1 - Creating a Microsoft Silverlight-Based Application
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Coho Winery wants to upgrade its existing Benefits Web site to use richer and more dynamic content.
In this lab, students will investigate the features of Microsoft Silverlight and create a simple version of
the Benefits Web site. The new Web site will contain a default page that loads an associated picture
and dynamic text explaining each benefit when the user selects the benefit name.

Student Book Content

Task 2: Add images to the project and create variables


1. Add the images from the E:\Labfiles\Starter folder to the Benefits project.
There are five images in this folder. Four images display a different benefit type and the other image displays a
banner for the Web site.
2. Open Page.xaml, and then in the Page class, create the following objects:
A string named activeButton that contains the name of the currently selected button.
An integer named currentPage that contains the current page number. Set this integer to 1.
An integer named nextPage that contains the current page number. Set this integer to 0.

Task 3: Create an event handler for when the user clicks a button
1. In the Page class, create an event handler named OnMouseDown that accepts the event type
MouseEventArgs.
2. If the user clicked a button other than the active button, perform the following:
a) Call the Begin method of the buttonName_Click storyboard where the name of the button is the button
selected.
b) Call the Begin method of the buttonName_Leave storyboard where the name of the button is the previously
selected button.
c) Check the name of the selected button, and then set the nextPage integer accordingly, for example, 1 for
Button1 and 2 for Button2.
d) Set the activeButton string to the name of the selected button.
e) Call the Begin method of the Page_Out storyboard.
To find the name of the clicked button, you can use (sender as Canvas).Name (Visual C#) or TryCast(sender,
Canvas).Name (Visual Basic).
You can use the FindName method to concatenate the name of the selected button with the string _Click or
_Leave to call the Begin method of the storyboards. For example, the following code inside an event procedure
calls the Begin method of the clicked button.
[Visual C#]

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 254


Exercise 2 - Adding Dynamic Content to a Microsoft Silverlight
Application
Saturday, September 06, 2008
12:35 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. How can you create a square XAML object?
Use the Rectangle object.
2. How can you create a circular XAML object?
Use the Ellipse object.
3. How can you easily add event procedures for many controls?
You can use the FindName method in conjunction with a loop to concatenate the name of a
control with a string such as "_Click". This can create strings such as Button1_Click and
Button2_Click that you can use to add event procedures.
4. Where is the code for the object animation?
The element contains elements for object animation. There are elements for page fading
and when the pointer enters, leaves, or clicks one of the four buttons.

Student Book Content

Task 8: Build and view the page


1. On the Build menu, click Build Solution.
2. In Solution Explorer, right-click TestPage.html, and then click View in Browser.
3. In the browser, click the buttons in the left pane to display a related picture and text.
4. Close Internet Explorer.

Results:After this exercise, you have added XAML code and images to display the front page of the Web site and
event handling code to display an associated picture and text when the user selects a benefit.

Module 12-Delivering Dynamic Content with Microsoft Silverlight página 255


Overview of XML Web Services
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Overview of XML Web Services
One of the challenges that you may encounter when you create feature-rich Web sites is application integration.
You often have to combine several applications into a single, easy-to-use solution. The problem with this is that the
applications that you want to combine may be on a variety of platforms, and each platform may run a different
operating system. The applications may also use several different programming languages.
XML Web services provide a simple, flexible, standards-based model that you can use to connect applications
together over the Internet. XML Web services enable you to take advantage of the existing Internet infrastructure
and link applications regardless of which platforms, programming languages, or object models that they use.
This lesson describes XML Web services and explains the process that you use to call an XML Web service from a
Web Form.

Module 13-Consuming and Creating XML Web Services página 256


What Is an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Ensure that the students understand that XML Web services do not have a user interface (UI) but do
use Internet-based protocols to communicate with other applications.

Student Book Content


What Is an XML Web Service?
Key Points
XML Web services do not have a user interface (UI).
XML Web services communicate by using standard Web protocols and data formats such as HTTP, XML, and Simple
Object Access Protocol (SOAP).
The XML Web services model assumes a stateless service architecture; such architectures are generally more
scalable than statefull architectures.

CD Content
XML Web services are similar to components because they represent black-box functionality that developers can
use to add features to a Web Form, Microsoft Windows ® Form, or even another XML Web service without
worrying about how the supporting service is implemented.
Application-to-Application Communication Across the Internet
XML Web services interact directly with other applications over the Internet. As a result, XML Web services do not
have user interfaces (UIs); instead, XML Web services provide standard defined interfaces called contracts that
describe the services that they provide.
An XML Web service can be used internally by a single application, or it can be used externally by many applications
that access it by using the Internet.
Language Independence
You can write a connection to an XML Web service in any Microsoft .NET Framework-based language. Because of
this flexibility, you do not have to learn a new language every time you want to use an XML Web service.
Protocol Independence

Module 13-Consuming and Creating XML Web Services página 257


Why Use XML Web Services
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


The advantages of the XML Web service model may not be obvious to developers who do not have a
lot of experience in connecting applications. Ensure that the students understand the benefits of XML
Web services.

Student Book Content


Why Use XML Web Services?
Key Points
XML Web services enable you to share programming logic and capabilities with many other applications.
Visual Studio 2008 provides applications that make XML Web services extremely easy to develop and to consume.
Question: What are some functions for XML Web services in your own applications?
CD Content

Module 13-Consuming and Creating XML Web Services página 258


Finding an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on this slide. The steps that you use to create a proxy to
consume an XML Web service will be explained in a later lesson.
Alternative delivery. If you have access to the Internet, find an XML Web service at the following Web
sites: http://uddi.xml.org/

Student Book Content

Example of an XML Web Service


A hypothetical travel Web site offers several features that are based on XML Web services. In this scenario, the user
enters a destination city name, and the Web Form uses the city name as a parameter in calls to several XML Web
services. From the user's perspective, this is a sophisticated travel Web site. From a developer's perspective, the
Web site is a graphical interface that combines several XML Web services from unrelated companies.
This Web site provides advantages to both the travel agency and the various XML Web service providers:
Advantages for the travel agency:
The applications that the travel agency has access to are not limited by the travel agency developers' programming
skills, availability, or subject expertise.
The travel agency does not bear the high maintenance costs of keeping data such as weather reports or exchange
rates up-to-date.
The XML Web services use the Internet, so the travel agency does not have to create or maintain dedicated
connections to offer the service.
The XML Web services are language, protocol, and platform independent, so the travel agency developers do not
have to learn how the XML Web service was built and deployed.

Advantages for the XML Web service providers:


The XML Web service provider may be able to charge the Web site for the use of the service.
A bank can access the customer base of multiple travel agencies, by offering an application such as an exchange rate
calculator as an XML Web service.

Module 13-Consuming and Creating XML Web Services página 259


Multimedia - XML Web Service Execution Model
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


This multimedia explains how Web services interact with browsers and other Web Forms.
Mention that to enable remote HTTP access to the XML Web service, the following elements must be
included in the web.config file for the XML Web service:

Student Book Content


Multimedia: XML Web Service Execution Model
Key Points
In this animation, you will see how XML Web services interact with browsers and other Web Forms.
CD Content
In this animation, you will see how XML Web services interact with browsers and other Web Forms.
XML Web Service Model
A Web service consists of methods that are stored in an .asmx file.

Module 13-Consuming and Creating XML Web Services página 260


Calling an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Calling an XML Web Service
You can access an XML Web service directly from a browser by using HTTP, which is a process called direct access.
Direct access enables you to view the methods, properties, and output of an XML Web service. You can also call an
XML Web service from a Web Form programmatically. To accomplish this, you must create a proxy to handle the
call.
This lesson describes how to access an XML Web service directly from a browser. It also explains how to create a
Web reference proxy for an XML Web service method and call the Web method from a Web Form.

Module 13-Consuming and Creating XML Web Services página 261


Calling an XML Web Service by Using HTTP
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Use a demonstration to illustrate the points as you discuss them.
Open the demonstration Web service and show students how to browse to the XML Web service URL.
You can also append ?WSDL to the URL or click the service description link to show the WSDL
document.

Student Book Content


Calling an XML Web Service by Using HTTP
Key Points
When you access an XML Web service directly with a browser, you first access the HTML description page.
The description page provides information about what an XML Web service does, the available Web methods that it
contains, the Web method parameters, and the Web service responses.
You can click a Web method to view the available parameters for that Web method and to test the method.
Question: Why may you want to access a Web service by using HTTP?

Module 13-Consuming and Creating XML Web Services página 262


What Is a Proxy
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Explain that the Add Web Reference option creates the proxy automatically.
Emphasize that the use of the proxy is the programmatic way to access Web services. Also emphasize
that this is the technique typically used to access the functionality of the Web service in a production
application.
Mention that when you invoke the Web service methods by using the proxy, the SOAP call is managed
internally and automatically.

Student Book Content


What Is a Proxy?
Key Points
To call an XML Web service, you create a Web reference to the XML Web service. The members in the generated
proxy include:
WebMethodName for synchronous communication.
BeginWebMethodName to start asynchronous communication.
EndWebMethodName to finish asynchronous communication.
WebMethodNameAsync to implement the event-driven asynchronous programming model.

Question: What is the purpose of the proxy class that is created when you create a Web reference to an XML Web
service?
CD Content
To call an XML Web service from a Web Form, you must create a Web reference to the XML Web service in your
Web application project. The Web reference creates the proxy object that you use to communicate with the XML
Web service by using SOAP.
What Is a Proxy?
A proxy class is code that looks exactly like the class it represents; however, it does not contain any of the
application logic. Instead, the proxy class contains marshaling and transport logic. A proxy object enables a client to
access an XML Web service as if it is a local component. The proxy must be on the computer that has the Web
application.
Visual Studio 2008 automatically creates a proxy when you add a Web reference to an XML Web service.
Interaction with SOAP
Proxies and XML Web services interact by using SOAP, which is an XML protocol that you use to exchange
structured and typed information.

Module 13-Consuming and Creating XML Web Services página 263


Steps for Calling an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


This slide builds directly on the Finding an XML Web Service slide from the first lesson, "Overview of
XML Web Services." To remind the students why they may want to build a proxy, you can return to
the Finding an XML Web Service slide.
Emphasize to the students that they must create a reference to the Web service URL so that Microsoft
Visual Studio can automatically create the proxy class.

Student Book Content

Proxy Creation from the WSDL Document


Visual Studio 2008 automatically creates a proxy when you create a new Web reference. The WSDL file on the XML
Web service server identifies the Web methods and parameters that are available in the XML Web service.
Proxy Members
When you create a proxy by using Visual Studio 2008, several methods and properties that support programmatic
access to the XML Web service are available. The members that are available to a proxy include:
Members built into the proxy. The infrastructure for making synchornous and asynchronous calls from a Web Form
to an XML Web service is built into the proxy class that is created automatically by Visual Studio 2008 when you add
a Web reference. Methods called WebMethodName, BeginWebMethodName, EndWebMethodName, and
WebMethodNameAsync are automatically created in the proxy for every Web method of the XML Web service:
WebMethodName. The WebMethodName method of the proxy class is used to communicate with the Web
service method synchronously.
BeginWebMethodName. The Begin method is used to start asynchronous communication with an XML Web
service method WebMethodName.
EndWebMethodName. The End method is used to finish an asynchronous communication with an XML Web
service method WebMethodName and retrieve the completed reply from the XML Web service method.
For example, creating a Web reference to the Stocks XML Web service creates a proxy with two additional
methods: BeginGetRating and EndGetRating.

Additional Reading: For more information about calling an XML Web service asynchronously, see
"Communicating With XML Web Services Asynchronously" at http://go.microsoft.com/fwlink/?LinkId=110703
WebMethodNameAsync. The Async method implements the event-driven asynchronous programming model,
which was introduced in ASP.NET 2.0.

Module 13-Consuming and Creating XML Web Services página 264


XML Web Service Error Handling
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Explain the possible error sources that students may encounter when they use a Web service.
Explain that it is important to use structured error handling to test for these types of errors.

Student Book Content


XML Web Service Error Handling
Key Points
The three major sources of error when you use an XML Web service are:
Unavailable service.
Long response delays.
Errors that are internal to the XML Web service.
Question: Discuss some occurrences that may cause an error when you access an XML Web service.
CD Content

Module 13-Consuming and Creating XML Web Services página 265


Demonstration - Testing the Availability of an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Use this demonstration to reinforce to students how important it is to handle errors when they access
Web services.
In this demonstration, students will see how to test if the XML Web service is available.
To run the demonstration
1. Open the WeatherSite.sln file from the E:\Democode\CS\WeatherSite or
E:\Democode\VB\WeatherSite folder. The WeatherService Web service also opens.
2. In the WeatherSite application, add a Web Reference named WeatherWebRef that
points to the WeatherService Web service.
3. In the WeatherSite application, examine the Default.aspx page. In the Web service,
examine the Service1 class.
4. View the default.aspx Web page in the browser, in the box on the page, type any city
name, and then click Get Forecast. Repeat this step several times and then close the
browser.
Add a try...catch to the Web service call
1. In the button event handler, modify the code to set a timeout of 10 seconds (10,000),
and then add code to add a Try...Catch statement around the call to the XML Web
service.
Your code should resemble the following example.
[Visual C#]
protected void Button1_Click(object sender, EventArgs e)
{
WeatherWebRef.Service1 getWeatherProxy =
new WeatherWebRef.Service1();
getWeatherProxy.Timeout = 10000;

try
{
Label2.Text = getWeatherProxy.WeatherByCity(TextBox1.Text);
}
catch (Exception err)
{
Label2.Text = err.Message;
}
}
[Visual Basic]
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Button1.Click

Dim getWeatherProxy As New WeatherWebRef.Service1


getWeatherProxy.Timeout = 10000

Try
Label2.Text = getWeatherProxy.WeatherByCity(TextBox1.Text)
Catch err As Exception
Label2.Text = err.Message
End Try
End Sub

Module 13-Consuming and Creating XML Web Services página 266


Student Book Content
Demonstration: Testing the Availability of an XML Web Service
In this demonstration, the instructor will show you how to test if the XML Web service is available.

Module 13-Consuming and Creating XML Web Services página 267


Creating an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Creating an XML Web Service
Visual Studio 2008 provides templates that make it easy for you to develop XML Web services. This lesson describes
how to use these templates to create an XML Web service.

Module 13-Consuming and Creating XML Web Services página 268


Steps to Create an XML Web Service
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)

Student Book Content


Steps to Create an XML Web Service
Key Points
When you create a new Web service application, Visual Studio 2008 automatically creates the required folders, files,
and the XML Web service page. Visual Studio 2008 also creates a default Hello World function on the XML Web
service page.
To test your Web service, right-click the XML Web service in Solution Explorer, and then click View in Browser.

CD Content
Visual Studio 2008 provides templates and a default XML Web service method to help you start to create XML Web
services.
To create an XML Web service in Visual Studio 2008
1. Open Visual Studio 2008, and create a new ASP.NET Web Service Application project or an ASP.NET Web Service
Web site.
Visual Studio 2008 automatically creates the required folders, files, and the XML Web service page. It is
recommended that you rename the project and the XML Web service to help you to identify and maintain the
project and files.

Note: If you create a Web Service Web site, the code file that supports the logic of the Web service is placed
in the App_Code folder. For a Web Service Application project, the code file is in the application root.
2. Declare the functions for the Web service.
Visual Studio 2008 creates a default Hello World function on the XML Web service page. You can use this function
or write your own. You can write almost any kind of function as an XML Web service method from a simple local
calculation to a complex database query.
Each function must contain the [WebMethod] (Microsoft Visual C# ®) or <WebMethod()> (Microsoft Visual
Basic ®) attribute.
3. Build the ASP.NET Web Service project.

Module 13-Consuming and Creating XML Web Services página 269


XML Web Service Code
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


If you have time, use a demonstration to illustrate how to create a Web service.

Student Book Content


XML Web Service Code
Key Points
Web services consist of two primary files. The .asmx file identifies the Web page as an XML Web service, and the
code file contains the XML Web service logic.

CD Content
When you create an XML Web service with Visual Studio 2008, two primary files are created that make up the XML
Web service: the .asmx file and the .asmx.cs or .asmx.vb file. The .asmx file identifies the Web page as an XML Web
service, and the .asmx.cs or .asmx.vb file contains the XML Web service logic.

Module 13-Consuming and Creating XML Web Services página 270


Lab - Consuming and Creating XML Web Services
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


The key point is that although the code that creates the XML Web service is constant, the XML Web
service can be a wrapper for almost any application on any platform.
Alternative delivery. Use a demonstration to illustrate the points in this topic.

Student Book Content

[Visual Basic]
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

' To allow this Web Service to be called from script, using ASP.NET
' AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding _
(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class Service1
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function

End Class

Code-behind pages have the following attributes:


Namespaces. XML Web services import several namespaces, including the System.Web.Services namespace.
This namespace contains the methods and properties that support XML Web services. All of the Web methods, data
types, and the Web service itself inherit the namespace.
Class. The Class attribute identifies the base class that supports this instance of an XML Web service.
The default XML Web service class is Service1.
XML Web service methods. You must flag each method that you want to expose from the XML Web service with a
custom [WebMethod] (Visual C#) or <WebMethod()> (Visual Basic) attribute. This attribute is required because
without it, the method is not exposed from the XML Web service.
Visual Studio 2008 creates a default Hello World Web method. You can edit the default function or add your own
functions.
The following example displays the code for the default Visual Studio 2008 XML Web service method.
[Visual C#]

Module 13-Consuming and Creating XML Web Services página 271


Exercise 1 - Creating the Dentist XML Web Service and the
GetAllDentists XML Web Service Method
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


In this lab, students will create and test an XML Web service.
Note: When you run the application, a warning message appears because the AjaxControlToolkit.dll
file is not present in the virtual machine. You can ignore this warning message or download the
version of the AjaxControlToolkit.dll file that targets the official release of .NET Framework 3.5 and
Visual Studio 2008 from the www.codeplex.com Web site. If you download the AjaxControlToolkit.dll
file, copy it to the virtual machine to remove the warning message. Mention this to the students.
Exercise 1
In this exercise, students create an XML Web service that contains a Web method that returns a
DataSet from a Microsoft SQL Server™ database.
Exercise 2
In this exercise, students create a Web method that returns a DataSet by using a stored procedure.
Exercise 3
In this exercise, students consume the GetAllDentists Web method.
Exercise 4
In this exercise, students consume the GetDentistsByPostalCode Web method.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

Results: After this exercise, you have consumed the GetDentistsByPostalCode XML Web Service method.

Module 13-Consuming and Creating XML Web Services página 272


Exercise 2 - Creating the GetDentistsByPostalCode XML Web
Service Method
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


In this lab, students will create an XML Web service that retrieves data from the dentists database.
The Web service will contain two Web methods: one that retrieves all of the dentists from the
dentists table and one that uses a stored procedure to retrieve the dentists for a specific postal code.
Students will then call the stored procedures from a Web Form.

Student Book Content


You set a timeout for the proxy and look for timeout exceptions when you call the Web methods of
the XML Web service.
5. What attribute do you add to methods that you want to be exposed to the Web from your XML Web service?
WebMethod is required. Without it, the function will not be exposed on the Web.

Module 13-Consuming and Creating XML Web Services página 273


Exercise 3 - Consuming the GetAllDentists XML Web Service
Method
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. When you test a Web service, where does the description page come from?
This page is automatically created by ASP.NET from the XML Web service
description.
2. What is the effect if you change the default namespace of a Web service?
The warning message no longer appears in the service description page.
3. What must you do in the Benefits Web site before you can consume the methods in the
DentalService Web service?
Add a Web reference to the Web service.

Student Book Content

Module 13-Consuming and Creating XML Web Services página 274


Exercise 4 - Consuming the GetDentistsByPostalCode XML Web
Service Method
Saturday, September 06, 2008
12:38 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Common Issues and Troubleshooting Tips
Point the students to possible troubleshooting tips for the issues presented in this section.
Real-World Issues and Scenarios
You can either discuss possible solutions for the scenarios at the end of the module or assign these
scenarios as homework for the students. If you assign the scenarios as homework, you should provide
some high-level hints that might help the students solve the problem stated in the scenarios. You can
also do a follow-up debriefing the following day on some of the scenarios that have been assigned as
homework to students.
You can create high-level hints for each scenario by using the following possible solutions for the
scenarios.
• You need to find existing XML Web services to add to your Web site. How can you do this?
Use one or more of a series of discovery services, as follows:
○ Universal Description, Discovery, and Integration (UDDI) Web site
○ Discovery file (DISCO) documents: .disco, .vsdisco
○ Web Services Description Language (WSDL) files
• How can you add information to a Web service?
When you create a Web service and add methods to it, you can add information to the
service in the form of attributes.

Student Book Content

Module 13-Consuming and Creating XML Web Services página 275


State Management
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
State Management
The connection that is established between a user (the client computer) and a Web server is called a session.
Sessions can span multiple Web pages and are tracked by using state management. State management is the
process by which you maintain the same information throughout multiple requests for the same or different Web
pages.
In this lesson, you will begin to understand in detail what state management is and why it is important to manage
state. This lesson explains server-side state management and client-side state management and describes the
Global.asax file.

Module 14-Managing State página 276


What Is State Management
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Ensure that the students understand that HTTP is a stateless protocol but Microsoft® ASP.NET
provides state management to enable you to store and retrieve user information.

Student Book Content


What Is State Management?
Key Points
ASP.NET provides state management that saves information on the server between page requests and postbacks;
this helps to maintain the continuity of user information (state) throughout a visit to a Web site.
If state is maintained between pages, you can reuse the information so that users do not have to reenter the same
information multiple times. This is particularly useful during the postback process when a user fills out a long or
complicated form.
Question: If you do not use state management, what happens to user details after they are provided by a user on an
initial logon page?

Module 14-Managing State página 277


Types of State Management
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


The focus of this module is application state, session state, and cookies. Mention that cookies have
security implications because information is stored in plain text.
Do not spend too much time on the ViewState property and query strings. Control state is similar to
view state but functionally independent of view state. Control state stores the data of a control (for
example, a page number) that must be available on postback to enable the control to function even
when view state is disabled.
State management is scalable Mention that because the Microsoft SQL Server™ database or state
server do not have to be on the same server as the Web application, it allows for a more scalable
approach to state management.

Student Book Content


However, you can use state management in your Web application to maintain state across multiple Web pages.
Therefore, when the user's personal information is sent to the server, the second page welcomes the user by his
name.
Types of State Management
Key Points
ASP.NET provides two types of state management:
Server-side state management options use server resources to store state information. These options provide
higher security than client-side state management.
Client-side state management does not use server resources to store state information and therefore offers fast
server performance. However, it can be unreliable and pose a security risk if you want to store sensitive
information.

Question: What are the differences between server-side and client-side state management?

Module 14-Managing State página 278


Server-Side State Management
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Ensure that students understand the difference between application and session state.
Mention that the SessionID for a page request appeared on the trace ouput page shown in Module 5,
"Tracing and Debugging."

Student Book Content


Server-Side State Management
Key Points
Application state is a global storage mechanism that is accessible from all of the pages in the Web application. It
enables you to store user information between server round trips and between pages.
Session state is similar to application state except that it is limited to the current browser session. If multiple users
access a Web application, each user has a different session state.
Question: How does ASP.NET provide application state and session state?

Module 14-Managing State página 279


Client-Side State Management
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Explain the key features of cookies. Also explain why they are not as useful as server side state
management.
Mention that persistent cookies have an expiration time.

Student Book Content


Client-Side State Management
Key Points
Most Web applications use cookies for client-side state management. A cookie contains page-specific information
that is stored either in a text file on the file system of the client computer or in-memory in the client-browser
session.
Cookies can expire when the browser session ends or they can exist indefinitely on the client computer. Cookies are
not as secure as server-side state management options.
Question: Why are cookies less secure than server-side state management options?
CD Content
Most Web applications use cookies for client-side state management.

Module 14-Managing State página 280


The Global.asax File
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Emphasize that this file is optional.
Mention that there are three categories of events that are supported by Global.asax:
• Events that are fired when a page is requested.
• Events that are fired when the requested page is sent.
• Conditional application events.
Mention a few of the events from each category.

Student Book Content


The Global.asax File
Key Points
The Global.asax file is an optional declarative file that you can use to handle events while your Web application is
running.
Every ASP.NET Web application supports one Global.asax file per Web application; the Global.asax file is stored in
the virtual root of the Web application.
Question: What are the types of events that the Global.asax file supports?
CD Content
The Global.asax file is a declarative file that you can use to handle events while your Web application is running.

Module 14-Managing State página 281


Application and Session Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)

Student Book Content

Module 14-Managing State página 282


Initializing Application and Session Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Mention that you initialize session and application variables in the Global.asax file, in the Start event
procedures of the Application and Session objects.

Student Book Content


Lesson 2
Application and Session Variables
You can use application and session variables to share information between the pages of an ASP.NET Web
application. This lesson explains how to initialize and use application and session variables. It also demonstrates
how to specify the duration for application and session variables and describes how application and session
variables impact scalable storage. Finally, it explains how to save application and session variables in a database.

Module 14-Managing State página 283


Accessing Application and Session Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Ask students why they must use Application.Loc k and Application.UnLoc k when they access
application and session variables.
Mention that when you increment application and session variables, you can use "+=" in Microsoft
Visual Basic® but not in Microsoft Visual C#®.
Emphasize that the read value from the application and session variables must be explicitly cast to the
correct data type. In Visual Basic, this is necessary when Option Strict is On.

Student Book Content


Accessing Application and Session Variables
Key Points
To set a session variable, you must provide a key that identifies the item that you want to store. You must also set a
value.
To set an application variable, you must prevent multiple users or applications from updating the data
simultaneously by using a simple set of locking methods.
To use a session or application variable in an ASP.NET page, you can read the value from the Session or
Application object.
Question: When you set application variables, why must you use the locking methods of the Application object?

Module 14-Managing State página 284


Application and Session Variable Duration
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Explain that a shorter session duration uses fewer resources on the Web server.

Student Book Content


Application and Session Variable Duration
Key Points
By default, a session times out when a user has not requested a page for more than 20 minutes. If the same user
requests a page after 20 minutes, that user is treated as a new user. You can modify the session duration in the
web.config file.
Question: What must you set in the web.config file to modify the session duration?
CD Content
HTTP is a stateless protocol. A Web server has no means of detecting when a user leaves a Web site. Instead, the
Web server detects that a certain period of time has passed without the user requesting a page. At that point, the
Web server removes all of the items in session state that are associated with that user.

Module 14-Managing State página 285


Scalable Storage of Application and Session Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Mention that it is also possible to create a custom session-state store provider if required.

Student Book Content


Scalable Storage of Application and Session Variables
Key Points
By default, session state is managed in-process so all of the information that is added to a session state is stored in
the same Web server that runs the ASP.NET Web application. However, this limits the scalability of your Web site.
You can store session state out-of-process by managing session state with a Microsoft SQL Server™ database or a
separate state server. To store session state out-of-process, you must modify the Web.config file to set the
sessionState element. The main advantage of out of process management is that is provides scalability for your
Web site.
Question: If you want to store session state out of process, what values must you set for the sessionState
element?

Module 14-Managing State página 286


Saving Application and Session Variables in a Database
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Explain that the Aspnet_regsql.exe tool creates a database named ASPState that contains stored
procedures that support SQLServer mode. The session data is stored in the TempDB database by
default. You can use the -sstype option to store the data in a specified database.
Demonstrate the Aspnet_regsql tool by typing the following command at a command prompt.
aspnet_regsql -ssadd -S LON-DEV\sqlexpress -E -sstype p

Student Book Content


Saving Application and Session Variables in a Database
Key Points
To save application and session variables in a SQL Server database or in a state server:
1. Configure the session state in the Web.config file of your Web server.
2. Configure the SQL Server database or the state server.

Question: What must you modify in the Web.config file to configure the session state?

Module 14-Managing State página 287


Cookies and Cookieless Sessions
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Cookies and Cookieless Sessions
Cookies are a means by which the Web application that runs on the Web server can cause a client to return
information to the Web server with each HTTP request. You can use the returned information to maintain state with
the client across multiple requests. Cookies are sent to the client as part of the Hypertext Transfer Protocol (HTTP)
header in a client request or are sent in a server response.
This lesson explains how to use cookies to store session data and how to retrieve that data from a cookie. It also
describes cookieless sessions and explains how to set up cookieless sessions.

Module 14-Managing State página 288


Storing Session Date by Using Cookies
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


This slide shows the code that creates a temporary (non-persistent) cookie. The line of code that is
added to the slide sets the expiration time to create a persistent cookie. The cookie contains
information about the domain.
Point out that the response is a write action and the request is a read action.
Mention that if you create a cookie that already exists, the old cookie is destroyed. This is how the
cookie crumbles.
Display the cookies folder on the file system to the students and examine the format of file which
contains the domain name.

Student Book Content


Storing Session Date by Using Cookies
Key Points
You can create cookies by using the Cookies collection of the Response and Request objects. The Cookies
property represents a collection of cookies and is an instance of the HttpCookieCollection class.
If you set the expiration time of a cookie, the cookie changes from a temporary cookie to a persistent cookie.
Persistent cookies are saved as text files to the hard disk.
Question: How do you set the expiration time of a cookie?

Module 14-Managing State página 289


Retrieving Information from a Cookie
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Step through the code and ensure that the students understand how to retrieve the key and value
pairs from the cookie.
If you attempt to read a cookie that does not exist (such as a cookie that has been deleted by a user),
you can potentially receive a null reference exception. It is always good practice to check for a null
value first.
For more information about the Color.FromName method, see "Color.FromName Method" at
http://msdn2.microsoft.com/en-us/library/system.draw ing.color.fromname.aspx
Also, point out that some data type conversion may be necessary when you read the values from a
cookie.

Student Book Content


Retrieving Information from a Cookie
Key Points
To retrieve information from a cookie, you read the cookie and retrieve the key/value pairs from the cookie.
A cookie is returned to the server by the client in an HTTP "Cookie:" header. Multiple cookies, separated by
semicolons, can appear in this header.
You can read an existing cookie by accessing the Cookies collection of the Request object.
CD Content
To retrieve information from a cookie, you read the cookie and retrieve the key/value pairs from the cookie.

Module 14-Managing State página 290


Cookieless Sessions
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Ensure that the students understand that cookieless sessions can be used only in limited
circumstances.
The process of including the SessionID in the URL is known as URL munging. This has several
implications because of the limitations URL characters and mobile devices.

Student Book Content


Cookieless Sessions
Key Points
Cookieless sessions enable you to take advantage of session state even with browsers that have cookie support
disabled. The SessionID that identifies the active session is included in the URL instead of a cookie.
Question: What are the limitations of cookieless sessions?
CD Content
Each active session is identified and tracked by using a SessionID. The SessionID is communicated across client-
server requests by using an HTTP cookie or by including it in the URL. By default, SessionID is stored in cookies.

Module 14-Managing State página 291


Setting Up Cookieless Sessions
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Mention that the sections in the web.config file are generally referred to in camelCase.

Student Book Content


Setting Up Cookieless Sessions
Key Points
To enable cookieless sessions, in the <sessionState> section of the Web.config file, set the cookieless attribute
to true.
CD Content
You enable cookieless sessions by modifying a single attribute in the Web.config file.
Setting up a Cookieless Session
In the Web.config file, in the <sessionState>section, set the cookieless attribute to the value true. You only
have to set this value to enable cookieless sessions. The following code example illustrates this.
<sessionState cookieless="true" />

Module 14-Managing State página 292


Lab - Storing Application and Session Data
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


In this lab, students will store application and session data.
Note: When you run the application, a warning message appears because the AjaxControlToolkit.dll
file is not present in the virtual machine. You can ignore this warning message or download the
version of the AjaxControlToolkit.dll file that targets the official release of .NET Framework 3.5 and
Visual Studio 2008 from the www.codeplex.com Web site. If you download the AjaxControlToolkit.dll
file, copy it to the virtual machine to remove the warning message. Mention this to the students.
Exercise 1
In this exercise, students create session and application variables and then use them to store and
retrieve information.
Exercise 2
In this exercise, students create, read to, and write from persistent cookies.
Exercise 3
In this exercise, students create a page counter by using an application variable.
Exercise 4
In this exercise, students store session variables in a Microsoft SQL Server database.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Storing Application and Session Data
Exercise 1: Implementing Session Variables
Scenario
Coho Winery offers several benefits to its employees. In the labs for this course, you will create a Web site that
enables employees to select and set up their chosen benefits.
In this lab, you will use session and application variables to enhance the experience for users when they browse the
Benefits Web site.
In the current Web site, users must enter redundant information on multiple pages. For example, users must supply
their name and birth date on both the medical page and the life insurance page. To simplify the user experience of
the Web site, you will use a cookie to store this information in session variables so that users must enter this
information only once.

Module 14-Managing State página 293


Exercise 1 - Implementing Session Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


In this lab, students will use session and application variables to enhance the experience for users
when they browse the Benefits Web site.
In the current Web application, users must enter redundant information on multiple pages. For
example, users must supply their name and birth date on both the medical page and the life insurance
page. To simplify the user experience of the Web site, students will use a cookie to store this
information in session variables so that users must enter this information only once.

Student Book Content

Task 4: Test the cookie


1. In Solution Explorer, right-click Default.aspx, and then click View in Browser.
2. In the browser, click the Life Insurance link.
3. Fill in the required information, select one or both of the term coverage options, and then click Save.
The browser returns you to the Default.aspx page; the page now contains the life insurance information.
4. In the browser, click the Medical link.
5. Select a doctor, and then click Save.
The browser returns you to the Default.aspx page; the page now contains the doctor information.
6. Close the browser.

Results:After this exercise, you have used cookies to store all of a user's benefits selections and when a user
returns to the Default.aspx page, the page lists the selected benefits for the user.

Module 14-Managing State página 294


Exercise 2 - Implementing Cookies
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. How do you set session variables?
The following syntax sets a session variable, where VariableName is the name of the
session variable and Value is the value of the session variable.
[Visual C#]
Session["VariableName"] = "Value";
[Visual Basic]
Session("VariableName") = "Value"
2. How can you check if a cookie exists?
To check if a cookie exists, first create a HttpCookie instance by calling Request.Cookies.
Pass the name of the cookie as a parameter to Request.Cookies. If the HttpCookie instance
is null, the cookie does not exist.
3. When you modify an application variable, why must you lock it?
If you do not lock an application variable, multiple clients can simultaneously attempt to
modify it.
4. How can you store the session variables in a SQL Server database?
In the web.config file, in the system.web element, create a sessionState child element. In
the sessionState element, set the Mode, sqlConnectionString, cookieless, and Timeout
attributes accordingly.

Student Book Content

CD Content
Review Questions
1. How do you set up a Web application to use cookieless sessions?
Create a <sessionState> section in the Web.config file and set the cookieless attribute to true.
<sessionState cookieless="true"/>
2. What are the three categories of events that are handled in the Global.asax file?
Events that are fired when a page is requested, events that are fired when the requested page is
sent, and conditional application events.
3. Why must you initialize application variables?
You must initialize application variables because they can produce a null reference exception.
4. Where can you initialize application variables?
It is advisable to create and initialize application variables in the Application_Start event of the
Global.asax file.
5. Can there be more than one Global.asax file for a single Web application?
No, but you can also have a Global.asax file if the application contains ASP pages.

Module 14-Managing State página 295


Exercise 3 - Implementing Application Variables
Saturday, September 06, 2008
12:40 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.
Tools
Point out the location from which each key tool can be installed. Let students review the function and
usage of each tool on their own. Remind students that they can use this as a master list to help them
gather all the tools required to facilitate their application support work.

Student Book Content

Module 14-Managing State página 296


Exercise 4 - Storing Session Variables in a Database
Saturday, September 06, 2008
12:40 AM

Student Book Content

Module 14-Managing State página 297


Implementing the Cache Object
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Implementing the Cache Object
One of most effective ways to increase the performance of an ASP.NET Web application is to use the ASP.NET
Cache object. The Cache object enables you to place items in server memory so that you can quickly retrieve
them.
This lesson describes how to set up the Cache object to optimize the response times for a Web application.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 298
What Is the Cache Object
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Check to see how familiar the students are with the Cache object. You may be able to skim through
this topic.
Ensure that the students understand the difference between the Cache object and page output
caching.
Mention that an object stored in the cache is just that, an object, and may require code to cast to the
appropriate data type on retrieval.

Student Book Content


What Is the Cache Object?
Key Points
The following process describes how the Cache object works:
1. A page requests an item that is stored in the Cache object.
2. ASP.NET checks the Cache object and uses the cached version if it is available.
If a cached version is not available, ASP.NET recreates the item, uses that item, and then stores that item in the
Cache object for future use.

Question: What are some possible uses for the Cache object in your own applications?
CD Content
An issue that you will encounter when you build high-performance Web applications is the requirement to avoid
duplication. A Cache object enables you to store items in memory the first time that they are requested and then
use the cached copy for later requests. By using the cached copy, you do not have to recreate information that
satisfied a previous request, particularly information that demands significant processor time on the server every
time that it is created.
In addition to caching individual items such as computational results in the Cache object, ASP.NET offers an output
cache that you can use to store Web pages and user controls. The Cache object and the output cache are distinct
objects with unique roles and properties.
Storing Information
ASP.NET provides a full-featured cache engine that you use to store and retrieve information. The Cache object
has no information about the content of the items it contains. The Cache object merely holds a reference to those
objects and provides a process to track their dependencies and set expiration policies.
The Cache object also provides a method to pass values between pages in the same Web application. The cache
methods implement automatic locking; therefore, it is safe for the application to access values concurrently from
more than one page.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 299
Advantages of the Cache Object
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Explain the advantages of the Cache object to the students.

Student Book Content

[Visual Basic]
Cache("mykey") = myValue

To retrieve an item from a Cache object, use the following code.


[Visual C#]
myValue = Cache["myKey"];

[Visual Basic]
myValue = Cache("myKey")

Additional Reading: For more information on caching, see "Caching Application Data",
http://go.microsoft.com/fwlink/?LinkId=110706

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 300
How to Use the Cache Object
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Explain to the students the two methods that you can use to write to the Cache object: implicit and
explicit.

Student Book Content


How to Use the Cache Object
Key Points
You can write an item into a Cache object implicitly or you can use the explicit Insert method with parameters. To
retrieve a value from the cache, you provide the correct key to hold the retrieved value and cast the object to the
correct data type.
CD Content
To use the Cache object, you use key-value pairs to store and retrieve items. The key is the Cache key string that
you use to reference the item. The value is the item that you want to cache.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 301
Removing Items from the Cache Object
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Explain that the Cache object automatically removes the least used items when memory becomes
scarce. Also explain that it is possible to influence how these items are removed.

Student Book Content


Removing Items from the Cache Object
Key Points
To influence how the Cache object saves and removes items, define time limits, dependencies, and priorities for
items, as shown in the following code example:
[Visual C#]
Cache.Insert("MyBook.CurrentBook", CurrentBook, new CacheDependency
(Server.MapPath("Books.xml")), DateTime.Now.AddMinutes(5),
TimeSpan.FromSeconds(30), CacheItemPriority.High, onRemove);

[Visual Basic]
Cache.Insert("MyBook.CurrentBook", CurrentBook, new CacheDependency _
(Server.MapPath("Books.xml")), DateTime.Now.AddMinutes(5), _
TimeSpan.FromSeconds(30), CacheItemPriority.High, onRemove)

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 302
ASP.NET Output Caching
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)

Student Book Content

[Visual Basic]
Cache.Insert("myKey", myValue, Nothing, _
Nothing, TimeSpan.FromSeconds(20))

Dependencies
There are times when you want to remove an object from the Cache object because a related item such as a file
has changed. ASP.NET enables you to define the validity of a cached item based on file dependencies or another
cached item. Dependencies based on external files and directories are referred to as file dependencies;
dependencies based on another cached item are referred to as key dependencies. If a dependency changes,
ASP.NET invalidates the cached item and removes it from the Cache object.
The following code example removes myValue from the Cache object when the myDoc.xml file changes.
[Visual C#]
Cache.Insert("myKey", myValue, new CacheDependency(Server.MapPath("myDoc.xml")));

[Visual Basic]
Cache.Insert("myKey", myValue, _
new CacheDependency(Server.MapPath("myDoc.xml")))

Cache Item Priority


When the Web server runs low on memory, the Cache object selectively removes items to free up system
memory. Items that you assign higher priority values to are less likely to be removed from the cache, whereas the
items to which you assign lower priority values are more likely to be removed.
The following code specifies that myValue has a high priority.
[Visual C#]
Cache.Insert("myKey", myValue, null, null, Cache.NoSlidingExpiration, CacheItemPriority.High);

[Visual Basic]

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 303
Multimedia - Output Caching
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


If necessary, discuss the multimedia after you have viewed it.

Student Book Content


Multimedia: Output Caching
In this animation, you will see how the page output cache affects server response times when an ASP.NET Web
Form is requested more than once.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 304
Output Cache Types
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Do not spend more than the allotted time on page caching and page fragment caching; these topics
will be explained in more depth later in this lesson.

Student Book Content


Output Cache Types
Key Points
Page output caching enables you to store entire Web Forms and user controls in server memory. You can cache
portions of a page by creating the section as a user control and then caching the user control with the page output
cache.
For a Web service, you can specify the number of seconds that the results for the XML Web service method will
remain in the output cache.
Question: How can your own applications benefit from page output caching?
CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 305
Implementing the Page Output Cache
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Ensure that the students understand that c aching provides a powerful way to improve the
performance of a Web application.

Student Book Content


Implementing the Page Output Cache
Key Points
You can implement the page output cache:
Declaratively by using the @ OutputCache directive.
Programmatically by using the SetCacheabilitymethod on the Cache property of the Response object.
In a configuration file by using the OutputCache and OutputCacheSettings elements.

CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 306
Implementing Control Caching
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Explain that control caching enables you to separate portions of a page that take valuable processor
time to create (such as database queries) from other parts of the page.

Student Book Content


Implementing Control Caching
Key Points
Control caching enables you to separate certain portions of a page from the rest of the page.
Items that are good candidates for control caching include headers, footers, and lists that are used by multiple
pages.
You can set the caching policies for a user control declaratively by using the @ OutputCache directive or
programmatically by using the PartialCachingAttribute class.
CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 307
Configuring an ASP.NET Web Application
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)

Student Book Content

[Visual Basic]
<PartialCaching(25)> _
Partial Class myControl
Inherits UserControl
...
End Class

Post-Cache Substitution
Post-cache substitution enables you to cache a Web page but enable sections of the page to remain dynamic. You
specify that areas of a page cannot be placed in the cache by using the Substitution or AdRotator controls.
These areas of the page are then created dynamically at each page request and combined with the cached page
output.

Additional Reading: For more information about post-cache substitution, see "Dynamically Updating Portions
of a Cached Page" at http://go.microsoft.com/fwlink/?LinkId=110710

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 308
Overview of Configuration Files
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


If time permits, you can open the Machine.config file and a web.config file and point out inherited and
overridden settings.
Mention that it is important that the config files contain well-formed XML because a malformed file
causes the Web site to crash.

Student Book Content


Overview of Configuration Files
Key Points
Configuration information for ASP.NET resources is contained in a collection of configuration files. Each
configuration file contains a nested hierarchy of XML elements with attributes that specify the configuration
settings.
Question: How many web.config files does your application use?
CD Content
Configuration information for ASP.NET resources is contained in a collection of configuration files. Each
configuration file contains a nested hierarchy of XML elements with attributes that specify the configuration
settings.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 309
Configuring a Web Server by Using Machine.config
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Mention that the Machine.config file stores the default settings for an entire computer.
Explain the advantages and disadvantages of storing configuration settings in the Machine.config file.

Student Book Content


Machine.config
Machine-level configuration settings are stored in the Machine.config file. There is only one Machine.config file on
each Web server. As a result, you can use the Machine.config file to store settings that apply to all of the ASP.NET
Web applications that reside on that Web server.
Web.config
Application and directory-level settings are stored in web.config files. Each Web application typically has at least
one web.config file. Virtual directories can have their own web.config files that contain settings that are specific to
that directory. If a web application does not have a web.config file in the application root folder, it inherits the
settings in the web.config file in the config folder of the installed framework on the server. This file in turn inherits
settings from the Machine.config file.
.config file Attributes
Because the tags in Machine.config and web.config files must be well-formed XML, the elements and attributes are
case sensitive. Tag names and attribute names are camelCased, which means that the first character of a tag name
is lowercase and the first letter of any subsequent concatenated words is uppercase. All configuration information
in a .config file resides between the <configuration> and </configuration> root XML tags.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 310
Configuring an Application by Using Web.config
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Ensure that the students are familiar with the purpose of web.config files.

Student Book Content


Configuring an Application by Using Web.config
Key Points
You use the web.config file to share information and settings between Web pages. A single web.config file is
typically located in the root folder of the Web application. You can place additional web.config files in the folder of
the virtual directory to which they belong.
CD Content
In ASP.NET, you can share information and settings between Web pages by storing Web application settings in a
central location called the web.config file. You can also store local information and settings in virtual directories by
creating additional local web.config files.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 311
Configuration Inheritance
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Emphasize that each level of configuration file overrides the previous level.

Student Book Content

Note: For more information about security in the web.config file, see Module 16, "Securing a Microsoft
ASP.NET Web Application."•

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 312
Demonstration - Configuration Inheritance
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Use this demonstration to illustrate the previous topic as you discuss it.
To run the demonstration
1. Open the ConfigInheritance Web site from the E:\Democode\CS or E:\Democode\VB
folder.
2. In Microsoft® Visual Studio® 2008, in the main folder, show the code for the
web.config file and Default.aspx.
3. Point out the value that is stored in the Web.config file.
4. In the SubFolder folder, show the code for the web.config file and
GetConfigSubFolder.aspx.
5. Point out that the value that is stored in the web.config file is different.
6. View the Default.aspx page in the browser, and then highlight the value that was
retrieved from the web.config file.
7. In the browser, click Next to open the GetConfigSubFolder.aspx page in the SubFolder
folder, and then emphasize that the value is different here.
8. Close the browser window
9. In the SubFolder folder, rename the web.config file to oldweb.config.
10.View the Default.aspx page in the browser, and then highlight the value that was
retrieved from the web.config file.
11.In the browser, click Next to open the GetConfigSubFolder.aspx page in the SubFolder
folder, and then point out that the value is the same as the value in the web.config file
in the main directory.

Student Book Content


Configuration Inheritance
Key Points
The settings in the Machine.config file apply to all ASP.NET directories and subdirectories. Additional configuration
information is contained in the web.config configuration files, which are located in the same directories as the
application files. Child directories inherit the settings of the parent directories unless the settings are overridden by
a web.config file in the child directory.
CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 313
Web Site Administration Tool
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Emphasize that the Web Site Administration Tool provides an easy way to edit configuration files.

Student Book Content


Web Site Administration Tool
Key Points
The Web Site Administration Tool enables you to configure your ASP.NET Web site by using a Web page. The Tool
contains three sections as follows:
The Security tab enables you to manage security settings.
The Application tab enables you to manage several application-wide settings.
The Provider tab enables you to specify where and how to store administration data used by your Web site such as
membership data.

Question: In what situations may you have to take a Web application offline?

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 314
Retrieving Data from Web.config
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Step through the example code provided to illustrate how to retrieve settings from the Web.config file.

Student Book Content


Retrieving Data from Web.config
Key Points
The WebConfigurationManager class provides the AppSettings and ConnectionStrings properties, which
you use to access the key-value pairs in the <appSettings> and <connectionStrings> sections of the
web.config file.
For other sections in the configuration file, the WebConfigurationManager class provides the GetSection
method.
Question: In which situations may you want to access the configuration settings of your Web application
programmatically?
CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 315
Deploying an ASP.NET Web Application
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 4
Deploying an ASP.NET Web Application
After you set up caching and organize the Web application settings between the Machine.config and web.config
files, you are ready to deploy your ASP.NET Web application.
This lesson describes how to select the files that are necessary to run the Web application and then use XCOPY or
file transfer protocol (FTP) to copy these files to the production directory.

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 316
Web Application Deployment
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Mention to the students that they can use a Web Setup project to handle any issues with registration
and configuration automatically.

Student Book Content


Web Application Deployment
Key Points
You can choose from several deployment options for your Web application. Before you can deploy a Web
application to a production directory, the folder to which you will deploy your Web application must be configured
as an application in Internet Information Services (IIS).
The files that are required on the production server include:
The bin folder and the DLL files that are in it.
All Web Form, user control, and XML Web service files (.aspx, .ascx, .asmx).
Files, including web.config configuration files and global.asax.
Any additional support files that are in the directory (such as XML files).

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 317
Deploying a Web Application by Using the Publish Web Site Utility
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


Explain the steps required to use the Publish Web Site utility. If you have time, demonstrate the steps
as you describe them.

Student Book Content


Deploying a Web Application by Using the Publish Web Site Utility
Key Points
An advantage of the Publish Web Site utility is that the source code is removed from the Web site prior to
deployment. However, if you do not select the option Allow this precompiled site to be updatable, you must
recompile the site if you want to make changes.
Question: How can the Publish Web Site utility be useful to you when you develop your own Web applications?
CD Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 318
Sharing Assemblies in the Global Assembly Cache
Saturday, September 06, 2008
12:42 AM

Instructor Notes (PPT Text)


You can open the global assembly cache (GAC) and show the contents.
Provide a few examples of shared assemblies and explain why they are shared.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 319
Updating Your Web Application
Saturday, September 06, 2008
12:43 AM

Instructor Notes (PPT Text)


Emphasize that students can update an application without the requirement to restart IIS, the Web
server, or the application.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 320
Lab - Configuring, Optimizing, and Deploying a Microsoft ASP.NET
Web Application
Saturday, September 06, 2008
12:43 AM

Instructor Notes (PPT Text)


In this lab, students will configure, optimize, and deploy a Microsoft ASP.NET Web application.
Note: When you run the application, a warning message appears because the AjaxControlToolkit.dll
file is not present in the virtual machine. You can ignore this warning message or download the
version of the AjaxControlToolkit.dll file that targets the official release of .NET Framework 3.5 and
Visual Studio 2008 from the www.codeplex.com Web site. If you download the AjaxControlToolkit.dll
file, copy it to the virtual machine to remove the warning message. Mention this to the students.
Exercise 1
In this exercise, students cache a DataSet by using the Cache object.
Exercise 2
In this exercise, students cache a Web Form and a user control by using page output caching.
Exercise 3
In this exercise, students implement partial-page caching.
Exercise 4
In this exercise, students deploy the Benefits Web site.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 321
Exercise 1 - Caching a DataSet by Using the Cache Object
Saturday, September 06, 2008
12:43 AM

Instructor Notes (PPT Text)


Coho Winery offers several benefits to its employees. In the labs for this course, you create a Web site
that enables employees to select and set up their chosen benefits. In this lab, you will optimize and
then deploy the Benefits Web site.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 322
Exercise 2 - Reducing Response Times by Using the Page Output
Cache
Saturday, September 06, 2008
12:43 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. In exercise 1, why do you implement caching in both the Page_Load event procedure
and in the list's SelectedIndexChanged event procedure on the doctors Web page?
Because the GridView uses DataViews that are based on the city name
selected from the list.
2. In Exercise 2, at the end of Task 1, you are returned to the medical.aspx page, but the
selected doctor's name does not appear next to the Primary Care Physician box.
Why?
The page is in cache and does not vary by any parameters passed. When the
page is first loaded into the cache, it does not display a doctor's name.
Therefore, regardless of what information is returned to the medical.aspx
page, the page is retrieved from cache and will not display a doctor's name.
3. In Exercise 2, Task 2, what is the name of the parameter that is passed from the
doctors.aspx page to the medical.aspx page?
pcp
4. Which methods, other than Publish Web Site, can you use to deploy the Web site?
Copy web site or Web Setup project.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 323
Exercise 3 - Partial-Page Caching
Saturday, September 06, 2008
12:43 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.
Common Issues and Troubleshooting Tips
Point the students to possible troubleshooting tips for the issues presented in this section.
Tools
Point out the location from which each key tool can be installed. Let students review the function and
usage of each tool on their own. Remind students that they can use this as a master list to help them
gather all the tools required to facilitate their application support work.

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 324
Exercise 4 - Deploying Your Site
Saturday, September 06, 2008
12:43 AM

Student Book Content

Module 15-Configuring, Optimizing, and Deploying a Microsoft ASP.NET Web Application página 325
Web Application Security Overview
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 1
Web Application Security Overview
By definition, Web applications provide user access to a central Web server and other database servers. If you
understand and implement suitable security measures for your Web application, you can protect your own
resources; you can also provide a secure environment that is easy for your users to work in.
This lesson provides an overview of different security concepts: authentication, authorization, and IIS authentication
mechanisms. It also explains Secure Sockets Layer (SSL).

Module 16-Securing a Microsoft ASP.NET Web Application página 326


Authentication vs. Authorization
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Check that the students can confidently provide a definition of authentication and authorization. Point
out that authentication relates to the logon process and authorization relates to permissions.

Student Book Content


Authentication vs. Authorization
Key Points
The two fundamental security concepts are as follows:
Authentication. Obtains user credentials and validates those credentials against some authority such as a database.
Authorization. Determines if the authenticated user has access to a specified resource. You can limit access rights by
granting or denying specific permissions to an authenticated identity.

Question: Does authentication occur before or after authorization or do they both occur at the same time?

Module 16-Securing a Microsoft ASP.NET Web Application página 327


What Are the ASP.NET Authentication Methods
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Distinguish between the two methods of authentication and explain the key features of each.

Student Book Content


What Are the ASP.NET Authentication Methods?
Key Points
ASP.NET implements authentication by using three types of authentication method:
Microsoft Windows ®-based authentication. The ASP.NET Web application relies on the Windows operating
system to authenticate the user.
Forms-based authentication. Non-authenticated requests are redirected to an authentication form by using client-
side redirection.
Microsoft Passport authentication. Users are authenticated to access Web sites by using a single Passport account.

Question: Which authentication method(s) also use IIS authentication?

Module 16-Securing a Microsoft ASP.NET Web Application página 328


Comparing the ASP.NET Authentication Methods
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Explain to the students when they can use each authentication method in a Web application.

Student Book Content


Comparing the ASP.NET Authentication Methods
Key Points
Windows-based authentication is appropriate when you have a fixed number of users with existing Windows user
accounts; however, it is not suitable for most Internet applications.
Forms-based authentication is appropriate when you want to set up a custom user registration system; however, it
utilizes cookies to determine the identity of the user.
Microsoft Passport authentication enables a user to sign in to multiple Webs sites by using a single set of
credentials; however, there is a subscription fee and it is based on cookies.
Question: Why is Windows-based authentication not suitable for most Internet applications?

Module 16-Securing a Microsoft ASP.NET Web Application página 329


What Are the IIS Authentication Mechanisms
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Explain to the students that they must configure IIS before they can use Microsoft® Windows®
authentication. Briefly explain each IIS authentication mechanism. Mention that NTLM represents 'NT
LAN Manager'.

Student Book Content


What Are the IIS Authentication Mechanisms?
Key Points
When you use Windows-based authentication, you must first configure the authentication mechanisms in IIS:
Anonymous access. When IIS receives a request from an anonymous user, IIS in turn makes the request to Windows
by using the default IUSR_machinename account.
Basic authentication. Supported by most browsers; users without credentials are prompted to supply a user name
and password.
Digest authentication. Similar to Basic authentication, but it uses an encoded hash to send user information to the
server. However, it works only with Active Directory ® directory service domain accounts.

Module 16-Securing a Microsoft ASP.NET Web Application página 330


Demonstration - IIS Authentication Mechanisms
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


In this demonstration, students will see the IIS authentication mechanisms. Mention that IIS is slightly
different for each version of Windows.
• Open the Computer Management console
1. Click Start, right-click Computer, and then click Manage.
2. In the User Account Control dialog box, click Continue.
• Display the authentication methods for the deployed Web site
3. In the Computer Management console, in the left pane, expand Services and Applications, and then
click Internet Information Services (IIS) Manager.
4. In the Connections pane, expand LONDON (LONDON\Stude nt), expand Web Sites, and then
click Default Web Site.
5. In the Default Web Site Home pane, double-click Authentication.
6. In the Authentication pane, point out the IIS authentication mechanisms.
7. Enable and disable an authentication mechanism.
8. Close the Computer Management console.

Student Book Content


Demonstration: IIS Authentication Mechanisms
Question: How can you enable and disable the authentication mechanisms in IIS?
CD Content
In this demonstration, the instructor will show you the authentication mechanisms in IIS.

Module 16-Securing a Microsoft ASP.NET Web Application página 331


What Is Secure Sockets Layer
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Do not spend too much time on this topic. The CD content for this slide provide a good overview of
Secure Sockets Layer (SSL), and the students can read these notes at their own pace. Explain the
term phishing: a type of e-mail scam that steals your identity.

Student Book Content


What Is Secure Sockets Layer?
Key Points
SSL is a protocol that you can use to transmit data securely across a network.
SSL secures data communication by using data encryption, server authentication, and data integrity.
Question: How can you prevent one Web site from impersonating another?
CD Content
IIS provides users with a secure communication channel by supporting the SSL protocol and RSA Data Security
encryption on both the server and client.

Module 16-Securing a Microsoft ASP.NET Web Application página 332


Windows-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 2
Windows-Based Authentication
You can use Windows-based authentication to secure Web applications when you know which users access your
Web site.
This lesson explains how to use Windows-based authentication to secure your Web applications.

Module 16-Securing a Microsoft ASP.NET Web Application página 333


Enabling Windows-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


This topic explains the four-step process that you use to secure Web applications by using Windows-
based authentication:
1. Configure IIS.
2. Set up authentication in the web.config file.
3. Set up authorization in the web.config file.
4. IIS requests logon information from the users.
Emphasize that impersonation is optional in ASP.NET and is disabled by default. To enable
impersonation, you must configure the web.config file.

Student Book Content


Enabling Windows-Based Authentication
Key Points
Securing Web applications by using Windows-based authentication is a four-step process:
1. Configure IIS to use one or more of its three authentication mechanisms.
2. Set up authentication in the <authentication>, <authorization>, and <identity> sections of the web.config
file.
3. Set up authorization for each secure page in the <location> sections of the web.config file.
4. IIS requests logon information from your users and grants access if the credentials are valid.

Module 16-Securing a Microsoft ASP.NET Web Application página 334


Reading User Information
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Briefly explain the code required to read user information. Mention that User.Identity is not limited
to Windows-based authentication.

Student Book Content


Reading User Information
Key Points
When Windows-based authentication is complete, the Web server can read the user identity from any Web page of
the Web application. You can use the User.Identityobject to ascertain the user identity, the IIS authentication
mechanism, or if the user is authenticated.
Question: What properties of the User.Identityobject can you use to ascertain the user identity, the IIS
authentication mechanism, or if the user is authenticated?
CD Content
After the process of Windows-based authentication is complete, the Web server can read the user identity from any
Web page of the Web application.

Module 16-Securing a Microsoft ASP.NET Web Application página 335


Forms-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)

Student Book Content


Lesson 3
Forms-Based Authentication
The most common authentication method to secure ASP.NET Web applications is Forms-based authentication.
This lesson describes Forms-based architecture and explains the steps that you use to enable Forms-based
authentication. It also demonstrates how to set up security in the web.config file and create a logon page.

Module 16-Securing a Microsoft ASP.NET Web Application página 336


Overview of Forms-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Ensure that the students understand the sequence of events for Forms-based authentication.

Student Book Content


Overview of Forms-Based Authentication
Key Points
When a user requests a Web page that is protected by Forms-based authentication, the request must first go
through IIS. Therefore, you must set IIS authentication to Anonymous access.
CD Content
When a user requests a Web page that is protected by Forms-based authentication, the request must first go
through IIS. Therefore, you must set IIS authentication to Anonymous access.
Events of Forms-Based Authentication
The following events occur during Forms-based authentication:

Module 16-Securing a Microsoft ASP.NET Web Application página 337


Multimedia - Forms-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Explain that the multimedia shows how Forms-based authentication works with a
non-authenticated client and with an authenticated client.

Student Book Content


Multimedia: Forms-Based Authentication
Key Points
In this animation, you will see the implementation of Forms-based authentication with a non-authenticated client
and with an authenticated client.
CD Content
In this animation, you will see the implementation of Forms-based authentication with a non-authenticated client
and with an authenticated client. The steps are as follows:
1. When a non-authenticated client requests a secure page on the Web server, the request first goes through IIS.
2. Because IIS must be configured as Anonymous to use Forms-based authentication, the request goes straight to
the ASP.NET Forms authentication module.

Module 16-Securing a Microsoft ASP.NET Web Application página 338


Enabling Forms-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Explain the steps required to enable Forms-based authentication.

Student Book Content


Enabling Forms-Based Authentication
Key Points
To enable Forms-based authentication for your Web application:
1. Enable Forms-based authentication by configuring IIS to use Anonymous authentication so that the user is
authenticated by ASP.NET and not by IIS.
2. Set up authentication in the <authentication> section of the web.config file.
3. Set up authorization in the <authorization> section of the web.config file.
4. Create a logon Web Form.

Module 16-Securing a Microsoft ASP.NET Web Application página 339


Creating a Logon Page
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Explain that a logon page is a standard .aspx Web Form that contains logon controls.
If time permits, display the login controls in the Toolbox of Microsoft Visual Studio®. Add different
login controls to a Web page and emphasize their specific login properties.

Student Book Content


Creating a Logon Page
Key Points
You can easily create a logon page by using the Login control.
ASP.NET provides other login controls that you can access from the Toolbox in Microsoft Visual Studio ®.
Question: What ASP.NET login controls can you add to a Web Form?
CD Content
You can easily add logon functionality to your Web application by using the ASP.NET login controls.

Module 16-Securing a Microsoft ASP.NET Web Application página 340


Demonstration - Forms-Based Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


In this demonstration, students will see how implement Forms-based authentication.
• Examine authentication and authorization in web.config
1. In Visual Studio, open the Web site in the E:\Democode\CS\FormsAuthentication or E:\Democode\CS
\FormsAuthentication folder.
2. In Solution Explorer, double-click the web.config file.
3. Examine the element that enables Forms authentication and redirects unauthenticated users to the
LoginDemo.aspx page.
4. Examine the elements that set the SecurityPageDemo1.aspx and SecurityPageDemo2.aspx pages to
require authorization.
• Examine the logon and register pages
5. Open the LogonDemo.aspx page in Design view to display the Logon control.
6. Open the RegisterDemo.aspx page in design view to display the CreateUserWizard control.
• Run the demonstration
7. In Solution Explorer, right-click NonSecurePage Demo.aspx, and then click View in Browser.
You can access the non-secure page.
2. In the browser, click the SecurePageDemo1 link.
You are redirected to the LogonDemo.aspx page because you are not an authenticated user and the
SecurePageDemo1.aspx page is a secure page. Show that you are automatically redirected to the
LoginDemo.aspx page. Show that the URL contains the SecurePageDemo1.aspx page.
3. Enter the user name Bob and the password Pa$$w0rd, and then click Log In.
You cannot access the secure page because you are not a registered user.
4. In the browser, click the link to register a new user.
5. Register the user name Bob and the password Pa$$w0rd, and then click Create
User.
6. In the browser, click Continue.
You are redirected the SecurePageDemo1.aspx page.
7. In the browser, click the SecurePageDemo2 link.
You can access this secure page because you are an authenticated user.
8. Close the browser.
If time permits, you can also show the students how to publish this Web site to IIS

Student Book Content


Demonstration: Forms-Based Authentication
Question: How can you configure Forms-based authentication?
CD Content
In this demonstration, the instructor will show you how to set up authentication and authorization in the web.config
file. Then, the instructor will demonstrate how the logon page works and then attempt to access secure and non-
secure pages.

Module 16-Securing a Microsoft ASP.NET Web Application página 341


Lab - Securing a Microsoft ASP.NET Web Application
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


In this lab, students will secure a Microsoft ASP.NET Web application by using Windows-based and
Forms-based authentication.
Note: When you run the application, a warning message appears because the AjaxControlToolkit.dll
file is not present in the virtual machine. You can ignore this warning message or download the
version of the AjaxControlToolkit.dll file that targets the official release of .NET Framework 3.5 and
Visual Studio 2008 from the www.codeplex.com Web site. If you download the AjaxControlToolkit.dll
file, copy it to the virtual machine to remove the warning message. Mention this to the students.
Exercise 1
In this exercise, students secure a Microsoft ASP.NET Web application by using Microsoft Windows-
based authentication.
Exercise 2
In this exercise, students secure a Web application by using Forms-based authentication.
Exercise 3
In this exercise, students create logon and registration pages.
Mention that students can set the home page of Internet Explorer to
http://localhost/Benefits/de fault.aspx so that they do not have to enter this URL multiple times.
Before the students begin the lab, read the scenario associated with each exercise to the class. This
will reinforce the broad issue that the students are troubleshooting and will help to encourage the lab
discussion at the end of the module. Remind the students to complete the discussion questions after
the last lab exercise.
Note: The lab exercise answer keys are provided on the Course Companion CD. To access the answer
key, click the link located at the bottom of the relevant lab exercise page.

Student Book Content


Lab: Securing a Microsoft ASP.NET Web Application
Exercise 1: Securing Your Web Site by Using Windows-Based Authentication
Scenario
Coho Winery offers several benefits to its employees.
Now that you have implemented all of the benefits, you want to allow only registered users to access the Web site.
In this lab, you will first secure the site by using Windows-based authentication. You will then change the Web site
to use Forms-based authentication. Finally, you will implement the registration page to enable users to register with
your Web site.

Module 16-Securing a Microsoft ASP.NET Web Application página 342


Exercise 1 - Securing Your Web Site by Using Windows-Based
Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Now that the students have implemented all of the benefits, they want to allow only registered users
to access the Web site. In this lab, students will first secure the site by using Windows-based
authentication. They will then change the Web site to use Forms-based authentication. Finally, they
will implement the registration page to enable users to register with the Web site.

Student Book Content

Task 7: Publish the Benefits Web site


1. In Solution Explorer, click the Benefits Web site.
2. On the Build menu, click Publish Web Site.
3. In the Publish Web Site dialog box, in the Target location box, type E:\Benefits
4. Clear the Allow this precompiled site to be updatable check box and then click OK.
5. Restore the Internet Information Services Manager dialog box.
6. In the Internet Information Services Manager dialog box, right-click Default Web Site, and then click
Add Application.
7. In the Add Application dialog box, in the Alias box, type Benefits
8. In the Physical path box, type E:\Benefits and then click OK.

Task 8: Configure IIS authentication


1. In Internet Information Services (IIS) Manager:
Verify that Anonymous Authentication is enabled and Windows Authentication is disabled for the Benefits
Web site.
Enable Basic Authentication for the Benefits Web site.
2. Minimize Internet Information Services (IIS) Manager.

Security Note: Anonymous access is enabled so that you can have both secure and non-secure pages in the
same Web application. For this exercise, Basic authentication has been enabled without the use of Secure
Sockets Layer (SSL); therefore, passwords are sent by using clear text. In a real-world scenario, to be secure,
you must obtain a server certificate and implement SSL when you use Basic authentication.
Task 9: Test Windows-based authentication for two pages
2. In a new browser, browse to http://localhost/Benefits/default.aspx.

Module 16-Securing a Microsoft ASP.NET Web Application página 343


Exercise 2 - Securing Your Web Site by Using Forms-Based
Authentication
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Lab Review Questions
Use the questions on the slide to guide the debriefing after students have completed the lab exercises.
Point the students to the appropriate section in the lab if they are not able to answer the questions
presented in this section.
1. How can you deny access to anonymous users for certain Web pages?
In the web.config file, you can add elements so that specified pages require authentication.
2. How can you configure Forms-based authentication in the web.config file?
In the web.config file, set .
3. How can you build a logon form for a Web site?
You can use a Login control to create a logon form.
4. How can you enable users to register with a Web site?
You can add a CreateUserWizard control to a register Web page to enable users to register
with a Web site.
5. How can you enable users to sign out of a Web site?
You can add a LoginStatus control to a Web site to enable users to sign out.

Student Book Content


Exercise 2: Securing Your Web Site by Using Forms-Based Authentication
Scenario
In this exercise, you will reconfigure IIS to use Anonymous authentication only. You will then use Forms-based
authentication to manage access to secure pages in the Benefits Web site. You will configure the web.config file to
use Forms-based authentication by denying non-authenticated users access to any page of the Benefits project
folder. Finally, you will create the login.aspx page and validate user credentials for users of your Web site.
The main tasks for this exercise are as follows:
1. Configure IIS to use only Anonymous authentication.
2. Configure Forms-based authentication in the web.config file.
3. Add a login.aspx Web Form to enter the credentials.
4. Test Forms-based authentication.

Task 1: Configure IIS to use only Anonymous authentication


1. Switch to Internet Information Services (IIS) Manager.
2. In Internet Information Services (IIS) Manager for the Benefits Web site:
Verify that Anonymous Authentication is enabled.
Disable Basic Authentication.
3. Close the Computer Management console.

Task 2: Configure Forms-based authentication in the web.config file


1. Switch to Visual Studio 2008.
2. Open the web.config file.
3. In the web.config file, locate the <authentication> section, and then modify it to use Forms-based
authentication. You must create a cookie named .ASPXAUTH and redirect the user to a page named login.aspx if
the user is not authenticated.

Module 16-Securing a Microsoft ASP.NET Web Application página 344


Module 16-Securing a Microsoft ASP.NET Web Application página 345
Exercise 3 - Registering New Users
Saturday, September 06, 2008
12:44 AM

Instructor Notes (PPT Text)


Review Questions
Point the students to the appropriate section in the course so that they are able to answer the
questions presented in this section.

Best Practices
Help the students understand the best practices presented in this section. Ask students to consider
these best practices in the context of their own business situations.
Tools
Point out the location from which each key tool can be installed. Let students review the function and
usage of each tool on their own. Remind students that they can use this as a master list to help them
gather all the tools required to facilitate their application support work.

Student Book Content


Exercise 3: Registering New Users
Scenario
In this exercise, you will add a register.aspx page to enable users to register with your Web site.
The main tasks for this exercise are as follows:
1. Add a register.aspx Web Form to register new users.
2. Attempt to register a new user.
3. Configure the security for the register.aspx page in the web.config file.
4. Test authorized access to the register.aspx page.

Task 1: Add a register.aspx Web Form to register new users


1. Add the register.aspx file from the E:\Labfiles\Starter\CS\ or E:\Labfiles\Starter\VB\ folder to the Web site.
This page contains a title for the Web site.
2. Add a CreateUserWizard control named benefitsCreateUserWizard to the center of the Web Form.
3. Create a CreatedUser event handler for the benefitsCreateUserWizard control.
4. In the benefitsCreateUserWizard_CreatedUser event handler, write code to authenticate users, create a
temporary (non-persistent) authentication cookie by using the UserName property of the control, and then
redirect the user to the Default.aspx page.
5. Consider why you call the SetAuthCookie method here and not RedirectFromLoginPage.
You call the SetAuthCookie method because you want to redirect users to the Default.aspx Web Form. Usually,
the register.aspx Web Form is called from a link in the login.aspx Web Form. The RedirectFromLoginPage
method redirects a newly registered and authenticated user to the login.aspx Web Form, which makes no sense.

Task 2: Attempt to register a new user


1. Build the Web site and publish it to E:\Benefits.

Module 16-Securing a Microsoft ASP.NET Web Application página 346

S-ar putea să vă placă și