Você está na página 1de 180

O F F I C I A L

M I C R O S O F T

L E A R N I N G

P R O D U C T

10264A
Developing Web Applications with
Microsoft Visual Studio 2010
Companion Content

Information in this document, including URL and other Internet Web site references, is subject to change
without notice. Unless otherwise noted, the example companies, organizations, products, domain names,
e-mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with
any real company, organization, product, domain name, e-mail address, logo, person, place or event is
intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the
user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in
or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of
Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
The names of manufacturers, products, or URLs are provided for informational purposes only and
Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding
these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a
manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links
may be provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not
responsible for the contents of any linked site or any link contained in a linked site, or any changes or
updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission
received from any linked site. Microsoft is providing these links to you only as a convenience, and the
inclusion of any link does not imply endorsement of Microsoft of the site or the products contained
therein.
2010 Microsoft Corporation. All rights reserved.
Microsoft and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks
of the Microsoft group of companies. All other marks are property of their respective owners.

Product Number: 10264A


Released: 11/2010

Overview of Web Application Architecture and Design

Module 1
Overview of Web Application Architecture and Design
Contents:
Lesson 1: Overview of IIS 7.0

Lesson 2: Overview of ASP.NET 4.0

Lesson 3: Introduction to the MVC Framework

10

Lesson 4: Overview of the Request Life Cycle

14

1-1

1-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Overview of IIS 7.0


Contents:
Question and Answers

Detailed Demo Steps

Overview of Web Application Architecture and Design

Question and Answers


Key Features of IIS 7.0
Question: Which benefits are offered by the modular IIS architecture? Name at least one.
Answer: You can quickly and easily add new features, you can make changes to one feature, which
should not affect other features, and you can turn features on and off depending on your needs.

1-3

1-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Administering IIS 7.0 by Using IIS Manager
This demonstration will illustrate the many features of IIS, and show how to administer its functions. These
features include:

Creating a new website

Authentication

Permissions

Connection strings

Application settings

Starting and stopping a site

Recycling the Application pool

Create a new Website


1.

On the Start menu, point to Administrative Tools, right-click Internet Information Services
(IIS) Manager, and then click Run as administrator.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and
then click Yes.

2.

In Internet Information Services (IIS) Manager, expand 10264A-GEN-DEV (10264A-GENDEV\Admin), and then expand Sites.

3.

Right-click Sites, and then click Add Web Site.

4.

In the Add Web Site dialog box, specify the settings as shown in the following sample. You will
need to create the demo subfolder in the C:\inetpub\ folder.

Overview of Web Application Architecture and Design

5.

Click OK.

Change authentication
1.

In the Connections pane, click Demo.

2.

In the Demo Home pane, in the IIS section, double-click Authentication.

3.

In the Authentication pane, right-click Basic Authentication, and then click Enable.

Edit permissions
1.

In the Connections pane, click Demo.

2.

In the Actions pane, click Edit Permissions.

3.

In the demo Properties dialog box, click Security.

4.

Click Edit.

5.

In the Permissions for demo dialog box, click Add.

6.

In the Select Users or Groups dialog box, in the Enter the object names to select box, type
IIS_IUSRS, click Check Names, and then click OK.

7.

In the Permissions for demo dialog box, click OK.

8.

In the demo Properties dialog box, click OK.

Set connection string


1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In the Demo Home pane, in the ASP.NET section, double-click Connection Strings.

3.

In the Actions pane, click Add.

1-5

1-6

Developing Web Applications with Microsoft Visual Studio 2010

4.

In the Add Connection String dialog box, specify the settings as shown in the following
illustration.

5.

Click OK.

6.

In the Connection Strings pane, click Content View.

7.

In the Demo Content pane, click web.config.


Note: A web.config file is added to the websites root directory.

8.

In the Connections pane, right-click Demo, and then click Explore.

9.

In Windows Explorer, double-click web.config.


Note: In Microsoft Visual Studio 2010, you can see the new connection string added to the
web.config file.

10. Close Microsoft Visual Studio 2010.


11. Close Windows Explorer.

Specify application settings


1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In the Demo Content pane, click Features View.

3.

In the Demo Home pane, in the ASP.NET section, double-click Application Settings.

Overview of Web Application Architecture and Design

4.

In the Actions pane, click Add.

5.

In the Add Application Setting dialog box, specify the settings per the following.

6.

Click OK.

7.

In Windows Explorer, double-click web.config.


Note: In Microsoft Visual Studio 2010, you can see the new application setting added to the
web.config file.

8.

Close Microsoft Visual Studio 2010.

9.

Close Windows Explorer.

Restart the Website


1.

In the Connections pane, click Default Web Site, and then click Demo.

2.

In Actions pane, in the Manage Web Site section, click Restart.

Recycle an application pool


1.

In the Connections pane, click Application Pools.

2.

In the Application Pools pane, click DefaultAppPool, and then in the Actions pane, in the
Application Pool Tasks section, click Recycle.

3.

Close Internet Information Services (IIS) Manager.

1-7

1-8

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Overview of ASP.NET 4.0


Contents:
Question and Answers

Overview of Web Application Architecture and Design

Question and Answers


New Features in ASP.NET 4.0
Question: How is compression of serialized session state enabled?
Answer: Compression of serialized session state is enabled by setting the value of the
compressionEnabled configuration option to true.

1-9

1-10

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Introduction to the MVC Framework


Contents:
Question and Answers

11

Detailed Demo Steps

12

Overview of Web Application Architecture and Design

1-11

Question and Answers


What Is the MVC Framework?
Question: What advantages are there in separating the concerns of data structures, presentation, and
application logic?
Answer: Separation of concerns allows for autonomous updates, and easier maintenance.

Demonstration: Exploring an MVC Application


Question: What other elements did you recognize in the MVC solution?
Answers: May vary, but the controllers, views, and models, as well as the .aspx extension and master
pages.

1-12

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Exploring an MVC Application
Exploring the Adventure Works MVC Application
1.

Open Microsoft Visual Studio 2010.

2.

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

Create a new MVC project.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.

b.

In the New Project dialog box, in the left pane, in the Installed Templates section,
expand Visual C# or Visual Basic, and then click Web.

c.

In the New Project dialog box, in the middle pane, click ASP.NET MVC 2 Web
Application.

d.

In the New Project dialog box, in the middle pane, in the Name box, type
DemoMvcApplication, in the Location box, type D:\Demofiles\Module 01\Demo 02,
and then click OK.

3.

In the Create Unit Test dialog box, select the No, do not create a unit test project option, and
then click OK.

4.

View the Controllers folder.

In Solution Explorer, expand the Controllers folder.

Note: Observe that the code files all have the suffix Controller.
5.

View the Models folder

6.

In Solution Explorer, expand the Models folder.

View all the code in the AccountModels code file.


a.

In Solution Explorer, double-click the AccountModels.cs or AccountModels.vb code


file.

b.

In the AccountModels.cs or AccountModels.vb window, press CTRL+M, CTRL+L.

c.

Scroll down and show the different regions of code.

Note: The model code file contains the data structures for this web application and classes that
control logic for working with the data store.
d.
7.

In the AccountModels.cs or AccountModels.vb window, click the Close button.

View the Views folder.

In Solution Explorer, expand the Views folder.

Note: Several folders share their name with the names of the controllers in the Controllers
folder.
8.

View the Views/Shared folder.

Overview of Web Application Architecture and Design

1-13

In Solution Explorer, expand the Views/Shared folder.

Note: The Shared folder contains master pages, user controls, and pages shared across the
MVC web application.
9.

Close Microsoft Visual Studio 2010.

In the DemoMvcApplication - Microsoft Visual Studio 2010 window, click the Close
button.

1-14

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 4

Overview of the Request Life Cycle


Contents:
Question and Answers

15

Overview of Web Application Architecture and Design

1-15

Question and Answers


Life Cycle of a Web Forms Request
Question: What is postback data?
Answers: Postback data is data that is available in the HTML form element.

Life Cycle of an MVC Request


Question: What is the first step of an MVC request?
Answers: ASP.NET Routing routes the request to the appropriate resource.

Comparison of the Web Forms and MVC Request Life Cycles


Question: In what other ways do the request life cycles differ between Web Forms and MVC?
Answer: May vary discuss with students.

Working with the Web Forms Page Life Cycle


Question: What other scenarios can you imagine where you would need to use events in the pages
life cycle to process the page correctly?
Answer: May vary discuss with students.

Designing a Web Application

Module 2
Designing a Web Application
Contents:
Lesson 1: Web Applications: Case Studies

Lesson 2: Web Application Design Essentials

Lesson 3: Visual Studio 2010 Tools and Technologies


for Web Application Design

2-1

2-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Web Applications: Case Studies


Contents:
Questions and Answers

Designing a Web Application

Questions and Answers


Discussion: Overview of Web Applications and Their Characteristics
Question: What are some further variations on websites that were not covered?
Answer: Will vary.
Question: While not being an exact fit, do these four types of websites relate to the previous
questions answers in some ways?
Answer: Will vary.

2-3

2-4

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Web Application Design Essentials


Contents:
Questions and Answers

Designing a Web Application

2-5

Questions and Answers


Common Design Considerations
Question: How does security play a role in every type of web application?
Answer: Even for static websites, the file system should have security attached.
Question: How do scalability and reliability relate to one another?
Answer: Often scalability and reliability are closely linked, as the ability to recover from the loss of
resources requires the ability of your web application to spread its processing across more than one
single point of failure.

Discussion: Web Forms and MVC


Question: What features, common or different, do you see in both the Web Forms and MVC
frameworks that would benefit your development efforts?
Answer: May vary.

Guidelines for Determining When to Use Web Forms and When to Use
MVC
Question: What solutions in your experience may have benefited from implementation using MVC?
Answer: Will Vary.
Question: What key features of Web Forms that you use frequently might you miss when developing
with MVC?
Answer: Will Vary.

2-6

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Visual Studio 2010 Tools and Technologies for Web


Application Design
Contents:
Questions and Answers

Designing a Web Application

Questions and Answers


Overview of the Design View in Visual Studio 2010
Question: What value does the Design view bring to your development process?
Answer: The Design view shows you any master pages and nested master pages that are
implemented in your page so that you see exactly what you would see when you view the page in a
browser.

Enterprise Library
Question: What benefits can you see to using the Enterprise Library as a consistent interface for
common tasks that your applications require?
Answer: Will vary.

IIS SEO Toolkit


Question: What value do the robots.txt and sitemap.xml files provide?
Answer: The robots.txt file tells a search engine what it can and cannot crawl when indexing your
site. The sitemap.xml file provides a map of your site for a search engine crawler. This allows the
crawler to access areas of your site that it might not have without the sitemap.
Question: How does the Site Analysis tool help you understand how a search engine crawler will
react to the content of your site?
Answer: By running the Site Analysis tool, you can find and correct potential issues that will stop a
search engine crawler from properly attributing relevance to your content, and possibly halting the
indexing of your site altogether.

2-7

Developing MVC Models

Module 3
Developing MVC Models
Contents:
Lesson 1: Exploring Ways to Create MVC Models

Lesson 2: Working with Data in MVC Models

Lesson 3: Creating a Data Repository

3-1

3-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Exploring Ways to Create MVC Models


Contents:
Detailed Demo Steps

Developing MVC Models

3-3

Detailed Demo Steps


Demonstration: Creating an MVC Model by Using Classes
Creating an MVC model using classes
Open Microsoft Visual Studio 2010.

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

Create a new ASP.NET MVC 2 Web Application project, with an associated Unit Test project.
a.
b.

c.

In the Start Page Microsoft Visual Studio window, on the File menu, click New Project, or
press CTRL+SHIFT+N.
In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the middle
pane, click ASP.NET MVC 2 Web Application, in the Location box, type D:\Demofiles\CS or
D:\Demofiles\VB, and then click OK.
In the Create Unit Test Project dialog box, ensure the Yes, create a unit test project check box
is selected, and then click OK.

Add a new class named Blog to the Models folder.


a.
b.

In Solution Explorer, right-click Models, point to Add and then click New Item, or press
CTRL+SHIFT+A.
In the Add New Item MvcApplication1 dialog box, in the left pane, click Visual C# or Visual
Basic, in the middle pane, click Class, in the Name box, type Blog, and then click Add.

Add the following code to the Blog class.

[Visual C#]
public class Blog
{
public string Title { get; set; }
public string Description { get; set; }
}

[Visual Basic]
Public Class Blog
Private Property Title As String
Private Property Description As String
End Class

Build the solution, and fix any errors.

In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click Build
Solution, or press CTRL+SHIFT+B.

Close Visual Studio 2010.

In the MvcApplication1 Microsoft Visual Studio window, click the Close button.
Best Practices: Model should not be concerned about saving itself to the persistent medium,
and the data access responsibility should be kept separate from the model.

3-4

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Working with Data in MVC Models


Contents:
Questions and Answers

Developing MVC Models

3-5

Questions and Answers


Data Mapper Pattern
Question: How is the Data Mapper pattern different from the Active Record pattern?
Answer: The Active Record pattern uses a strongly typed class wrapper around a row in the database
table, and thus directly mimics the database structure, while the Data Mapper pattern keeps the
database structure and object structure separate.

3-6

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Creating a Data Repository


Contents:
Questions and Answers

Detailed Demo Steps

Developing MVC Models

Questions and Answers


Extending Model Classes to Add Business Rules
Question: Why is it not a good idea to implement the business rules in the model class created by
using the Entity Framework?
Answer: When the project is built, custom code is overwritten.

3-7

3-8

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating a Data Repository
This topic focuses on implementing a data repository. The demonstration uses the Entity Framework as
the data model. The repository will exhibit persistence and data retrieval methods.
1.

Open Microsoft Visual Studio 2010.

2.

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

Open the MvcApplication1 solution at the following location.

Programming Language

Location

Visual C#

D:\Demofiles\CS\MvcApplication1

Visual Basic

D:\Demofiles\VB\MvcApplication1

3.

4.

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\MvcApplication1\MvcApplication1.sln or
D:\Demofiles\VB\MvcApplication1\MvcApplication1.sln and then click Open.

Add a new ADO.NET Entity Data Model named MyModel.edmx to the project, and generate the
model from database. The model must be added to the Models folder.
a.

In Solution Explorer, right-click Models, point to Add, and then click New Item.

b.

In the Add New Item MvcApplication1 dialog box, in the left pane, click Data.

c.

In the middle pane, click ADO.NET Entity Data Model, in the Name box, type
MyModel.edmx, and then click Add.

d.

In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate
from database, and then click Next.

In the Entity Data Model Wizard, on the Choose Your Data Connection page, if the Which data
connection should your application use to connect to the database? list, is empty, click New
Connection, and create a new connection to the AdventureWorksLT2008R2 database on the
.\SQLExpress SQL Server instance.
a.

In the Choose Data Source dialog box, in the Data source list, click Microsoft SQL
Server, and then click OK.

b.

In the Connection Properties dialog box, in the Server name box, type .\SQLExpress,
in the Select or enter a database name list, click AdventureWorksLT2008R2, and
then click Continue.

5.

In the Entity Data Model Wizard, on the Choose Your Data Connection page, if the Which data
connection should your application use to connect to the database? list, click 10264a-gendev\sqlexpress.AdventureWorksLT2008R2.Sales(LT), and then click Next.

6.

Select the Blog and Blogger tables from the database.

Developing MVC Models

3-9

7.

On the Choose Your Database Objects page, in the Which database objects do you want to
include in your model list, expand Tables, select the Blog and Blogger check boxes, and then
click Finish.

8.

Add a new data repository class named BlogRepository to the Models folder.

9.

a.

In Solution Explorer, right-click Models, point to Add, and then click New Item.

b.

In the Add New Item MvcApplication1 dialog box, in the left pane, click Visual C# or
Visual Basic.

c.

In the middle pane, click Class, in the Name box, type BlogRepository, and then click
Add.

Add the following code to the BlogRepository class.

[Visual C#]
private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();
public IQueryable<MvcApplication1.Models.Blog> GetAllBlogs()
{
return db.Blogs;
}

[Visual Basic]
Private db As New AdventureWorksLT2008R2Entities()
Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)
Return db.Blogs
End Function

In the BlogRepository.cs or BlogRepository.vb window, at the top of the


BlogRepository class, type the following code.

[Visual C#]
private AdventureWorksLT2008R2Entities db = new AdventureWorksLT2008R2Entities();
public IQueryable<MvcApplication1.Models.Blog> GetAllBlogs()
{

3-10

Developing Web Applications with Microsoft Visual Studio 2010

return db.Blogs;
}

[Visual Basic]
Private AdventureWorksLT2008R2Entities db As New AdventureWorksLT2008R2Entities()
Public Function GetAllBlogs() As IQueryable(Of MvcApplication1.Blog)
Return db.Blogs
End Function

10. Append the Save method to the BlogRepository class, which is responsible for persisting the
Blog object into the database.

[Visual C#]
public static void Save(MvcApplication1.Models.Blog blog)
{
using (var db = new AdventureWorksLT2008R2Entities ())
{
if (blog.BloggerID == 0)
{
db.AddToBlogs(blog);
db.SaveChanges();
}
}
}

[Visual Basic]
Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)
Using db As New AdventureWorksLT2008R2Entities()
If blog.BloggerID = 0 Then
db.AddToBlogs(blog)
db.SaveChanges()
End If
End Using
End Sub

In the BlogRepository.cs or BlogRepository.vb window, append the following code.


[Visual C#]
public static void Save(MvcApplication1.Models.Blog blog)
{
using (var db = new AdventureWorksLT2008R2Entities ())
{
if (blog.BloggerID == 0)
{
db.AddToBlogs(blog);
db.SaveChanges();
}
}
}

[Visual Basic]
Public Shared Sub Save(ByVal blog As MvcApplication1.Blog)
Using db As New AdventureWorksLT2008R2Entities()
If blog.BloggerID = 0 Then
db.AddToBlogs(blog)

Developing MVC Models

3-11

db.SaveChanges()
End If
End Using
End Sub

11. Delete the Blog class from the Models folder.


a.

In Solution Explorer, in the Models folder, right-click Blog.cs or Blog.vb, and then click
Delete.

b.

In the Microsoft Visual Studio dialog box, click OK.

12. Build the solution, and fix any errors.


In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click
Build Solution, or press CTRL+SHIFT+B.
13. Close Visual Studio 2010.
In the MvcApplication1 Microsoft Visual Studio window, click the Close button.

Developing MVC Controllers

Module 4
Developing MVC Controllers
Contents:
Lesson 1: Implementing MVC Controllers

Lesson 2: Creating Action Methods

4-1

4-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Implementing MVC Controllers


Contents:
Questions and Answers

Detailed Demo Steps

Additional Reading

Developing MVC Controllers

4-3

Questions and Answers


What Is an MVC Controller?
Question: What is the name of the Product controller class?
Answer: Because each controller class must end with the Controller suffix, the name of the Product
controller is ProductController.

What Is an Action Filter?


Question: What are some uses for action filters?
Answer: The possible uses for action filters are as varied as the actions to which they can be applied.
Some possible uses for action filters include:

Logging, to track user interactions.

"Anti-image-leeching," to prevent images from being loaded in pages that are not on your site.

Web crawler filtering, to change application behavior based on the browser user agent.

Localization, to set the locale.

Dynamic actions, to inject an action into a controller.


Question: What types of action filters does ASP.NET MVC provide?
Answer: The types of action filters that ASP.NET MVC provides are:

Authorization

Action

Result

Exception

4-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating an MVC Controller
In this demonstration, you will learn how to create an MVC controller.
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

Create a new ASP.NET MVC 2 Web Application project, with an associated Unit Test project.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Location box, type
D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

c.

In the Create Unit Test Project dialog box, ensure that Yes, create a unit test project
is selected, and then click OK.

Create a controller named BlogController in the Controllers folder. The controller should
include action methods for create, update, delete, and details scenarios.
a.

In Solution Explorer, right-click Controllers, point to Add and then click Controller.

b.

In the Add Controller dialog box, in the Controller Name box, type BlogController,
select the Add action methods for Create, Update, Delete, and Details scenarios
check box, and then click Add.

Build the solution, and fix any errors.

5.

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

In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click
Build Solution, or press CTRL+SHIFT+B.

Close Visual Studio 2010.

In the MvcApplication1 Microsoft Visual Studio window, click the Close button.

Demonstration: Using an Action Filter


In this demonstration, you will learn how to use a controller that is decorated with the
HandleErrorAttribute attribute.
1.

Open Microsoft Visual Studio 2010.

2.

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

Open the MvcApplication1 solution from the following location.

Programming Language

Location

Visual C#

D:\Demofiles\CS\MvcApplication1

Visual Basic

D:\Demofiles\VB\MvcApplication1

Developing MVC Controllers

3.

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project,
or press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\MvcApplication1\MvcApplication1.sln or
D:\Demofiles\VB\MvcApplication1\MvcApplication1.sln and then click Open.

Open the HomeController controller.

4.

In Solution Explorer, expand Controllers, and then double-click HomeController.cs or


HomeController.vb.

In the About action method, throw an exception of type Exception.

[Visual C#]
[HandleError(ExceptionType=typeof(Exception))]
public ActionResult About()
{
throw new Exception();
}

[Visual Basic]
<HandleError(ExceptionType:=GetType(Exception))>
Public Function About() As ActionResult
Throw New Exception()
End Function

5.

Open the Web.config file.

6.

In Solution Explorer, double-click Web.config.

Add a customErrors element to the Web.config file.

<system.web>
<customErrors mode="On" />
</system.web>
7.

Run the application.

8.

In the MvcApplication1 Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.

Display the About page.

In the Home Page Windows Internet Explorer window, click About.

Note: The error message, which is part of the Error.aspx page or view, located in the
Views\Shared folder, is displayed.
9.

4-5

Close Visual Studio 2010.

In the MvcApplication1 Microsoft Visual Studio window, click the Close button.

4-6

Developing Web Applications with Microsoft Visual Studio 2010

Additional Reading
What Is an MVC Controller?
For more information about MVC controllers, see Controller Class.
For more information about routing, see Understanding the MVC Application Execution
Process.

Developing MVC Controllers

Lesson 2

Creating Action Methods


Contents:
Questions and Answers

Detailed Demo Steps

10

Additional Reading

13

4-7

4-8

Developing Web Applications with Microsoft Visual Studio 2010

Questions and Answers


What Are Action Methods?
Question: What are the restrictions on action methods?
Answer: Action methods:

Must be public.

Cannot be static.

Cannot have unbounded generic type parameters.

Cannot be overloaded based on parameters unless they are disambiguated with attributes
such as NonActionAttribute or AcceptVerbsAttribute.

Question: How do you prevent a public method of a controller from being treated like an action
method?
Answer: By default, ASP.NET MVC treats all public methods of a controller class as action methods. If
your controller class contains a public method and you do not want it to be an action method, you
must decorate that method with the NonActionAttribute attribute.
Question: What is the shortest attribute you can use to designate that an action method should
respond only to an HTTP Post?
Answer: The shortest attribute you can use to designate that an action method should only respond
to an HTTP Post is the HttpPostAttribute attribute.

Calling an MVC View


Question: Which types derive from the ActionResult class?
Answer: The following types derive from ActionResult class:

ContentResult

EmptyResult

FileResult

JavaScriptResult

JsonResult

PartialViewResult

RedirectResult

RedirectToRouteResult

ViewResult

Question: What are the three ways that the ViewResult class can pass data to the view?
Answer: The three ways covered in this lesson are:

Developing MVC Controllers

ViewData

TempData

View property

4-9

Retrieving Data from the Request


Question: How can you retrieve data from a form?
Answer: You can retrieve data by using the Request object, the model binders, and the
FormCollection.
Question: How can you access the list of errors that occurred during the model binding?
Answer: The ModelState.Errors property returns a ModelErrorCollection object that contains any
errors that occurred during model binding.

4-10

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Retrieving Data from the Request
In this demonstration, you will learn how to retrieve data from the RouteData, the QueryString, a TextBox,
and the FormCollection.
1.

Open Microsoft Visual Studio 2010.

2.

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

Open the DemoHello solution from the following location.

Programming Language

Location

Visual C#

D:\Demofiles\CS

Visual Basic

D:\Demofiles\VB

3.

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project,
or press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DemoHello.sln or D:\Demofiles\VB\DemoHello.sln and then click Open.

Retrieve data from the RouteData.


a.

Run the project by pressing CTRL+F5.

b.

In the Hello Page - Windows Internet Explorer window, click Hello.

c.

Append the following text to the URL in the address bar, and then press ENTER.

/RouteDataDemo/World

Note: The value of the id key, retrieved from the RouteData.Values key/value pair collection,
(World) is displayed.

d.
4.

Close Windows Internet Explorer.

Retrieve data from the QueryString.


a.

Run the project by pressing CTRL+F5.

b.

In the Hello Page - Windows Internet Explorer window, click Hello.

c.

Append the following text to the URL in the address bar, and then press ENTER.

/QueryStringDemo?id=World

Note: The value of the id key, retrieved from the Request object key/value pair collection,
(World) is displayed.

Developing MVC Controllers

d.
5.

Close Internet Explorer.

Retrieve data from the text box.


a.

Replace the content of the Content2 Content control in the Index.aspx page file in the
Views\Hello folder with the following markup.

[Visual C#]
<% Html.BeginForm(); %>
Enter Your Name: <%: Html.TextBox("id") %>
<input id="Submit1" type="submit" value="Submit" />
<h2><%: ViewData["Message"] %></h2>
<% Html.EndForm(); %>

[Visual Basic]
<% Html.BeginForm() %>
Enter Your Name: <%: Html.TextBox("id") %>
<input id="Submit1" type="submit" value="Submit" />
<h2><%: ViewData("Message") %></h2>
<% Html.EndForm() %>

b.

In Solution Explorer, click DemoHello.

c.

Run the project by pressing CTRL+F5.

d.

In the Hello Page - Windows Internet Explorer window, click Hello.

e.

Append the following text to the URL in the address bar, and then press ENTER.

/TextBoxDemo

f.

In the Enter Your Name box, type your name, and then click Submit.

Note: The value entered in the text box is displayed.


g.
6.

4-11

Close Internet Explorer.

Retrieve data from a FormCollection.


a.

Add a new action method named FormCollectionDemo in the HelloController.

[Visual C#]
public ActionResult FormCollectionDemo(FormCollection collection)
{
ViewData["Message"] = "Hello " + collection["id"];
return View("Index");
}

[Visual Basic]
Function FormCollectionDemo(ByVal collection As FormCollection) As ActionResult
ViewData("Message") = "Hello " & collection("id")
Return View("Index")
End Function

b.

Run the project by pressing CTRL+F5.

c.

In the Hello Page- Windows Internet Explorer window, click Hello.

4-12

Developing Web Applications with Microsoft Visual Studio 2010

d.

Append the following text to the URL in the address bar, and then press ENTER.

/FormCollectionDemo

e.

In the Enter Your Name box, type your name, and then click Submit.

f.

In the AutoComplete dialog box, click No.

Note: The value entered in the text box, retrieved from the FormCollection object, is displayed.
g.

Close Internet Explorer.

h.

Close Visual Studio 2010.

Developing MVC Controllers

Additional Reading
Calling an MVC View
For more information about the ActionResult class, see ActionResult Class.

For more information about the ViewResult class, see ViewResult Class.

4-13

Developing MVC Views

Module 5
Developing MVC Views
Contents:
Lesson 1: Implementing MVC Views

Lesson 2: Implementing Strongly-Typed MVC Views

Lesson 3: Implementing Partial MVC Views

13

5-1

5-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Implementing MVC Views


Contents:
Questions and Answers

Detailed Demo Steps

Additional Reading

Developing MVC Views

5-3

Questions and Answers


What Is an MVC View?
Question: Where can the view associated with the Sample action method of the Home controller be
located?
Answer: The view associated with the Sample action method of the Home controller can be located
in any of the following locations:
~/Views/Home/Sample.aspx
~/Views/Home/Sample.ascx
~/Views/Shared/Sample.aspx
~/Views/Shared/Sample.ascx
Question: What is the difference between the ViewData property and the TempData property?
Answer: The value of the TempData property persists only from one request to the next.
Question: What is the attribute of the Page directive that is used to identify the master page?
Answer: The MasterPageFile attribute of the Page directive identifies the master page.

What Are HTML Helpers?


Question: What does an HTML helper return?
Answer: An Html helper returns a string of type MvcHtmlString. An MvcHtmlString represents an
HTML-encoded string that should not be encoded again.
Question: Into which categories are the HTML helpers organized?
Answer: These are the categories that Html helpers are organized into:

MvcForm Extensions

Input Extensions

Label Extensions

Link Extensions

Select Extensions

TextArea Extensions

Validation Extensions

5-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating an MVC View
In this demonstration, you will learn how to create an MVC view.
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

5.

Create a new ASP.NET MVC 2 Web Application project, without an associated Unit Test project.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Location box, type
D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

c.

In the Create Unit Test Project dialog box, ensure No, do not create a unit test
project is selected, and then click OK.

Delete the Home\About view.


a.

In Solution Explorer, expand Views, expand Home, right-click About.aspx, and then
click Delete.

b.

In the Microsoft Visual Studio dialog box, click OK.

Create an empty view named About in the Home folder.


a.

In Solution Explorer, right-click Home, point to Add and then click View.

b.

In the Add View dialog box, in the View name box, type About, clear the Create a
strongly-typed view check box, and then click Add.

Build the solution, and fix any errors.

6.

7.

In the MvcApplication1 Microsoft Visual Studio window, on the Build menu, click
Build Solution, or press CTRL+SHIFT+B.

Run the application.


a.

In Solution Explorer, click MvcApplication1.

b.

In the MvcApplication1 Microsoft Visual Studio window, on the Debug menu, click
Start Without Debugging, or press CTRL+F5.

c.

In the Home Page Windows Internet Explorer window, click About.

Close Windows Internet Explorer.

8.

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

In the About Windows Internet Explorer window, click the Close button.

Close Visual Studio 2010.

In the MvcApplication1 Microsoft Visual Studio window, click the Close button.

Developing MVC Views

Additional Reading
What Is an MVC View?
For more information about the ViewPage class, see ViewPage Class.

For more information about the ViewDataDictionary class, see ViewDataDictionary Class.

For more information about the TempDataDictionary class, see TempDataDictionary Class.

What Are HTML Helpers?


For more information about the HtmlHelper class, see HtmlHelper Class.

For more information about rendering a view using HTML helpers, see Rendering a Form in
ASP.NET MVC Using HTML Helpers.

5-5

5-6

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Implementing Strongly-Typed MVC Views


Contents:
Questions and Answers

Detailed Demo Steps

Additional Reading

12

Developing MVC Views

5-7

Questions and Answers


What Is a Strongly-typed View?
Question: From which class does a strongly-typed view inherit?
Answer: A strongly-type view inherits from ViewPage<(Of <(TModel>)>)
Question: What is the easiest way to create a strongly-typed view?
Answer: The easiest way to create a strongly-typed view is by using the Add View dialog box.
Question: What are the advantages of using strongly-typed views?
Answer: The advantages of using strongly-typed views are that the view knows exactly what type of
data it is expecting and Microsoft IntelliSense is available.

5-8

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating a Strongly-typed View
In this demonstration, you will see how to create a strongly-typed MVC view.
1.

Open Microsoft Visual Studio 2010.

2.

3.

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

Create a new ASP.NET MVC 2 Web Application project, without an associated Unit Test project.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project, or press CTRL+SHIFT+N.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET MVC 2 Web Application, in the Name box, type
StronglyTypedView, in the Location box, type D:\Demofiles\CS or D:\Demofiles\VB,
and then click OK.

c.

In the Create Unit Test Project dialog box, ensure No, do not create a unit test
project is selected, and then click OK.

Add a model class named Person to the Models folder.

[Visual C#]
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
}

[Visual Basic]
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Person
<Required()>
<DisplayName("First Name")>
Public Property FirstName As String
<Required()>
<DisplayName("Last Name")>
Public Property LastName As String
<Required()>
Public Property Age As Integer
<Required()>
Public Property Gender As String
End Class

Developing MVC Views

a.

In Solution Explorer, right-click Models, point to Add, and then click Class.

b.

In the Add New Item dialog box, in the Name box, type Person.cs or Person.vb, and
then click Add.

c.

In the Person.cs or Person.vb window, replace the content with the following code.

5-9

[Visual C#]
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public class Person
{
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required]
[DisplayName("Last Name")]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
[Required]
public string Gender { get; set; }
}

[Visual Basic]
Imports System.ComponentModel
Imports System.ComponentModel.DataAnnotations
Public Class Person
<Required()>
<DisplayName("First Name")>
Public Property FirstName As String
<Required()>
<DisplayName("Last Name")>
Public Property LastName As String
<Required()>
Public Property Age As Integer
<Required()>
Public Property Gender As String
End Class

4.

Build the solution, and fix any errors.

5.

6.

In the StronglyTypedView Microsoft Visual Studio window, on the Build menu,


click Build Solution, or press CTRL+SHIFT+B.

Create a strongly-typed view named Person in the Views\Home folder. The view should include
default content for the Create operation.
a.

In Solution Explorer, expand Views, right-click Home, point to Add and then click View.

b.

[Visual C#] In the Add View dialog box, in the View name box, type Person, select the
Create a strongly-typed view check box, in the View data class list, click Person, in
the View content list, click Create, and then click Add.

c.

[Visual Basic] In the Add View dialog box, in the View name box, type Person, select
the Create a strongly-typed view check box, in the View data class list, click
StronglyTypedView.Person, in the View content list, click Create, and then click Add.

Change the TextBox for displaying the Gender property for the model to a DropDownList.

5-10

Developing Web Applications with Microsoft Visual Studio 2010

a.

Replace the following markup and code.

[Visual C#]
<%: Html.TextBoxFor(model => model.Gender) %>

[Visual Basic]
<%: Html.TextBoxFor(Function(model) model.Gender) %>

b.

With the following markup and code.

[Visual C#]
<%: Html.DropDownListFor(model => model.Gender,
(SelectList)ViewData["Gender"]) %>

[Visual Basic]
<%: Html.DropDownListFor(Function(model) model.Gender,
CType(ViewData("Gender"), SelectList)) %>

7.

Add an action method named Person to the HomeController controller in the Controllers
folder.

[Visual C#]
public ActionResult Person()
{
ViewData["Gender"] = new SelectList(new[] { "", "Female",
return View();
}

"Male" });

[Visual Basic]
Public Function Person() As ActionResult
ViewData("Gender") = New SelectList({"", "Female", "Male"})
Return View()
End Function

a.

In Solution Explorer, expand Controllers, and then double-click HomeController.

b.

In the HomeController.cs or HomeController.vb window, in the HomeController


class, type the following code.

[Visual C#]
public ActionResult Person()
{
ViewData["Gender"] = new SelectList(new[] { "", "Female",
return View();
}

[Visual Basic]
Public Function Person() As ActionResult
ViewData("Gender") = New SelectList({"", "Female", "Male"})
Return View()

"Male" });

Developing MVC Views

5-11

End Function

8.

9.

Run the application.


a.

In Solution Explorer, click StronglyTypedView.

b.

In the StronglyTypedView Microsoft Visual Studio window, on the Debug menu,


click Start Without Debugging, or press CTRL+F5.

Navigate directly to the Person view, by using the following route.


Home/Person

In the Home Page Windows Internet Explorer window, in the address bar, append
the following URL, and then press ENTER.

Home/Person

10. Close Internet Explorer.

In the Person Windows Internet Explorer window, click the Close button.

11. Close Visual Studio 2010.

In the StronglyTypedView Microsoft Visual Studio window, click the Close button.

5-12

Developing Web Applications with Microsoft Visual Studio 2010

Additional Reading
What Is a Strongly-typed View?
For more information about the HtmlHelper(TModel) class, see HtmlHelper(TModel) Class.

Developing MVC Views

Lesson 3

Implementing Partial MVC Views


Contents:
Questions and Answers

14

Detailed Demo Steps

15

5-13

5-14

Developing Web Applications with Microsoft Visual Studio 2010

Questions and Answers


What Is a Partial View?
Question: What is the HTML helper that is used to render a partial view?
Answer: Html.RenderPartial is used to render a partial view.
Question: In which type of file does a partial view store its markup?
Answer: A partial view stores its markup in an ASP.NET user control (.ascx file).

Developing MVC Views

5-15

Detailed Demo Steps


Demonstration: Creating a Partial MVC View
In this demonstration, you will see how to create a partial MVC view.
1.

Open Microsoft Visual Studio 2010.

2.

3.

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

Open the StronglyTypedView solution used in the previous demonstration.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\StronglyTypedView\StronglyTypedView.sln or
D:\Demofiles\VB\StronglyTypedView\StronglyTypedView.sln and then click Open.

Add a strongly-typed partial view named Partial to the Views\Home folder, by using the Add
View dialog box. The view must contain default content for a Create view, and the view should
be based on the Person class.
a.

In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.

b.

[Visual C#] In the Add View dialog box, in the View name box, type Partial, select the
Create a partial view (.ascx) and Create a strongly-typed view check boxes, in the
View data class list, click Person, in the View content list, click Create, and then click
Add.
or-

c.

4.

5.

[Visual Basic] In the Add View dialog box, in the View name box, type Partial, select
the Create a partial view (.ascx) and Create a strongly-typed view check boxes, in
the View data class list, click StronglyTypedView.Person, in the View content list,
click Create, and then click Add.

Add an empty view named Create to the Views\Home folder, by using the Add View dialog
box.
a.

In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.

b.

In the Add View dialog box, in the View name box, type Create, clear the Create a
partial view (.ascx) and Create a strongly-typed view check boxes, and then click
Add.

Incorporate the Partial view in the Create view as part of the Content2 Content control, by
using the Html.RenderPartial method.

[Visual C#]
<% Html.RenderPartial("Partial"); %>

5-16

Developing Web Applications with Microsoft Visual Studio 2010

[Visual Basic]
<% Html.RenderPartial("Partial") %>

Add the following code to the Create view, in the Content2 Content control,
immediately after the h2 element.

[Visual C#]
<% Html.RenderPartial("Partial"); %>

[Visual Basic]
<% Html.RenderPartial("Partial") %>

6.

7.

Run the application.


a.

In Solution Explorer, click StronglyTypedView.

b.

In the StronglyTypedView Microsoft Visual Studio window, on the Debug menu,


click Start Without Debugging, or press CTRL+F5.

Navigate directly to the Person view, by using the following route.


Home/Person

In the Home Page Windows Internet Explorer window, in the address bar, append
the following URL, and then press ENTER.

Home/Person

8.

Close Internet Explorer.

9.

In the Person Windows Internet Explorer window, click the Close button.

Close Visual Studio 2010.

In the StronglyTypedView Microsoft Visual Studio window, click the Close button.

Designing for Discoverability

Module 6
Designing for Discoverability
Contents:
Lesson 1: Search Engine Optimization

Lesson 2: Discoverability Files

Lesson 3: Using ASP.NET Routing

12

6-1

6-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Search Engine Optimization


Contents:
Questions and Answers

Detailed Demo Steps

Designing for Discoverability

6-3

Questions and Answers


Overview of Search Engine Optimization
Question: When estimating the effort to complete a site, do you typically include SEO (search engine
optimization) items?
Answer: Will vary.
Question: In which activities have you participated to increase a websites search ranking?
Answer: Will vary.
Question: How did traffic patterns change after you completed SEO activities?
Answer: Will vary.

Components of the IIS SEO Toolkit


Question: Have you encountered a website that did not have an accurate robots.txt file? What
mistakes were made? Did traffic improve once the robots.txt file was fixed?
Answer: Will vary.
Question: Have you encountered a website that did not have an accurate sitemap.xml file? If so,
how did it impact your use and perception of the website?
Answer: Will vary.

Demonstration: Analyzing a Website by Using the IIS SEO Toolkit


Question: When would be the ideal timeframe in a project to run the Site Analysis Tool?
Answer: After initial development and after deployment.
Question: What feature of the report can be used to avoid production issues proactively?
Answer: Violations.

6-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Analyzing a Website by Using the IIS SEO Toolkit
Detailed demonstration steps
Crawling a Website
1.

Open IIS SEO Toolkit.


a.

On the Start menu, point to All Programs, expand IIS 7.0 Extensions, right-click Search Engine
Optimization (SEO) Toolkit 1.0, and then click Run as Administrator.

b.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then click
Yes.

2.

In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysis section, click
Create a new analysis.

3.

In the New Analysis dialog box, in the Name box, type Default Web Site analysis, in the Start URL
box, type http://localhost, and then click OK.

Note: It is possible to crawl any website that is publicly accessible on the Internet.

The New Analysis Dialog Box


Advanced Settings
Maximum Number of Links: Controls the number of unique links to be processed and downloaded
from a website during a crawl. A link is any URL that is used within a pages markup, including hyperlinks,
references to image files, CSS files, and java script files. Increasing this number increases the size of the
reports file, and makes the crawling process run longer.
Maximum Download Size per Link: Controls the number of kilobytes of content to be downloaded per
link. Increasing this number increases the size of the cached content stored by Site Analysis on the local
file system.
Ignore 'nofollow' attribute: The nofollow attribute and the nofollow meta tag are used to tell search
engine crawlers not to follow certain or all hyperlinks in the page. This is a means of protection against
spam in blog comments. If pages on your site use this attribute, the hyperlinks on those pages will not be
processed or analyzed during site analysis. However, links to resources such as images, CSS, and java script
files will still be processed. If it is necessary to analyze the hyperlinks that use this attribute, use this setting
to ignore the nofollow attributes and meta tags.
Ignore 'noindex' meta tag: - Used to tell search engine crawlers not to index the content of the page. If
pages on your site use this meta tag, the content of those pages will not be searched for any violations. If
it is necessary to analyze even the pages that use this attribute, use this setting to ignore the noindex
meta tag.
External Links: Use this drop-down list when your website has sub-domains, or when you want to run an
analysis on a particular directory within a site. This setting controls whether sub-domains and/or
subdirectories should be treated as external or internal links.

Designing for Discoverability

6-5

Edit Feature Settings


Maximum Number of Concurrent Requests: Controls the number of concurrent requests the web
crawler will make.
Reports Directory: Specifies the directory on the local file system where all crawled data and cached
website content is stored.
Note: Two numbers are reported during analysis.
Links Processed: The total number of links that have been crawled and downloaded by the
web crawler.
Total Links: The total number of links found while crawling the website.

Interpreting the Site Analysis Report


In Internet Information Services (IIS) Manager, in the Site Analysis Report section, you can view a
number of pages with report details. To get to the Site Analysis Report section, follow these steps.
1.

2.
3.

Open IIS SEO Toolkit.


a.

On the Start menu, point to All Programs, expand IIS 7.0 Extensions, right-click Search Engine
Optimization (SEO) Toolkit, and then click Run as Administrator.

b.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then click
Yes.

In Internet Information Services (IIS) Manager, in the right pane, in the Site Analysis section, click
View existing reports.
In the Site Analysis pane, you can double-click any of the reports listed.

Note: In the Site Analysis Report section, you can use the vertically placed tabs on the left of
the Dashboard to get to the following information.

Summary Page
The site analysis summary page provides an overview of all SEO-related violations and problems found on
the analyzed website. In addition, it contains a large set of pre-built reports about your site content and
structure.
You can drill down into each individual item in the report by double-clicking it, or by using the View
Group Details command in the context menu. To open a particular report in a separate query page, use
the Open Query context menu command.

Query Page
Opening any of the pre-built reports from the summary page will result in a new query page.
The query page is used to issue queries against the site analysis data that was collected during the crawl
of the website. In the preceding screenshot, the query is used to get all the pages that reference images
without specifying an alt attribute within the img HTML element.
You can perform a set of actions, accessible from the context menu, for each item within the query results
pane. The following actions are as follows:

6-6

Developing Web Applications with Microsoft Visual Studio 2010

View Details: This option opens a dialog box, which can be used to obtain detailed information about the
item. Specifically, you can see the violation details and suggested corrective actions.
In addition, the actual response data is available if you need to investigate the causes of the reported
violation further. For example, if you want to find out where in the response HTML this violation occurred,
choose the Content tab. This opens the response content with the offending section of the markup
highlighted.
View in Browser: If you right-click a URL, you can select View in Browser from the context menu to show
the URL in the browser.
View Pages Linking to This Page: If you right-click a URL, you can also select View Pages Linking to
This Page. This option opens a new query page that shows all the pages on the site that reference the
URL for the selected item. This kind of report is useful when you want to find out which pages may be
affected if you change a particular URL on your site.
View Pages Linked by This Page: This option opens a new query page that shows all the URLs and
resources that the HTML markup for the currently selected URL references.
View Violations in This Page: This option opens a new query page that shows all the violations found on
the page of the selected URL.
View in Hierarchy: This option opens a hierarchy view page that consists of the following parts:

URLs of all pages that lead to the selected page.

The URL of the selected page.

URLs of all the resources and pages referenced by the selected page.

View Routes to this Page: This option opens a new page that displays the 5 shortest unique routes from
the analysis start page to the currently selected page.
Each route is shown with the start page at the bottom and each subsequent page above, with the selected
page on top. This report can be used to analyze how visitors can get to a particular page on your website,
and whether there any unnecessary pages that can be eliminated for users to discover the selected page
more easily.
Word Analysis: This feature can be used to get an idea of the most commonly used words in a pages
content. These can be used as keywords for accurately describing the web page content for search
engines.
The most often used words within a page will be displayed, which can give you an idea of which keywords
to choose for this page. In addition, the texts of links that reference this page are listed at the bottom of
the dialog box. This helps you to check whether the anchor text used within those links accurately
describes the content of the page.

Designing for Discoverability

Lesson 2

Discoverability Files
Contents:
Questions and Answers

Detailed Demo Steps

6-7

6-8

Developing Web Applications with Microsoft Visual Studio 2010

Questions and Answers


What are Robots Files?
Question: Have you ever piloted or tested content in a production environment that you did not
want a search engine to index?
Answer: Will vary.
Question: What are some disadvantages of allowing web crawlers to index content that is not ready
for production?
Answer: Search engines will pick up information that is not ready and direct users to it.

What is the Sitemap File?


Question: When do you usually install a sitemap file?
Answer: At the start of a project.

Designing for Discoverability

6-9

Detailed Demo Steps


Demonstration: Creating a Robots File
Detailed demonstration steps
In this demonstration, you will see how to create a robots.txt file.
1.

Open Internet Information Services (IIS) Manager as an administrator.


a.

On the Start menu, click Control Panel.

b.

In Control Panel, click System and Security, and then click Administrative Tools.

c.

Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.

2.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then press
ENTER.

3.

Select the Default Website.

4.

Open the Search Engine Optimization feature.

5.

In the Connections pane, expand 10264A-GEN-DEV (10264A-GEN-DEV\Admin), expand


Sites, and then click Default Web Site.
In Internet Information Services (IIS) Manager, in the middle pane, in the Management section,
double-click Search Engine Optimization.

View existing rules.

In the Search Engine Optimization pane, in the Robots Exclusion section, click View existing
rules.

Note: Currently there are no rules, and there is no robots.txt file.


6.

Add a sitemap file.


a.

In the Actions pane, in the Sitemap Locations section, click Add Sitemaps.

b.

In the Add Sitemaps dialog box, in the URL Paths list, select the Default Web Site, and then
click OK.

Note: Currently there are is no sitemap file, but this action will create the robots.txt file.
7.

Open the robots.txt file.

In the Actions pane, in the Robots section, click Open Robots.txt File.

Note: The robots.txt file is opened in Notepad. Currently, it holds only a reference to the
sitemap at the default location for the default website.
Following are examples of what you can add to a robots.txt file.

This example disallows all web spiders for the entire site:
# Make changes for all web spiders
User-agent: *

6-10

Developing Web Applications with Microsoft Visual Studio 2010

Disallow: /

The following example disallows a robot named WebSpider from the virtual paths /marketing and
/sales:
# Tell "WebSpider" where it can't go
User-agent: WebSpider
Disallow: /marketing
Disallow: /sales
# Allow all other robots to browse everywhere
User-agent: *
Disallow:

This example allows only a web spider named SpiderOne into a site, while denying all other spiders:
# Allow "SpiderOne" in the site
User-agent: SpiderOne
Disallow:
# Deny all other spiders
User-agent: *
Disallow: /

This last example disallows FrontPage-related paths in the root of your website:
# Ignore FrontPage files
User-agent: *
Disallow: /_borders
Disallow: /_derived
Disallow: /_fpclass
Disallow: /_overlay
Disallow: /_private
Disallow: /_themes
Disallow: /_vti_bin
Disallow: /_vti_cnf
Disallow: /_vti_log
Disallow: /_vti_map
Disallow: /_vti_pvt
Disallow: /_vti_txt

8.

Close Notepad.

9.

Close Internet Information Services (IIS) Manager.

In the robots.txt - Notepad window, click the Close button.


In the Internet Information Services (IIS) Manager window, click the Close button.

10. Close Administrative Tools.

In the Control Panel\System and Security\Administrative Tools window, click the Close
button.

11. Close System and Security.

In the Control Panel\System and Security window, click the Close button.

Demonstration: Creating a Sitemap File


Detailed demonstration steps
In this demonstration, you will see how to create a sitemap file by using the IIS SEO Toolkit extensions.

Designing for Discoverability

6-11

Creating a Sitemap File


1.

Open Internet Information Services (IIS) Manager as an administrator.

On the Start menu, click Control Panel.

2.

In Control Panel, click System and Security, and then click Administrative Tools.

3.

Right-click Internet Information Services (IIS) Manager, and then click Run as administrator.

4.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and then press
ENTER.

5.

Open the Search Engine Optimization feature.

6.

7.

Create a new sitemap for the default website, in a file named Sitemap.xml. Set the change frequency
to daily, do not record the last modified date and time, and set the priority to 1.
a.

In the Search Engine Optimization pane, in the Sitemaps and Sitemap Indexes section, click
Create a new sitemap.

b.

In the Choose Site dialog box, in the Site list, click Default Web Site, and then click OK.

c.

In the Add Sitemap dialog box, in the File Name box, type Sitemap.xml, and then click OK.

d.

In the Add URLs dialog box, in the URL Paths list, click Default Web Site, and then click OK.

Close Internet Information Services (IIS) Manager.

8.

In the Internet Information Services (IIS) Manager window, click the Close button.

Close Administrative Tools.

9.

In the right pane, in the Management Group section, double-click Search Engine
Optimization.

In the Control Panel\System and Security\Administrative Tools window, click the Close
button.

Close System and Security.

In the Control Panel\System and Security window, click the Close button.

6-12

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Using ASP.NET Routing


Contents:
Questions and Answers

13

Detailed Demo Steps

14

Designing for Discoverability

Questions and Answers


How ASP.NET Routing Works
Question: What are the advantages of using routed URLs over standard URLs?
Answer: URLs are simpler and can be easily typed, copy-pasted, or used in search engines.

Demonstration: Using ASP.NET Routing with Web Forms Pages


Question: How can using ASP.NET Routing improve long-term maintenance of a web application?
Answer: Changes to the website can be easily accomplished by updating the routing tables
Question: What is your perception of a website when you get an HTTP 404 error?
Answer: Will vary.

Using ASP.NET Routing with MVC Pages


Question: How does MVC built-in routing improve search engine query results?
Answer: It produces search engine friendly URLs.
Question: How does MVC built-in routing improve the maintainability of a website?
Answer: It is simple to add or move views, by simply modifying the corresponding route.

6-13

6-14

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Using ASP.NET Routing with Web Forms Pages
Detailed demonstration steps
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

Open the WebFormsRouting solution at the following location.


Programming Language

Location

Visual C#

D:\Demofiles\CS

Visual Basic

D:\Demofiles\VB

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open Project, or
press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\WebFormsRouting.sln or D:\Demofiles\VB\WebFormsRouting.sln and
then click Open.

Add reference to the System.Web.Routing assembly.


a.

In Solution Explorer, right-click WebFormsRouting, and then click Add Reference.

b.

In the Add Reference dialog box, click .NET.

c.

In the list, click System.Web.Routing, and then click OK.

Open the Global.asax file.

5.

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

In Solution Explorer, double-click Global.asax.

Import the System.Web.Routing namespace in the Global.asax code file.

At the top of the Global.asax.cs or Global.asax.vb code file, add the following code.
[Visual C#]
using System.Web.Routing;

[Visual Basic]
Imports System.Web.Routing

6.

Add a RegisterRoutes method as shown to the Global class.


[Visual C#]
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"SearchRoute",
// Route name
"search/{searchterm}", // URL with parameters
"~/Search.aspx"
// Web forms page to handle it
);

Designing for Discoverability

[Visual Basic]
Sub RegisterRoutes(ByVal routes As RouteCollection)
' Route name
' URL with parameters
' Web forms page to handle it
routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")
End Sub

In the Global.asax.cs or Global.asax.vb window, in the Global class, add the following code.
[Visual C#]
void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute(
"SearchRoute",
// Route name
"search/{searchterm}", // URL with parameters
"~/Search.aspx"
// Web forms page to handle it
);
}

[Visual Basic]
Private Sub RegisterRoutes(ByVal routes As RouteCollection)
' Route name
' URL with parameters
' Web forms page to handle it
routes.MapPageRoute("SearchRoute", "search/{searchterm}", "~/Search.aspx")
End Sub

7.

Modify the Application_Start method as shown.


[Visual C#]
void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}

[Visual Basic]
Private Sub Application_Start()
RegisterRoutes(RouteTable.Routes)
End Sub

8.

Open the Search.aspx.cs or Search.aspx.vb code file.

9.

In Solution Explorer, right-click Search.aspx, and then click View Code.

Modify the Page_Load method in the Search class as shown.


[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{

6-15

6-16

Developing Web Applications with Microsoft Visual Studio 2010

string searchTerm = "No Search Term specified.";


if (RouteData.Values["searchterm"] != null)
{
searchTerm = "You searched for '" +
RouteData.Values["searchterm"].ToString() + "'";
}

SearchTermLabel.Text = searchTerm;

[Visual Basic]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim searchTerm As String = "No Search Term specified."
If Not RouteData.Values("searchterm") Is Nothing Then
searchTerm = "You searched for '" &
RouteData.Values("searchterm").ToString() & "'"
End If
SearchTermLabel.Text = searchTerm
End If
End Sub

10. Run the application.


a.

In Solution Explorer, click WebFormsRouting.

b.

In the AdventureWorks Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.

11. Navigate directly to the Search page by using the following route.
search/My Search Term

In the Home Page Windows Internet Explorer window, in the address bar, append the
following text.
search/My Search Term

12. Close Windows Internet Explorer.

In the http://localhost:xxxx/search/My%20Search%20Term Windows Internet Explorer


window, click the Close button.

13. Close Visual Studio 2010.

In the RouteConstraints Microsoft Visual Studio window, click the Close button.

Demonstration: Creating Custom Routes


Detailed demonstration steps
1.

Open Microsoft Visual Studio 2010.

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

Designing for Discoverability

2.

3.

Create a new ASP.NET MVC 2 web application named Routes in the D:\Demofiles\CS\Module06 or
D:\Demofiles\VB\Module06 folder, by using the ASP.NET MVC 2 Web Application template.
a.

On the File menu, click New Project.

b.

In the Installed Templates section, expand Visual Basic or Visual C#, and then click Web.

c.

In the list of project types, click ASP.NET MVC 2 Web Application.

d.

In the Name box, type Routes.

e.

In the Location box, type D:\Demofiles\CS\Module06 or D:\Demofiles\VB\Module06, and


then click OK.

f.

In the Create Unit Test Project dialog box, select the No, do not create a unit test project
option, and then click OK.

Open the Global.asax file.

4.

6-17

In the Solution Explorer window, double-click Global.asax.

Add the following route to the RegisterRoutes method as shown.


[Visual C#]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"}
);

[Visual Basic]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} _
)

In the Global.asax.cs or Global.asax.vb window, in the MvcApplication class, in the


RegisterRoutes method, add the following code.
[Visual C#]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"}
);

[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} _
)

6-18

Developing Web Applications with Microsoft Visual Studio 2010

After this code:


[Visual C#]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

[Visual Basic]
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")

5.

6.

Create the AddressController controller.


a.

In the Solution Explorer window, right-click Controllers, point to Add, and then click Controller.

b.

In the Add Controller dialog box, in the Controller Name box, type AddressController, and
then click Add.

Add the List action method to the AddressController class as shown.


[Visual C#]
public ActionResult List(int houseNumber)
{
ViewData["HouseNumber"] = houseNumber.ToString();
}

return View();

[Visual Basic]
Function List(ByVal houseNumber As Integer) As ActionResult
ViewData("HouseNumber") = houseNumber.ToString()
Return View()
End Function

7.

8.

Create the List view in the Views/Address folder.


a.

In the Solution Explorer window, right-click Views, point to Add, and then click New Folder.

b.

In the text box, type Address, and then press ENTER.

c.

In the Solution Explorer window, right-click Address, point to Add, and then click View.

d.

In the Add View dialog box, in the View name box, type List, and then click Add.

Replace the default content of the Content2 Content control in the List view with the following
markup and code, to display the house number requested.
[Visual C#]
<h2>
List</h2>
<h3>
List of houses with number
<%: ViewData["houseNumber"]%></h3>

[Visual Basic]

Designing for Discoverability

6-19

<h2>
List</h2>
<h3>
List of houses with number
<%: ViewData("houseNumber")%></h3>

9.

Run the application.


a.

In Solution Explorer, click Routes.

b.

In the Routes Microsoft Visual Studio window, on the Debug menu, click Start Without
Debugging, or press CTRL+F5.

10. Navigate directly to the Address/List view by using the following route.
Address/123

In the Home Page Windows Internet Explorer window, in the address bar, append the
following text, and then press Enter.
Address/123

Note: A message stating List of houses with number 123 is now shown.
11. Navigate directly to the Address/List view by using the following route.
Address/twentyseven

In the List Windows Internet Explorer window, in the address bar, replace Address/123 with
the following text.
Address/twentyseven

Note: An error message is now shown.


[Visual Basic]
The parameters dictionary contains a null entry for parameter 'houseNumber' of
non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult
List(Int32)' in 'Routes.Routes.AddressController'. An optional parameter must be a
reference type, a nullable type, or be declared as an optional parameter.
[Visual C#]
The parameters dictionary contains a null entry for parameter 'houseNumber' of
non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult
List(Int32)' in 'Routes.Controllers.AddressController'. An optional parameter must
be a reference type, a nullable type, or be declared as an optional parameter.
12. Close Internet Explorer.

In the window The parameters dictionary contains a null entry for parameter
'houseNumber' of non-nullable type Windows Internet Explorer, click the Close button.

6-20

Developing Web Applications with Microsoft Visual Studio 2010

Keep the solution open for the next demonstration.

Demonstration: Creating Route Constraints


Detailed demonstration steps
Use the solution from the previous demonstration.
1.

Modify the Address route in Global.asax as shown to add an integer constraint to the
houseNumber parameter.
[Visual C#]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"},
new {houseNumber = @"\d+"}
);

[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"}, _
New With {.houseNumber = "\d+"} _
)

a.

In the Routes Microsoft Visual Studio window, click Global.asax.cs or Global.asax.vb.

b.

Insert the following code


[Visual C#]
,
new {houseNumber = @"\d+" }

[Visual Basic]
, _
New With {.houseNumber = "\d+"} _

At this location
[Visual C#]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
new {controller="Address", action="List"} <Insert Code Here>
);

[Visual Basic]
routes.MapRoute(
"Address",
"Address/{houseNumber}",
New With {.controller = "Address", .action = "List"} <Insert Code Here>

Designing for Discoverability

6-21

2.

3.

Run the application.


a.

In the Solution Explorer window, click Routes.

b.

In the Routes Microsoft Visual Studio window, on the Debug menu, click Start Without
Debugging, or press CTRL+F5.

Navigate directly to the Address/List view by using the following route.


Address/twentyseven

In the Home Page Windows Internet Explorer window, in the address bar, append the
following text , and then press Enter.
Address/twentyseven

Note: An error message is now shown.


The resource cannot be found.
4.

Close Internet Explorer.

5.

In the window The resource cannot be found. Windows Internet Explorer, click the Close
button.

Close Visual Studio 2010.

In the Routes Microsoft Visual Studio window, click the Close button.

6-22

Developing Web Applications with Microsoft Visual Studio 2010

In the Home Page Windows Internet Explorer window, in the address bar, append
the following text.

blog/12-25-2010

7.

Close Internet Explorer.

8.

In the Blog Archive Windows Internet Explorer window, click the Close button.

Close Visual Studio 2010.

In the RouteConstraints Microsoft Visual Studio window, click the Close button.

Writing Server-Side Code for Web Forms

Module 7
Writing Server-Side Code for Web Forms
Contents:
Lesson 3: Localizing a Web Application

7-1

7-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Localizing a Web Application


Contents:
Detailed Demo Steps

Writing Server-Side Code for Web Forms

7-3

Detailed Demo Steps


Demonstration: Localize a Web Application
In this demonstration, you will see how to localize a web application.
1.

Open Microsoft Visual Studio 2010.

2.

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

Open the Localization solution from the following location.

Programming Language

Location

Visual C#

D:\Demofiles\CS

Visual Basic

D:\Demofiles\VB

3.

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project, or press CTRL+SHIFT+O.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Localization.sln or D:\Demofiles\VB\Localization.sln and then
click Open.

Open Default.aspx.

4.

In Solution Explorer, double-click Default.aspx.

Add a Label server control after the h2 element, with the following attributes.

Attribute

Value

ID

HelloLabel

Text

Hello in English
a.

Place the cursor after the h2 element.

b.

Open the Toolbox, expand Standard, and then double-click Label.

<asp:Label ID="HelloLabel" runat="server" Text="Hello in English"></asp:Label>

5.

Switch to Design view.

6.

Generate local resources by using the Generate Local Resource command on the Tools menu.

7.

In the Localization Microsoft Visual Studio window, on the Tools menu, click
Generate Local Resource.

Switch to Source view.

8.

In the Default.aspx window, click Design.

In the Default.aspx window, click Source.

Notice the newly added attributes, meta:resourcekey, for both the page and the Label server
control.

7-4

Developing Web Applications with Microsoft Visual Studio 2010

9.

Open the App_LocalResources\Default.aspx.resx file.

In Solution Explorer, in the App_LocalResources folder, double-click Default.aspx.resx.

10. Add a new string resource named HeaderText.Text with the value Localization.

In the bottom row of the Resource Editor, in the Name box, type HeaderText.Text, and
in the Value box, type Localization.

11. Add a new string resource named DescriptionText with the value ASP.NET Localization.

In the bottom row of the Resource Editor, in the Name box, type DescriptionText, and
in the Value box, type ASP.NET Localization.

12. Save and close the resource file.


a.

On the File menu, click Save App_LocalResources\Default.aspx.resx, or press


CTRL+S.

b.

In the Default.aspx.resx window, click the Close button.

13. Copy the App_LocalResources\Default.aspx.resx file to a new file named


Default.aspx.de.resx, in the App_LocalResources folder.
a.

In Solution Explorer, in the App_LocalResources folder, right-click Default.aspx.resx,


and then click Copy.

b.

In Solution Explorer, right-click App_LocalResources, and then click Paste.

c.

In Solution Explorer, in the App_LocalResources folder, right-click Copy of


Default.aspx.resx, and then click Rename.

d.

In the text box, type Default.aspx.de.resx, and then press ENTER.

14. Open the App_LocalResources\Default.aspx.de.resx file.

In Solution Explorer, in the App_LocalResources folder, double-click


Default.aspx.de.resx.

15. Localize the string resource named HeaderText.Text with a new value of Lokalisierung.

In the Resource Editor, in the row with a value in the Name column of
HeaderText.Text, in the Value box, type Lokalisierung.

16. Localize the string resource named HelloLabelResource1.Text with a new value of Hallo in
Deutsch.

In the Resource Editor, in the row with a value in the Name column of
HelloLabelResource1.Text, in the Value box, type Hallo in Deutsch.

17. Localize the string resource named PageResource1.Title with a new value of Startseite.

In the Resource Editor, in the row with a value in the Name column of
PageResource1.Title, in the Value box, type Startseite.

18. Localize the string resource named DescriptionText with a new value of ASP.NET
Lokalisierung.

In the Resource Editor, in the row with a value in the Name column of DescriptionText,
in the Value box, type ASP.NET Lokalisierung.

19. Save and close the resource file.

Writing Server-Side Code for Web Forms

a.

On the File menu, click Save App_LocalResources\Default.aspx.de.resx, or press


CTRL+S.

b.

In the Default.aspx.de.resx window, click the Close button.

7-5

20. In Default.aspx, localize the hard-coded Localization text implicitly, by adding a Localize server
control within the h2 element, with the following attributes.
Attribute

Value

ID

HeaderText

meta:resourcekey

HeaderText

a.

Place the cursor within the h2 element, just before the text Localization.

b.

Open the Toolbox, expand Standard, and then double-click Localize.

c.

Modify the Localize server control to appear as follows.

<asp:Localize ID="HeaderText" runat="server"


meta:resourcekey="HeaderText"></asp:Localize>

21. Delete the text Localization from the h2 element.


22. Add two HTML self-closing br elements, and a Literal server control named DescriptionLiteral,
after the HelloLabel server control.
a.

Place the cursor after the HelloLabel element.

b.

Type the following text and then press ENTER.

<br/><br/>

c.

Open the Toolbox, expand Standard, and then double-click Literal.

d.

Modify the Literal server control to appear as follows.

<asp:Literal ID="DescriptionLiteral" runat="server" Text=""></asp:Literal>

23. Make the Literal control explicitly localizable, by adding the following text to the Text property.
<%$ Resources: DescriptionText %>

24. Add a new global resource file named WebResources.resx to the App_GlobalResources folder.
a.

In Solution Explorer, right-click Localization, point to Add, point to Add ASP.NET


Folder, and then click App_GlobalResources.

b.

In Solution Explorer, right-click App_GlobalResources, point to Add, and then click


New Item.

c.

In the Add New Item dialog box, in the middle pane, click Resources File, in the Name
box, type WebResources.resx, and then click Add.

Note: The name of the file is the same as the class that will be generated in the Resources
namespace.
25. Add a new string resource named FooterText with the value This is the footer....

7-6

Developing Web Applications with Microsoft Visual Studio 2010

In the bottom row of the Resource Editor, in the Name box, type FooterText, in the
Value box, type This is the footer....

26. Save and close the resource file.


a.

On the File menu, click Save App_GlobalResources\WebResources.resx, or press


CTRL+S.

b.

In the WebResources.resx window, click the Close button.

27. Copy the App_GlobalResources\WebResources.resx file to a new file named


WebResources.de.resx, in the App_GlobalResources folder.
a.

In Solution Explorer, in the App_GlobalResources folder, right-click


WebResources.resx, and then click Copy.

b.

In Solution Explorer, right-click App_GlobalResources, and then click Paste.

c.

In Solution Explorer, in the App_LocalResources folder, right-click Copy of


WebResources.resx, and then click Rename.

d.

In the text box, type WebResources.de.resx, and then press ENTER.

e.

Open the App_GlobalResources\WebResources.de.resx file.


In Solution Explorer, in the App_GlobalResources folder, double-click
WebResources.de.resx.

28. Localize the string resource named FooterText with a new value of Dies ist der Fuzeile....

In the Resource Editor, in the row with a value in the Name column of FooterText, in
the Value box, type Dies ist der Fuzeile....

29. Save and close the resource file.


a.

On the File menu, click Save App_GlobalResources\WebResources.de.resx, or press


CTRL+S.

b.

In the WebResources.de.resx window, click the Close button.

30. Add an h3 element, and within the h3 element, a Label server control named FooterLabel, after
the DescriptionLiteral server control.
a.

Place the cursor after the DescriptionLiteral element.

b.

Type the following text and the press ENTER.

<h3></h3>
c.

Place the cursor between the opening and closing h3 tags.

d.

Open the Toolbox, expand Standard, and then double-click Label.

e.

Modify the Label server control to appear as follows.

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

31. Modify the Label control, by adding the following text to the Text property.

<%$ Resources:WebResources, FooterText %>


32. Run the application.

Writing Server-Side Code for Web Forms

7-7

a.

In Solution Explorer, click Localization.

b.

In the Localization Microsoft Visual Studio window, on the Debug menu, click Start
Without Debugging, or press CTRL+F5.

33. Verify that Default.aspx Web Form displays text in English.


34. Show the Localization home page in German, by changing the language preference in the
Internet Options dialog box.
a.

In the Home Page - Windows Internet Explorer window, on the Tools menu, click
Internet Options.

b.

In the Internet Options dialog box, click Languages.

c.

In the Language Preference dialog box, click Add.

d.

In the Add Language dialog box, in the Language list, click German (Germany) [deDE], and then click OK.

e.

In the Language Preference dialog box, in the Language list, click German (Germany)
[de-DE], and then click Move up.

35. In the Language Preference dialog box, click OK.


36. In the Internet Options dialog box, click OK.
37. Refresh the page in Windows Internet Explorer.

In the Home Page Windows Internet Explorer window, press F5.

Note: The page should now be shown in German.


38. Close Internet Explorer.

In the Home Page Windows Internet Explorer window, click the Close button.

39. Close Visual Studio 2010.

In the Localization Microsoft Visual Studio window, click the Close button.

Optimizing Data Management for Web Forms

Module 8
Optimizing Data Management for Web Forms
Contents:
Lesson 1: Managing Data by Using LINQ to Entities

Lesson 2: Using Data Source Controls

Lesson 3: Using ASP.NET Dynamic Data

11

8-1

8-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Managing Data by Using LINQ to Entities


Contents:
Questions and Answers

Detailed Demo Steps

Additional Reading

Optimizing Data Management for Web Forms

8-3

Questions and Answers


Overview of LINQ to Entities
Question: Which infrastructure does LINQ to Entities queries use for interacting with the Entity Data
Model as CLR objects?
Answer: LINQ to Entities queries use the Object Services infrastructure for interacting with the Entity
Data Model as CLR objects.

Overview of ADO.NET Entity Framework Object Services


Question: What are POCO entities?
Answer: POCO entities are plain-old CLR object types.

The Entity Data Model


Question: What is the first step in creating an Entity Data Model?
Answer: You must first define the entities and the relationships, if any, in a design schema.

Demonstration: Creating an Entity Data Model


Question: What does it mean to pluralize or singularize generated object names?
Answer: It means that English-language rules are used to make all EntityType names singular, and
all EntitySet names plural, and then for NavigationProperty, for each that returns at most one
entity, make the name singular; for each that returns more than one entity, make the name plural.

Object Oriented Programming Using LINQ to Entities


Question: What is the first step when you want to use an Entity Data Model from your code?
Answer: You need to create an instance of the ObjectContext derived type.

CRUD Operations Using LINQ to Entities


Question: Which method is used to submit local changes to the database?
Answer: The SaveChanges method is used to submit local changes to the database.

8-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating an Entity Data Model
This demonstration shows you how to create an Entity Data Model.
1.

Open Microsoft Visual Studio 2010.

2.

3.

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

Open the EDM solution from the D:\Demofiles\VB or D:\Demofiles\CS folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type D:\Demofiles\VB\EDM.sln
or D:\Demofiles\CS\EDM.sln, and then click Open.

Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx.


a.

In Solution Explorer, right-click EDM, point to Add, and then click New Item.

b.

In the Add New Item - EDM dialog box, in the left pane, click Data, and then in the
middle pane, click ADO.NET Entity data Model.

c.

In the Name box, type AdventureWorks.edmx, and then click Add.

d.

In the Entity Data Model Wizard, on the Choose Model Contents page, click
Generate from database, and then click Next.

e.

On the Choose Your Data Connection page, click New Connection.

f.

If the Choose Data Source dialog box opens, in the Data source list, click Microsoft
SQL Server, and then click Continue.

g.

In the Connection Properties dialog box, in the Server name box, type 10264A-GENDEV\SQLEXPRESS, in the Select or enter a database name box, type
AdventureWorksLT2008R2, and then click OK.

h.

In the Entity Data Model Wizard, on the Choose Your Data Connection page, view
the updated settings, derived from the selected database, and then click Next.

i.

On the Choose Your Database Objects page, in the Which database objects do you
want to include in your model? list, expand Tables, select the Tables check box, clear
the BuildVersion (dbo) check box, and then click Finish.

Note: If the Pluralize or singularize generated object names check box is selected, the wizard
uses English-language rules for singulars and plurals and does the following: makes all
EntityType names singular and all EntitySet names plural; and for NavigationProperty, for
each that returns at most one entity, makes the name singular, and for each that returns more
than one entity, makes the name plural.
If the Include foreign key columns in the model check box is selected, the wizard generates
properties on entity types that correspond to foreign key columns in the database.
j.
4.

Review the entity properties.

In the AdventureWorks.edmx window, click the Customer entity, and then show the
Properties window.

Optimizing Data Management for Web Forms

8-5

Notice how Entity Set Name property is plural (Customers), and the Name property is singular
(Customer).

5.

a.

Review the mapping.

b.

In the AdventureWorks.edmx window, click and possibly expand the Mapping Details
- Customer window.

c.

Under Column Mappings, in particular, observe how the NameStyle SQL Server bit
column is mapped to a .NET Framework Boolean/bool data type.

Close the ADO.NET Entity Data Model item.

6.

In the AdventureWorks.edmx window, click the Close button.

Close Visual Studio 2010.


a.

In the EDM Microsoft Visual Studio window, click the Close button.

b.

In the Microsoft Visual Studio dialog box, click Yes.

8-6

Developing Web Applications with Microsoft Visual Studio 2010

Additional Reading
Overview of LINQ to Entities
For more information about the ADO.NET Entity Framework, see ADO.NET Entity Framework.

Overview of ADO.NET Entity Framework Object Services


For more information about POCO entities and POCO proxies, see Working with POCO Entities
(Entity Framework).

For more information about the self-tracking entities, see Working with Self-Tracking Entities
(Entity Framework).

For more information about Entity SQL, see Entity SQL Overview.

The Entity Data Model


For more information about the Entity Data Model specification, see EDM Specifications.

Optimizing Data Management for Web Forms

Lesson 2

Using Data Source Controls


Contents:
Questions and Answers

Additional Reading

8-7

8-8

Developing Web Applications with Microsoft Visual Studio 2010

Questions and Answers


Types of Data Source Controls
Question: Which data source control should you use for managing site navigation?
Answer: You should you use the SiteMapDataSource control for managing site navigation.

Capabilities of Data Source Controls


Question: Which property of the LinqDataSource control should you set to enable sorting?
Answer: You should set the AllowSorting property to a value of true to enable sorting.

Advanced GridView Control Techniques


Question: Which XML element is used for customizing the display of an empty data source in the
GridView control?
Answer: You use the EmptyDataTemplate element to customize the display of an empty data
source in the GridView control.

Walkthrough: Creating a GridView TemplateField


Question: Which dialog box can be used to create a TemplateField object for the GridView control?
Answer: You use the Fields dialog box to create a TemplateField object for the GridView control.

How to Use the ListView and DetailsView Controls


Question: Which ListView control template element do you use to specify the appearance for an
item that is currently being edited?
Answer: The EditItemTemplate is used to specify the appearance for the item currently being
modified i n a ListView control.

Using the Microsoft Chart Control


Question: Where in Visual Studio 2010 can you find the Chat control?
Answer: The Chart control can be found on the Data tab of the Toolbox in Visual Studio 2010.

Optimizing Data Management for Web Forms

8-9

Additional Reading
Types of Data Source Controls
For more information about the AccessDataSource control, see AccessDataSource Web Server
Control Overview.

For more information about the ObjectDataSource control, see ObjectDataSource Web Server
Control Overview.

For more information about the SiteMapDataSource control, see SiteMapDataSource Web
Server Control Overview.

For more information about the SqlDataSource control, see SqlDataSource Web Server Control
Overview.

For more information about the XmlDataSource control, see XmlDataSource Web Server Control
Overview.

Capabilities of Data Source Controls


For more information about binding by using data source controls, see Binding to Data Using a
Data Source Control.

For more information about sorting by using data source controls, see Sorting Data with Data
Source Controls.

For more information about filtering by using data source controls, see Filtering Data Using
Data Source Controls.

For more information about filtering by using the XmlDataSource control, see Filtering Data
Using the XmlDataSource Control.

For information on the types of parameters that can be used in the FilterParameters collection,
see Using Parameters with Data Source Controls.

Advanced GridView Control Techniques


For more information about the PagerSettings class, see PagerSettings Class.

How to Use the ListView and DetailsView Controls


For more information about the ListView control, see ListView Web Server Control Overview.

8-10

Developing Web Applications with Microsoft Visual Studio 2010

For more information about the DetailsView control, see DetailsView Web Server Control
Overview.

Using the Microsoft Chart Control


For some samples of how to use the Microsoft Chart controls, see Samples Environment for
Microsoft Chart Controls.

Optimizing Data Management for Web Forms

Lesson 3

Using ASP.NET Dynamic Data


Contents:
Questions and Answers

12

Detailed Demo Steps

13

Additional Reading

16

8-11

8-12

Developing Web Applications with Microsoft Visual Studio 2010

Questions and Answers


What Is ASP.NET Dynamic Data?
Question: What does scaffolding do in the context of ASP.NET Dynamic Data?
Answer: Scaffolding is used to enhance the existing ASP.NET web forms page framework by
dynamically displaying pages based on the data and the metadata exposed by the data model.

Scaffolding Feature of ASP.NET Dynamic Data


Question: What is the ScaffoldColumn attribute used for?
Answer: It is used to show or hide a column/field in the UI.

Routing Feature of ASP.NET Dynamic Data


Question: In which file is ASP.NET Dynamic Data routing defined?
Answer: ASP.NET Dynamic Data routing is defined in the global application file.

Demonstration: Creating an ASP.NET Dynamic Data Web Application


Question: What is the RegisterContext method used for?
Answer: The RegisterContext method is used for registering the data or object context.

Optimizing Data Management for Web Forms

8-13

Detailed Demo Steps


Demonstration: Creating an ASP.NET Dynamic Data Web Application
Perform the following step to create and customize the ASP.NET Dynamic Data web application.
1.

Open Visual Studio 2010.

2.

3.

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

Create a web application by using the New Project dialog box.


a.

On the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.

c.

In the middle pane, click ASP.NET Dynamic Data Entities Web Application.

d.

In the Name box, type DDWebApp, in the Location box, type D:\Demofiles\VB or
D:\Demofiles\CS, and then click OK.

Add an ADO.NET Entity Data Model project item named AdventureWorks.edmx.


a.

In Solution Explorer, right-click DDWebApp, point to Add, and then click New Item.

b.

In the Add New Item - DDWebApp dialog box, in the left pane, click Data, and then in
the middle pane, click ADO.NET Entity data Model.

c.

In the Name box, type AdventureWorks.edmx, and then click Add.

4.

In the Entity Data Model Wizard, on the Choose Model Contents page, click Generate from
database, and then click Next.

5.

On the Choose Your Data Connection page, click New Connection.

6.

In the Connection Properties dialog box, in the Server name box, type 10264A-GENDEV\SQLEXPRESS, in the Select or enter a database name box, type
AdventureWorksLT2008R2, and then click OK.

7.

In the Entity Data Model Wizard, on the Choose Your Data Connection page, click Next.

8.

On the Choose Your Database Objects page, in the Which database objects do you want to
include in your model? list, expand Tables, select the Tables check box, clear the BuildVersion
(dbo) check box, and then click Finish.

9.

Save and close the AdventureWorks.edmx file.


a.

On the File menu of Visual Studio 2010, click Save AdventureWorks.edmx.

b.

In the AdventureWorks.edmx window, click the Close button.

10. In the Global.asax.vb or Global.asax.cs file, add context registration to the RegisterRoutes
procedure.

[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities),
New ContextConfiguration() With {.ScaffoldAllTables = True})

8-14

Developing Web Applications with Microsoft Visual Studio 2010

[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new
ContextConfiguration()
{
ScaffoldAllTables = true
});

In the Global.asax.vb or Global.asax.cs window, add the following code at the top of to
the RegisterRoutes procedure.

[Visual Basic]
DefaultModel.RegisterContext(GetType(AdventureWorksLT2008R2Entities),
New ContextConfiguration() With {.ScaffoldAllTables = True})

[Visual C#]
DefaultModel.RegisterContext(typeof(AdventureWorksLT2008R2Entities), new
ContextConfiguration()
{
ScaffoldAllTables = true
});

Note: Point out that this will register the Entity Data model object context for use by using the
Dynamic Data field, and enable the automatic scaffolding of the data model.
11. Save and close the Global.asax.vb or Global.asax.cs file.
a.

On the File menu of Visual Studio 2010, click Save Global.asax.vb or Save
Global.asax.cs.

b.

In the Global.asax.vb or Global.asax.cs window, click the Close button.

12. Build and run the web application.

On the Debug menu of Visual Studio 2010, click Start Without Debugging.
The page displayed in the browser displays a list of the tables you added to the data
model.

13. Test the web application for the Dynamic Data functionality and view some of the dynamically
generated pages.
a.

In the Dynamic Data Site Windows Internet Explorer window, click Addresses.
The page displays the List view that contains the data from the Addresses table.

b.

In the Addresses - Windows Internet Explorer window, click Details, to the left of an
address.
The page displays the Details view that contains the data for the selected row from the
Addresses table.

c.

In the Addresses - Windows Internet Explorer window, click Show all items, and then
click PostalCode.
The page displays the List view that contains the data of addresses, sorted by postal
code.

Optimizing Data Management for Web Forms

d.

In the Addresses - Windows Internet Explorer window, in the first row, under
CustomerAddresses, click View CustomerAddresses.
The page displays the List view that contains the data of customer addresses.

e.

In the Address list, click All.

f.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the


page, click Insert new item to create a new customer address.

g.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the


page, click Insert, and view the smart validation that has been added to the required
fields, and then click Cancel.
The page displays the List view that contains the data from the CustomerAddresses
table. This is the default view and the one you are returned to, after cancelling.

h.

In the CustomerAddresses - Windows Internet Explorer window, to the left of a


customer address, click Edit to modify a customer address.
The page displays the Edit view that contains the data for the selected row from the
CustomerAddresses table.

i.

In the CustomerAddresses - Windows Internet Explorer window, at the end of the


page, click Cancel to cancel the edit operation.

14. Close Windows Internet Explorer.

In the CustomerAddresses Windows Internet Explorer window, click the Close


button.

15. Close Visual Studio 2010.

In the DDWebApp Microsoft Visual Studio window, click the Close button.

8-15

8-16

Developing Web Applications with Microsoft Visual Studio 2010

Additional Reading
What Is ASP.NET Dynamic Data?
For more information about how the data model represents the information in a database and
how the objects in the database are related to each other, see ASP.NET Dynamic Data Model
Overview.

For more information about the DynamicControl control, see DynamicControl Class.

For more information about the DynamicField control, see the DynamicField Class.

Scaffolding Feature of ASP.NET Dynamic Data


For more information about how the MetaModel.RegisterContext method registers the data
context with the meta model, see MetaModel.RegisterContext Method.

For more information about how the ContextConfiguration class provides information for a
data-context instance to allow customization, see ContextConfiguration Class.

For more information about how the MetadataTypeAttribute class specifies the metadata class
to associate with a data model class, see MetadataTypeAttribute Class.

For more information about page template customization, see How to: Customize the Layout of
an Individual Table By Using a Custom Page Template.

For more information about entity template customization, see Walkthrough: Customizing Table
Layout Using Entity Templates.

For more information about field template customization, see How to: Customize ASP.NET
Dynamic Data Default Field Templates.

For more information about filter template customization, see Walkthrough: Filtering Rows in
Tables That Have a Parent-Child Relationship.

Routing Feature of ASP.NET Dynamic Data


For more information about ASP.NET Routing, see ASP.NET Routing.

Demonstration: Creating an ASP.NET Dynamic Data Web Application


For more information about how to create a data-driven website with minimal or no additional
code, see the Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

Module 9
Ensuring Quality by Debugging, Unit Testing, and
Refactoring
Contents:
Lesson 1: Debugging and Refactoring Code

Lesson 2: Unit Testing Code

Lesson 4: Test-Driven Development

12

9-1

9-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Debugging and Refactoring Code


Contents:
Question and Answers

Detailed Demo Steps

Ensuring Quality by Debugging, Unit Testing, and Refactoring

Question and Answers


Overview of Debugging Using Visual Studio 2010 Debugging Tools
Question: What percentage of your time development do you spend debugging?
Answer: Will vary.
Question: Without a debugger what is another way to debug an application?
Answer: Writing code that logs errors or information.

What Is Refactoring?
Question: What problems have you encountered by refactoring code without the use of a tool?
Answer: Will vary, but maybe not all instances of an object have been renamed.
Question: What percentage of your development time do you spend refactoring code?
Answer: Will vary, but developers who practice TDD, will generally refactor more.
Question: What third-party tools have you used to accomplish refactoring?
Answer: Will vary.

9-3

9-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Enabling Debugging of a Web Application
In this demonstration, you will see how to enable debugging of a web application.
1.

Open Microsoft Visual Studio.

2.

3.

Create a new ASP.NET web application by using the New Project dialog box.
a.

On the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual Basic or Visual C#.

c.

In the middle pane, click ASP.NET Web Application.

d.

In the Name box, type DebugWebApp, in the Location box, type D:\Demofiles\VB or
D:\Demofiles\CS, and then click OK.

Build the project.

4.

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

In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.

Open the Web.config file.

In Solution Explorer, double-click Web.config.

5.

Navigate to the self-closing system.web element and notice the attributes and values in the
compilation tag.

6.

In Solution Explorer, right-click DebugWebApp, and then click Properties.

7.

Open the Web page.

In the Properties Designer, click Web.

8.

Examine the various options on the Web page.

9.

In the Debuggers section, ensure the ASP.NET check box is selected.

10. Close the Properties Designer.

In the DebugWebApp window, click the Close button.

11. Close Microsoft Visual Studio 2010.

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

Demonstration: Extract Method Refactoring


In this demonstration, you will learn how to extract a method from existing code. The solution from the
Enable Debugging of a Web Application demonstration is being used.
1.

Open Microsoft Visual Studio.

2.

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

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

3.

a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

Open Default.aspx in Code view.

4.

9-5

In Solution Explorer, right-click Default.aspx and then click View Code.

In the Page_Load method, type in the following code:

[Visual C#]
protected void Page_Load(object sender, EventArgs e)
{
var i = 1;
var j = 2;
var answer = i + j;
}

5.

Select the three lines of code you just added.

6.

Right-click the selection, point to Refactor, and then click Extract Method.

7.

In the Extract Method dialog box, in the New method name box, type Add, and then click OK.
Note: The code has been extracted into a new method, and the function has been called in its
place.

8.

Build the project.

9.

In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click Build
DebugWebApp.

Close Microsoft Visual Studio 2010.

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

Demonstration: Encapsulate Field Refactoring


In this demonstration, you will see how to encapsulate a field. The solution from the Enable Debugging
of a Web Application demonstration is being used.
1.

Open Microsoft Visual Studio.

2.

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

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

3.

In Solution Explorer, right-click DebugWebApp, point to Add, and then click Class.

4.

In the Add New Item DebugWebApp dialog box, in the Name box, type Person, and then
click Add.

9-6

Developing Web Applications with Microsoft Visual Studio 2010

5.

Create a single private variable named name, by adding the following code

[Visual C#]
public class Person
{
private string name;
}

6.

In the Person.cs window, right-click name, point to Refactor, and then click Encapsulate Field.

7.

In the Encapsulate Field dialog box, click OK.

8.

In the Preview Reference Changes - Encapsulate Field dialog box, click Apply.
Note: The new property with accessors has been created.

9.

Build the project.

In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.

10. Close Microsoft Visual Studio 2010.

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

Demonstration: Extract Interface Refactoring


In this demonstration, you will see how to extract an interface from an existing class. The solution from the
Enable Debugging of a Web Application demonstration is being used.
1.

Open Microsoft Visual Studio.

2.

3.

Open the DebugWebApp solution from the D:\Demofiles\CS\DebugWebApp folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\DebugWebApp\DebugWebApp.sln, and then click Open.

Open the Person.cs file.

4.

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

In Solution Explorer, double-click Person.cs.

Add the age member variable, Age property, and Hire method to the Person class.

[Visual C#]
public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int age;
public int Age

Ensuring Quality by Debugging, Unit Testing, and Refactoring

{
get { return age; }
set { age = value; }
}
public void Hire()
{
// implementation Code
}
}

In the Person.cs window, in the Person class, append the following code.

[Visual C#]
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public void Hire()
{
// implementation Code
}

5.

Right-click Person, point to Refactor, and then click Extract Interface.

6.

In the Extract Interface dialog box, select the Age, Hire(), and Name check boxes, and then
click OK.
Note: The new interface is now created in a new file.

7.

Display the Person.cs file, and notice how the class now implements the new interface.

8.

Build the project.

9.

In the DebugWebApp Microsoft Visual Studio window, click Person.cs.

In the DebugWebApp Microsoft Visual Studio window, on the Build menu, click
Build DebugWebApp.

Close Microsoft Visual Studio 2010.

In the DebugWebApp - Microsoft Visual Studio window, click the Close button.

9-7

9-8

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Unit Testing Code


Contents:
Question and Answers

Detailed Demo Steps

10

Ensuring Quality by Debugging, Unit Testing, and Refactoring

Question and Answers


What Is Unit Testing?
Question: Have you ever isolated an error in an integrated module, and then applied a fix?
Answer: Will vary.
Question: What percentage of your development time is spent writing tests?
Answer: Will vary.

Optional Unit Test Steps


Question: How can unit test help you document code?
Answer: Will vary.
Question: Which third-party tools have you used to write unit tests?
Answer: Will vary.

9-9

9-10

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating and Running a Unit Test
In this demonstration, you will see how to create and run a unit test.
1.

Open Microsoft Visual Studio.

2.

3.

Open the UnitTest solution from the D:\Demofiles\CS or D:\Demofiles\VB folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\UnitTest.sln or D:\Demofiles\VB\UnitTest.sln, and then click Open.

Open the Person.cs or Person.vb file.

4.

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

In Solution Explorer, double-click Person.cs or Person.vb.

Modify the Age property as follows:

[Visual C#]
public int Age
{
get { return personAge; }
set
{
if (value < 21)
throw new Exception("Age must be greater than 21");
personAge = value;
}
}

[Visual Basic]
Public Property Age As Integer
Get
Return personAge
End Get
Set(ByVal value As Integer)
If value < 21 Then
Throw New Exception("Age must be greater than 21")
End If
personAge = value
End Set
End Property

5.

Right-click anywhere in the code for the Age property, and then click Create Unit Tests.

6.

In the Create Unit Tests dialog box, ensure the Age check box is selected, and then click OK.

7.

In the New Test Project dialog box, click Create.


Note: Notice the new project created for unit testing.

8.

In the open PersonTest.cs or PersonTest.vb file, review the AgeTest test method.

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9.

Change the declaration code for the expected local variable as follows.

[Visual C#]
int expected = 25;

[Visual Basic]
Dim expected As Integer = 25

10. Delete the following code.

[Visual C#]
Assert.Inconclusive("Verify the correctness of this test method.");

[Visual Basic]
Assert.Inconclusive("Verify the correctness of this test method.")

11. Right-click the AgeTest method declaration, and then click Run Tests.
Note: In the Test Results window, notice the AgeTest test passed.
12. Change the declaration code for the expected local variable as follows.

[Visual C#]
int expected = 2;

[Visual Basic]
Dim expected As Integer = 2

13. Right-click the AgeTest method declaration, and then click Run Tests.
Note: In the Test Results window, notice the AgeTest test failed.
14. Close Microsoft Visual Studio 2010.

In the UnitTest - Microsoft Visual Studio window, click the Close button.

9-11

9-12

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 4

Test-Driven Development
Contents:
Question and Answers

13

Ensuring Quality by Debugging, Unit Testing, and Refactoring

9-13

Question and Answers


Advantages of Test-Driven over Traditional Development
Question: What obstacles do you envision when transitioning from traditional development to testdriven development?
Answer: Will vary, but could include an increased learning curve, and longer development time.
Question: For what percentage of your code do you write unit tests?
Answer: Will vary.

The Test-Driven Development Process


Question: Have you ever authored tests as part of requirements gathering?
Answer: Will vary.
Question: How does authoring tests before development change your mindset?
Answer: Will vary.
Question: What design considerations will you need to make to accomplish test-driven
development?
Answer: Will vary.

Securing a Web Application

Module 10
Securing a Web Application
Contents:
Lesson 1: Configuring Authentication

Lesson 2: Configuring ASP.NET Membership

Lesson 3: Managing Authorization by Using ASP.NET Roles

10

10-1

10-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Configuring Authentication
Contents:
Question and Answers

Detailed Demo Steps

Securing a Web Application

10-3

Question and Answers


IIS Authentication
Question: What is the difference between Basic authentication and Windows authentication?
Answer: Basic authentication requires the username and password to be submitted using clear text,
whereas Windows authentication uses the credentials of the user logged on to the network.

How to Configure Forms Authentication


Question: Which authentication method allows the use of custom credentials in a web application?
Answer: Forms authentication allows the developer to set custom authentication for the application.
Using forms authentication, the user can be validated against any data source.

10-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Configuring IIS Authentication
Select a default Website in Internet Information Services (IIS) Manager
1.

Open Internet Information Services (IIS) Manager as an administrator.


a.

On the Start menu of 10264A-GEN-DEV, point to Administrative Tools, right-click


Internet Information Services (IIS) Manager, and then click Run as administrator.

b.

In the User Account Control dialog box, in the Password box, type Pa$$w0rd, and
then click Yes.

2.

In Internet Information Services (IIS) Manager, in the left pane, expand 10264-GEN-DEV (10264GEN-DEV\Admin), and then expand Sites.

3.

Click Default Web Site, and notice the available options in the right pane.

Configure anonymous authentication


1.

In the Authentication pane, in the IIS section, double-click Authentication.

2.

Right-click Anonymous Authentication and then click Enable or Disable to enable or disable
anonymous authentication for the selected web application.

3.

Right-click Anonymous Authentication and then click Edit to edit the credentials used with
anonymous authentication.

4.

Click Cancel in the Edit Anonymous Authentication Credentials dialog box.

Configure basic authentication


1.

In the Authentication pane, in the IIS section, double-click Authentication.

2.

Right-click Basic Authentication and then click Enable or Disable to enable or disable basic
authentication for the selected web application.

3.

Right-click Basic Authentication and then click Edit to edit the default domain or realm used
with basic authentication. The default domain is used to specify the domain against which users
are authenticated by default. The realm, a DNS domain name or address, uses the credentials that
have been authenticated against as the default domain.

4.

Click Cancel in the Edit Basic Authentication Settings dialog box.

Configure digest authentication


1.

In the Authentication pane, in the IIS section, double-click Authentication.

2.

Right-click Digest Authentication and then click Enable or Disable to enable or disable Digest
authentication for the selected web application.
Note: The 10264A-GEN-DEV machine is not joined to a domain, so it is not possible to enable
Digest authentication.

3.

Right-click Digest Authentication and then click Edit to edit the realm used with Digest
authentication. The realm, a DNS domain name or address, uses the credentials that have been
authenticated against as the internal Windows domain.

4.

Click Cancel in the Edit Digest Basic Authentication Settings dialog box.

Securing a Web Application

10-5

Configure Windows authentication


1.

In the Authentication pane, in the IIS section, double-click Authentication.

2.

Right-click Windows Authentication and then click Enable or Disable to enable or disable
Windows authentication for the selected web application.

3.

Right-click Windows Authentication and then click Advanced Settings to configure Extended
Protection and enable or disable kernel-mode authentication. Extended Protection enhances the
protection and handling of credentials when authenticating network connections by using
Windows authentication.

4.

Click Cancel in the Advanced Settings dialog box.

10-6

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Configuring ASP.NET Membership


Contents:
Question and Answers

Detailed Demo Steps

Securing a Web Application

10-7

Question and Answers


What Is ASP.NET Membership?
Question: What benefits are gained by using the provider pattern for the Membership configuration?
Answer: ASP.NET Membership API uses the provider model to plug in Membership providers. This
enables the developers to create their own provider model and use that as the Membership module.

Demonstration: Managing Users by Using ASP.NET Membership


Question: Does the ASP.NET Web Site Administration Tool edit the root Web.config?
Answer: Yes, the ASP.NET Web Site Administration Tool edits the root Web.config file.

How to Implement the Login Control


Question: How do you set up a default provider for ASP.NET Membership?
Answer: You set the value of the defaultProvider attribute of the membership opening tag in the
Web.config file.

10-8

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Managing Users by Using ASP.NET Membership
In this demonstration, you will learn how to manage ASP.NET Membership users by using the ASP.NET
Web Site Administration Tool.
1.

Open Microsoft Visual Studio 2010.

2.

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

Create a new ASP.NET web Application named Module10 in the D:\Demofiles\CS or


D:\Demofiles\VB folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type Module10, in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

3.

In Solution Explorer, click Module10.

4.

Build the solution.

5.

On the Build menu, click Build Solution, or press CTRL+SHIFT+B.

In Solution Explorer, click the ASP.NET Configuration button.


Note: The Web Site Administration Tool opens in Windows Internet Explorer. On the Home
page, you find the following options.

6.

In the Web Site Administration Tool, on the Home page, click Security.
Note: On the Security page, you find the following options.

7.

On the Security page, click Create user.

8.

In the Create User section, in the User Name box, type student, in the Password box, type
Pa$$w0rd, in the Confirm Password box, type Pa$$w0rd, in the E-mail box, type
student@adventureworks.com, and then click Create User.

9.

Close the ASP.NET Web Site Administration Tool.

In the ASP.NET Web Site Administration Tool window, click the Close button.

Securing a Web Application

10. Open the App_Data folder in Windows Explorer, by using Solution Explorer.

In Solution Explorer, right-click App_Data, and then click Open Folder in Windows
Explorer.

11. Notice the new database, ASPNETDB.MDF, and the corresponding log file, aspnetdb_log.ldf,
have been created in the App_Data folder.
12. Close Windows Explorer.

In the D:\Demofiles\CS\Module10\App_Data or
D:\Demofiles\VB\Module10\App_Data window, click the Close button.

13. Close Visual Studio 2010.

In the Module10 Microsoft Visual Studio window, click the Close button.

10-9

10-10

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Managing Authorization by Using ASP.NET Roles


Contents:
Question and Answers

11

Detailed Demo Steps

12

Securing a Web Application

10-11

Question and Answers


What Are ASP.NET Roles?
Question: Where are roles kept?
Answer: The roles are kept in the aspnet_Roles table. The aspnet_Roles table is created by running
the ASP.NET configuration as explained in demonstration Managing ASP.NET Roles. The roles
assigned to the user are kept in the aspnet_UserInRoles table.

10-12

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Managing ASP.NET Roles
In this demonstration, you will learn how to use the Web.config file and the Roles API to restrict users
from accessing unauthorized resources.
1.

Open Microsoft Visual Studio 2010.

2.

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

Open the Module10 solution from the D:\Demofiles\CS\Module10\Module10.sln or


D:\Demofiles\VB\Module10\Module10.sln folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module10\Module10.sln or
D:\Demofiles\VB\Module10\Module10.sln, and then click Open.

3.

In Solution Explorer, click Module10.

4.

Build the solution.

On the Build menu, click Build Solution, or press CTRL+SHIFT+B.

5.

In Solution Explorer, click the ASP.NET Configuration button.

6.

In the Web Site Administration Tool, on the Home page, click Security.

7.

On the Security page, click Enable Roles.

8.

Click Create or Manage roles.

9.

In the New role name box, type admin, and then click Add Role.

Note: The role is now created.


10. Close the ASP.NET Web Site Administration Tool.

In the ASP.NET Web Site Administration Tool window, click the Close button.

11. Close Visual Studio 2010.

In the Module10 Microsoft Visual Studio window, click the Close button.

Applying Master Pages and CSS

Module 11
Applying Master Pages and CSS
Contents:
Lesson 1: Applying Master Pages

Lesson 2: Applying CSS, Skins, and Themes

11-1

11-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Applying Master Pages


Contents:
Question and Answers

Detailed Demo Steps

Applying Master Pages and CSS

11-3

Question and Answers


Challenges in Providing a Consistent UI
Question: What are some examples of inconsistent UI issues that you have experienced with other
web applications, and how did it impact your use of the application?
Answer: May vary.
Question: How could those issues have been addressed to provide a consistent UI?
Answer: May vary.

What is a Master Page?


Question: How can master pages help you create a consistent UI?
Answer: Master pages act as templates for Web Forms, and help you create and maintain the basic
content of a Web Forms page.

Demonstration: Using a Master Page in Web Forms and MVC View Pages
Question: What ideas came to mind during this demonstration on using master pages?
Answer: May vary.

What are Nested Master Pages?


Question: What scenarios, in your experience, could have benefitted from using nested master
pages?
Answer: May vary.

The Master Page Event Model and Relationships


Question: What ideas came to mind when thinking of how pages and master pages can interact?
Answer: May vary.
Question: What concerns would you have about implementing this interaction?
Answer: May vary.

11-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating a Master Page
Creating a master page
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

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

Create a new ASP.NET web application named NewMasterPage in the D:\Demofiles\CS or


D:\Demofiles\VB folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type
NewMasterPage, in the Location box, type D:\Demofiles\CS or D:\Demofiles\VB,
and then click OK.

Create a new master page named SingleColumn.Master in the root folder.


a.

In Solution Explorer, right-click NewMasterPage, point to Add, and then click New
Item.

b.

In the Add New Item NewMasterPage dialog box, in the middle pane, click Master
Page, in the Name box, type SingleColumn.Master, and then click Add.

The content in your new master page looks like this.


<%@ Master ... Inherits="NewMasterPage.SingleColumn" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>

5.

Set the value of the ID attribute of the existing ContentPlaceHolder in the form element to
MainContentPlaceHolder.
<asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>

6.

In the form element, and before the opening div tag, create a new div element with an ID
attribute value of header.

Applying Master Pages and CSS

11-5

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


<div id="header">
</div>

7.

In the new div element, add a new ContentPlaceHolder control and set the ID attribute value to
HeadContentPlaceHolder.
<div id="header">
<asp:ContentPlaceHolder ID="HeadContentPlaceHolder" runat="server">
</asp:ContentPlaceHolder>
</div>

8.

Open the NewMasterPage master page in Design view.

9.

In the SingleColumn.Master window, click Design.

Notice the single column layout, with two ContentPlaceHolder controls.

10. Close Visual Studio 2010.


a.

In the NewMasterPage Microsoft Visual Studio window, click the Close button.

b.

In the Microsoft Visual Studio dialog box, click No.

Demonstration: Using a Master Page in Web Forms and MVC View Pages
Using master page in a new Web Forms page
1.

Open Microsoft Visual Studio 2010.

2.

3.

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

Open the AdventureWorks solution from the D:\Demofiles\CS\Module11 or


D:\Demofiles\VB\Module11 folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorks.sln or
D:\Demofiles\VB\Module11\AdventureWorks.sln, and then click Open.

Add a new Web Form named UsingMasterPage based on the Site.Master master page to the
project.
a.

In Solution Explorer, right-click AdventureWorks, point to Add, and then click New
Item.

b.

In the Add New Item AdventureWorks dialog box, in the middle pane, click Web
Form using Master Page, in the Name box, type UsingMasterPage, and then click
Add.

c.

In the Select a Master Page dialog box, in the Contents of folder list, click
Site.Master, and then click OK.

Note: Your markup should appear similar to the following.


<%@ Page Title="" ... MasterPageFile="~/Site.Master" ...
Inherits="AdventureWorks.UsingMasterPage" %>

11-6

Developing Web Applications with Microsoft Visual Studio 2010

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">


</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>

4.

In the Content control with a ContentPlaceHolderID attribute value of MainContent, type


Hello World, I am using a Master Page!.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
Hello World, I am using a Master Page!
</asp:Content>

5.

Now test your page by pressing CTRL+F5.


Note: The rendered page should appear similar to the following.

6.

Close Windows Internet Explorer.

7.

In the http://localhost:xxxxx/UsingMasterPage.aspx Windows Internet Explorer


window, click the Close button.

Close the AdventureWorks solution.

In the AdventureWorks Microsoft Visual Studio window, on the File menu, click
Close Solution.

Using a master page in a new MVC view page


1.

Open the AdventureWorksMvc solution from the D:\Demofiles\CS\Module11 or


D:\Demofiles\VB\Module11 folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorksMvc.sln or
D:\Demofiles\VB\Module11\AdventureWorksMvc.sln, and then click Open.

Applying Master Pages and CSS

2.

11-7

Add a new View named UsingMasterPage.aspx based on the Site.Master master page to the
project. The view should be rendered by the Home controller, and saved to the Views\Home
folder.
a.

In Solution Explorer, expand Views, right-click Home, point to Add, and then click
View.

b.

In the Add View dialog box, in the View name box, type UsingMasterPage.aspx,
ensure the Select master page check box is selected, ensure the box below the Select
master page check box contains ~/Views/Shared/Site.Master, and then click Add.

Note: Your markup should appear similar to the following.


<%@ Page Title="" ... MasterPageFile="~/Views/Shared/Site.Master" ... %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
UsingMasterPage
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>UsingMasterPage</h2>
</asp:Content>

3.

In the Content control with a ContentPlaceHolderID attribute value of MainContent, in the h2


element, type Hello World, I am using a Master Page!.
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
Hello World, I am using a Master Page!</h2>
</asp:Content>

4.

Run the application.

5.

In Solution Explorer, click AdventureWorksMvc, and then press CTRL+F5.

Test your view page, by appending the following route to the existing URL, and then press
ENTER.
Home/UsingMasterPage

6.

In the Welcome to AdventureWorks Windows Internet Explorer window, in the Address


bar, append the following URL.
Home/UsingMasterPage

Note: The rendered page should appear similar to the following.

7.

Close Windows Internet Explorer.

In the http://localhost:xxxx/Home/UsingMasterPage Windows Internet Explorer


window, click the Close button.

11-8

Developing Web Applications with Microsoft Visual Studio 2010

8.

Close Visual Studio 2010.

In the AdventureWorksMvc Microsoft Visual Studio window, click the Close button.

Applying Master Pages and CSS

Lesson 2

Applying CSS, Skins, and Themes


Contents:
Question and Answers

10

Detailed Demo Steps

11

11-9

11-10

Developing Web Applications with Microsoft Visual Studio 2010

Question and Answers


What are Cascading Style Sheets?
Question: How does CSS allow you to apply your UI consistently across your application?
Answer: One answer is that you can quickly create styles to be applied to the main parent elements,
and override when needed for child elements.

Demonstration: Creating a CSS File


Question: What ideas came to mind while creating and implementing these styles?
Answer: May vary.

CSS Features of Visual Studio


Question: Do you know of any, or have you used any other CSS tools?
Answer: May vary.

Applying Master Pages and CSS

11-11

Detailed Demo Steps


Demonstration: Creating a CSS File
Creating a CSS file
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

Open the AdventureWorks solution from the D:\Demofiles\CS\Module11 or


D:\Demofiles\VB\Module11 folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Module11\AdventureWorks.sln or
D:\Demofiles\VB\Module11\AdventureWorks.sln, and then click Open.

In the Styles folder, create a new CSS file named Demo.css.


a.

In Solution Explorer, right-click Styles, point to Add, and then click New Item.

b.

In the Add New Item - AdventureWorks dialog box, in the middle pane, click Style
Sheet, in the File name box, type Demo.css, and then click Add.

Clear the default content of the Demo.css document.

5.

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

In the Demo.css window, press CTRL+A, and then press DELETE.

Add the following class styles to the document.


.demo-bg-1 { background-color:Lime; }
.demo-bg-2 { background-color:Fuchsia; }
.demo-bold { font-weight:bold; }
.demo-text-maroon { color:Maroon; }

In the Demo.css window, type the following markup.

.demo-bg-1 { background-color:Lime; }
.demo-bg-2 { background-color:Fuchsia; }
.demo-bold { font-weight:bold; }
.demo-text-maroon { color:Maroon; }

6.

Open the Site.Master master page.

7.

In Solution Explorer, double-click Site.Master.

Add the following markup to the head element, to link to the new CSS file.
<link href="~/Styles/Demo.css" rel="Stylesheet" type="text/css" />

In the Site.Master window, in the head element, below the existing link element, type
the following markup.

<link href="~/Styles/Demo.css" rel="Stylesheet" type="text/css" />

11-12

Developing Web Applications with Microsoft Visual Studio 2010

8.

Edit the div element with the class attribute of main, to apply the main, demo-bg-1, and
demo-text-maroon styles.
<div class="main demo-bg-1 demo-text-maroon">

In the Site.Master window, the div element with the class attribute of main, append
the following markup to the class attribute.

demo-bg-1 demo-text-maroon

9.

Edit the div element with the class attribute of footer, to apply the footer, demo-bg-2, and the
demo-bold styles.
<div class="footer demo-bg-2 demo-bold">

In the Site.Master window, the div element with the class attribute of footer, append
the following markup to the class attribute.

demo-bg-2 demo-bold

10. Test your page by pressing CTRL+F5.


Note: The rendered page should appear as follows.

11. Close Windows Internet Explorer.

In the Home Page Windows Internet Explorer window, click the Close button.

12. Close Visual Studio 2010.

In the AdventureWorks Microsoft Visual Studio window, click the Close button.

Developing Client-side Scripts and Services

Module 12
Developing Client-side Scripts and Services
Contents:
Lesson 1: Developing Client-side Scripts

Lesson 2: Implementing Ajax

Lesson 3: Creating Services

10

12-1

12-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Developing Client-side Scripts


Contents:
Question and Answers

Detailed Demo Steps

Developing Client-side Scripts and Services

12-3

Question and Answers


Client-side Code vs. Server-side Code
Question: If you were running a mortgage website, and needed to implement a mortgage calculator,
which would you chooseclient-side scripting or server-side scripting?
Answer: Client-side scripting (faster response).
Question: How would you make sure that your website works, even if the user disables the client-side
script?
Answer: May vary.

Creating Client-side Script


Question: What benefits will you achieve by maintaining the client-side code in a separate script file?
Answer: Portability, easier debugging, modularity.
Question: What other operations can you perform to reduce the size of the client-side script?
Answer: Will vary.

ASP.NET Controls Using Client-side Script


Question: Why is it necessary to validate the user input on the server-side as well as on the clientside?
Answer: Without validation, invalid or potentially dangerous data is sent to the server.

12-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Adding Client-side Script to the Page
Adding client-side code using inline script
1.

Open Microsoft Visual Studio 2010.

2.

3.

Create a new ASP.NET web application named Script in the D:\Demofiles\CS or


D:\Demofiles\VB folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New
Project.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click ASP.NET Web Application, in the Name box, type Script, in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

Open the Site.Master master page.

4.

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

In Solution Explorer, double-click Site.Master.

Append the following markup and code after the closing html tag.
<script type="text/JavaScript">
function inlineGreet()
{
alert('Hello World (inline)');
}
</script>

Adding client-side code using a separate JavaScript file


1.

2.

Add new JScript file named Site.js, to the project.


a.

In Solution Explorer, right-click Scripts, point to Add, and then click New Item.

b.

In the Add New Item Script dialog box, in the middle pane, click JScript File, in the
Name box, type Site.js, and then click Add.

Add the following code in the JScript file.


function externalGreet()
{
alert('Hello World (external)');
}

3.

Open the Site.Master master page.

In the Script Microsoft Visual Studio window, click Site.Master.

4.

Locate the head element.

5.

Add the following markup in the head element.


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

Developing Client-side Scripts and Services

<asp:ContentPlaceHolder ID="HeadContent" runat="server">


</asp:ContentPlaceHolder>
<script src="Scripts/Site.js" type="text/JavaScript" />
</head>

In the Site.Master window, append the following markup to the head element.

<script src="Scripts/Site.js" type="text/JavaScript" />

Demonstration: Showing an Alert Box Using Client-side Code


In this demonstration, you will see how to display an alert box using client-side script.
1.

Open the solution created in the previous demonstration.

2.

Call the inlineGreet function from the onload event of the body element.
<body onload="inlineGreet()">

3.

Open the default Web Form.

4.

In Solution Explorer, double-click Default.aspx.

Append the following markup to the BodyContent control.


<input type="button" value="Greet (external)" onclick="externalGreet()"/>

5.

Run the application.

Press CTRL+F5.

Note: The alert box is displayed with the greeting from the inline script.
6.

Click Greet (external).

In the Home Page - Windows Internet Explorer window, click Greet (external).

Note: The alert box is displayed with the greeting from the external script file.
7.

Close Windows Internet Explorer.

8.

In the Home Page Windows Internet Explorer window, click the Close button.

Close Visual Studio 2010.

In the Script Microsoft Visual Studio window, click the Close button.

12-5

12-6

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Implementing Ajax
Contents:
Detailed Demo Steps

Developing Client-side Scripts and Services

12-7

Detailed Demo Steps


Demonstration: Using the UpdatePanel Control
In this demonstration, you will see how to implement partial updates by using the UpdatePanel control.
1.

Open Microsoft Visual Studio 2010.

2.

3.

Open the PartialUpdates solution from the D:\Demofiles\CS or D:\Demofiles\VB folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\PartialUpdates.sln or D:\Demofiles\VB\PartialUpdates.sln, and then
click Open.

Open the default Web Form in Design view.

4.

9.

Open the Toolbox, expand Data, and then drag a GridView control to the UpdatePanel
control.

Add a SqlDataSource control to the Default.aspx Web Form, in the BodyContent control.

8.

Open the Toolbox, expand AJAX Extensions, and then double-click UpdatePanel.

Add a GridView control to the Default.aspx Web Form, in the UpdatePanel control.

7.

Open the Toolbox, expand AJAX Extensions, and then double-click ScriptManager.

Add an UpdatePanel control to the Default.aspx Web Form, in the BodyContent control.

6.

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

Add a ScriptManager control to the Default.aspx Web Form, in the BodyContent control.

5.

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

Open the Toolbox, expand Data, and then drag a SqlDataSource control to the
BodyContent control.

Set the DataSourceID property of the GridView control to the ID of the SqlDataSource control.
a.

In the Default.aspx window, in the Designer, select the GridView control.

b.

On the GridView control, click the Smart Tag in the GridView Tasks pane, and then in
the Choose Data Source list, click SqlDataSource1.

Set the GridView control to allow paging, by using the Smart Tag and the GridView Tasks
pane.

On the GridView control, click the Smart Tag, and then in the GridView Tasks pane,
select Enable Paging check box.

10. Configure the Data Source for the SqlDataSource control to use the existing
AdventureWorks2008R2ConnectionString, by using the Start Tag and the SqlDataSource
Tasks pane. The CustomerID, Title, FirstName, MiddleName, LastName, CompanyName,
SalesPerson, and Phone columns of the Customer table should be used.
a.

On the SqlDataSource control, click the Smart Tag, and then in the SqlDataSource
Tasks pane, click Configure Data Source.

12-8

Developing Web Applications with Microsoft Visual Studio 2010

b.

In the Configure Data Source SqlDataSource1 wizard, on the Choose Your Data
Connection page, in the Which data connection should your application use to
connect to your database? list, click AdventureWorks2008R2ConnectionString, and
then click Next.

c.

On the Configure the Select Statement page, ensure the Specify columns from a
table or view check box is selected, in the Name list, click Customer, in the Columns
list, select the CustomerID, Title, FirstName, MiddleName, LastName,
CompanyName, SalesPerson, and Phone check boxes, and then click Next.

d.

Click Finish.

11. Ensure that your markup looks similar to this.


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="CustomerID">
<Columns>
<asp:BoundField DataField="CustomerID"
HeaderText="CustomerID" InsertVisible="False"
ReadOnly="True" SortExpression="CustomerID" />
<asp:BoundField DataField="Title" HeaderText="Title"
SortExpression="Title" />
<asp:BoundField DataField="FirstName"
HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="MiddleName"
HeaderText="MiddleName" SortExpression="MiddleName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="SalesPerson"
HeaderText="SalesPerson" SortExpression="SalesPerson" />
<asp:BoundField DataField="Phone" HeaderText="Phone"
SortExpression="Phone" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
ConnectionStrings:AdventureWorksLT2008R2ConnectionString %>"
SelectCommand="SELECT [CustomerID], [Title], [FirstName], [MiddleName],
[LastName], [CompanyName], [SalesPerson], [Phone] FROM [Customer]">
</asp:SqlDataSource>
</asp:Content>

12. Run the application.

Press CTRL+F5.

13. Page through the rows in the GridView control.

At the bottom of the GridView control, click different page numbers 4-5 times.

14. Close Windows Internet Explorer.

In the Home Page Windows Internet Explorer window, click the Close button.

Developing Client-side Scripts and Services

15. Close Visual Studio 2010.

In the Script Microsoft Visual Studio window, click the Close button.

12-9

12-10

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Creating Services
Contents:
Detailed Demo Steps

11

Developing Client-side Scripts and Services

12-11

Detailed Demo Steps


Demonstration: Creating Ajax-enabled WCF Services
In this demonstration, you will see how to add a WCF service to a web application that can be called from
the client side.
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

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

Open the Script solution from the D:\Demofiles\CS\Script or D:\Demofiles\VB\Script folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Script\Script.sln or D:\Demofiles\VB\Script\Script.sln, and then
click Open.

Add a new Ajax-enabled WCF service named GreetingsService.svc to the project.


a.

In Solution Explorer, right-click Script, point to Add, and then click New Item.

b.

In the Add New Item - Script dialog box, in the middle pane, click Ajax-enabled WCF
Service, in the Name box, type GreetingsService.svc, and then click Add.

Remove the default DoWork method and comments from the service class.

[Visual C#]
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is
WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]

[Visual Basic]
' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is
WebMessageFormat.Json)
' To create an operation that returns XML,
' add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,
' and include the following line in the operation body:
' WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
<OperationContract()>
Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>

In the GreetingsService.svc window, select the following code, and then press DELETE.

12-12

Developing Web Applications with Microsoft Visual Studio 2010

[Visual C#]
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is
WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public void DoWork()
{
// Add your operation implementation here
return;
}
// Add more operations here and mark them with [OperationContract]

[Visual Basic]
' To use HTTP GET, add <WebGet()> attribute. (Default ResponseFormat is
WebMessageFormat.Json)
' To create an operation that returns XML,
' add <WebGet(ResponseFormat:=WebMessageFormat.Xml)>,
' and include the following line in the operation body:
' WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"
<OperationContract()>
Public Sub DoWork()
' Add your operation implementation here
End Sub
' Add more operations here and mark them with <OperationContract()>

5.

Add the following code to the service class.

[Visual C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace Script
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode =
AspNetCompatibilityRequirementsMode.Allowed)]
public class GreetingsService
{
[OperationContract]
public string Greet()
{
return "Hello World";
}
}
}

[Visual Basic]
Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web

Developing Client-side Scripts and Services

12-13

<ServiceContract(Namespace:="")>
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirement
sMode.Allowed)>
Public Class Greeting
<OperationContract()>
Public Function Greet() As String
Return "Hello World"
End Function
End Class

6.

Build the solution and fix any errors.

7.

In the Script Microsoft Visual Studio window, press CTRL+SHIFT+B.

Close Visual Studio 2010.

In the Script Microsoft Visual Studio window, click the Close button.

Demonstration: Invoking Ajax-enabled WCF Service Using Client-side Code


In this demonstration, you will see how to invoke the GreetingsService.svc using client-side code.
1.

Open Microsoft Visual Studio 2010.

2.

3.

Open the Script solution from the D:\Demofiles\CS\Script or D:\Demofiles\VB\Script folder.


a.

In the Start Page Microsoft Visual Studio window, on the File menu, click Open
Project.

b.

In the Open Project dialog box, in the File name box, type
D:\Demofiles\CS\Script\Script.sln or D:\Demofiles\VB\Script\Script.sln, and then
click Open.

Open the Site.Master master page.

4.

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

In Solution Explorer, double-click Site.Master.

Remove the onload attribute and value from the opening body tag.
<body onload="inlineGreet()">

5.

Open the Default.aspx Web Form.

6.

Remove the content of the BodyContent Content control.

7.

In Solution Explorer, double-click Default.aspx.

In the Default.aspx window, select the markup within the opening and closing Content
tags for the Content control with an ID attribute value of BodyContent, and then press
DELETE.

Add the following markup to register the WCF service using the ScriptManager control. Add the
markup in the empty Content control with an ID attribute value of BodyContent.
<asp:ScriptManager id="ScriptManager1" runat="server">
<services>
<asp:ServiceReference path="~/GreetingsService.svc" />
</services>

12-14

Developing Web Applications with Microsoft Visual Studio 2010

</asp:ScriptManager>

8.

Add the following code to the Default.aspx page in the empty Content control with an ID
attribute value of BodyContent.
<script type="text/JavaScript">
function greetUser() {
GreetingsService.Greet(onSuccess);
}
function onSuccess(result) {
alert(result);
}
</script>

9.

Add the following markup to the Default.aspx page in the empty Content control with an ID
attribute value of BodyContent.
<input type="button" value="Invoke Service" onclick="greetUser()" />

10. Run the application.

Press CTRL+F5.

11. Click Invoke Service.


Note: The WCF service will be invoked and an alert message will be displayed.
12. Close the dialog box.

In the Message from webpage dialog box, click OK.

13. Close Windows Internet Explorer.

In the Home Page Windows Internet Explorer window, click the Close button.

14. Close Visual Studio 2010.

In the Script Microsoft Visual Studio window, click the Close button.

Implementing Advanced Ajax in a Web Application

Module 13
Implementing Advanced Ajax in a Web Application
Contents:
Lesson 3: Working with jQuery and Ajax Events

13-1

13-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Working with jQuery and Ajax Events


Contents:
Detailed Demo Steps

Implementing Advanced Ajax in a Web Application

13-3

Detailed Demo Steps


Demonstration: Working with jQuery Ajax Event Handlers
Detailed demonstration steps
Introduction
In this demonstration, you will see how to work with different jQuery Ajax events.
1.

Open Microsoft Visual Studio 2010.

2.

3.

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

Create a new ASP.NET MVC 2 web application named jQueryEventHandlers in the D:\Demofiles\CS
or D:\Demofiles\VB folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the middle
pane, click ASP.NET MVC 2 Web Application, in the Name box, type jQueryEventHandlers, in
the Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

c.

In the Create Unit Test Project dialog box, select the No, do not create a unit test project
check box, and then click OK.

Add a controller action named ServerTime to the Home controller.

[Visual C#]
public string ServerTime(string message)
{
if (message == "ex")
throw new ArgumentException();
}

return "You said " + message + ", and the time is " + DateTime.Now;

[Visual Basic]
Function ServerTime(ByVal message As String) As String
If message = "ex" Then
Throw New ArgumentException()
End If
Return "You said " & message & ", and the time is " & DateTime.Now
End Function

In the HomeController.cs or HomeController.vb window, type the following code in the


HomeController class.
[Visual C#]
public string ServerTime(string message)
{
if (message == "ex")
throw new ArgumentException();
return "You said " + message + ", and the time is " + DateTime.Now;

13-4

Developing Web Applications with Microsoft Visual Studio 2010

[Visual Basic]
Function ServerTime(ByVal message As String) As String
If message = "ex" Then
Throw New ArgumentException()
End If
Return "You said " & message & ", and the time is " & DateTime.Now
End Function

Note: If you pass in the string ex, the method will throw an exception on the server.
4.

In the Views/Home/Index view, replace the current content of the Content2 or indexContent
Content control with a text box, a button, a div for logging the Ajax messages, and a div element
for displaying some of the results from the Ajax call.

<h2>
ServerTime</h2>
<input id="yourtext" type="text" name="message" /><input id="submit" type="button"
value="Load Data" />
<div id="log">
</div>
<p id="results">
</p>

a.

In Solution Explorer, expand Views, expand Home, and then double-click Index.aspx.

b.

Select the markup in the Content2 or indexContent Content control, and then press DELETE.

c.

In the Content2 or indexContent Content control, type the following markup.


<h2>
ServerTime</h2>
<input id="yourtext" type="text" name="message" /><input id="submit" type="button"
value="Load Data" />
<div id="log">
</div>
<p id="results">
</p>

5.

Create and enable event handlers for the .ajaxSend(), .ajaxComplete(), and .ajaxError() events, by
adding the following markup and code to the Index view.

<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"


type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#log").ajaxSend(function () {
$(this).slideDown("200").text("Loading...");
});
$("#log").ajaxComplete(function () {
$(this).slideUp("600", function () { $(this).text(""); });
});
$('#submit').click(function () {
var msg = $("#yourtext").val();

Implementing Advanced Ajax in a Web Application

});

$("#results").load('<%= Url.Action("ServerTime") %>', { message: msg });

$("#log").ajaxError(function () {
alert("error");
});

});
</script>

In the Index.aspx window, type the following markup at the bottom of the Content2 or
indexContent Content control.
<script src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"
type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#log").ajaxSend(function () {
$(this).slideDown("fast").text("Loading...");
});
$("#log").ajaxComplete(function () {
$(this).slideUp("slow", function () { $(this).text(""); });
});

});

$('#submit').click(function () {
var msg = $("#yourtext").val();
$("#results").load('<%= Url.Action("ServerTime") %>', { message: msg
});
$("#log").ajaxError(function () {
alert("error");
});

});
</script>

6.

Build the solution and fix any errors.

7.

Run the application.

8.

In the jQueryEventHandlers Microsoft Visual Studio window, press CTRL+SHIFT+B.

In Solution Explorer, click jQueryEventHandlers, and then press CTRL+F5.

In Windows Internet Explorer, in the text box, type This is a test, and then click Load Data.
Note: When the call to the controller method is made, the text Loading... is displayed below
the text box. When the call completes, a message similar to You said This is a test, and the
time is 9/16/2010 12:00:46 AM, is displayed.

9.

In Windows Internet Explorer, in the text box, type ex, and then click Load Data.
Note: When the call to the controller method is made, the text Loading... is displayed below
the text box. When the call completes, a message box is displayed, containing the text error.

10. Close the message box.

In the Message from webpage message box, click OK.

13-5

13-6

Developing Web Applications with Microsoft Visual Studio 2010

11. Close Windows Internet Explorer.

In the Home Page Windows Internet Explorer window, click the Close button.

12. Close Visual Studio 2010.

In the jQueryEventHandlers Microsoft Visual Studio window, click the Close button.

ASP.NET Deployments

Module 14
ASP.NET Deployments
Contents:
Lesson 1: Overview of Web Application Deployments

Lesson 2: Overview of Website Deployments

14-1

14-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 1

Overview of Web Application Deployments


Contents:
Question and Answers

ASP.NET Deployments

14-3

Question and Answers


Web Deployment Packages
Question: In which scenarios have you used web deployment packages? What were the advantages?
What were the disadvantages?
Answer: Will vary.

One-Click Publish
Question: In which scenarios have you used One-Click publishing? What were the advantages? What
were the disadvantages?
Answer: Will vary.

Enterprise Scenarios
Question: How many intermediate environments have you seen in an enterprise scenario? Did you
ever encounter a scenario where no intermediate environments were used?
Answer: Will vary.

Third-party Hosting Scenarios


Question: Which third-party hosting providers have you used? Did they feature shared hosting
environments? Did they feature dedicated servers? How did these features impact how you deployed
your applications?
Answer: Will vary.

Deploying a SQL Server Database


Question: How do you currently propagate data structures and data? What are the advantages?
What are the disadvantages?
Answer: Will vary.

Extending the Web Publishing Platform: The Web Server


Question: How do you currently deploy GAC assemblies, COM assemblies, and registry keys? What
issues have you encountered by not deploying these components correctly?
Answer: Will vary.

14-4

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 2

Overview of Website Deployments


Contents:
Question and Answers

ASP.NET Deployments

Question and Answers


The Copy Web Site Tool
Question: Where have you leveraged the Copy Web Site tool?
Answer: Will vary.
Question: What are some advantages to not having to recompile an application?
Answer: Faster, less chance of a component not functioning properly.

The Publish Web Site Utility


Question: Where have you leveraged the Publish Web Site utility?
Answer: Will vary.
Question: What are some advantages to having to recompile the application?
Answer: Ensures that all code is up to date and any compile errors are found.

Web.config File Deployment


Question: Where have you leveraged the Publish Web Site utility?
Answer: Will vary.

14-5

Developing a Web Application by Using Silverlight

Module 15
Developing a Web Application by Using Silverlight
Contents:
Lesson 3: Create a Silverlight Application

15-1

15-2

Developing Web Applications with Microsoft Visual Studio 2010

Lesson 3

Create a Silverlight Application


Contents:
Question and Answers

Detailed Demo Steps

Developing a Web Application by Using Silverlight

Question and Answers


Demonstration: Creating the Silverlight Project Structure
Question: Explain why a host project is necessary in a Silverlight solution.
Answer: Silverlight must be hosted to be able to run. You can host it in a host project or a simple
HTML page.

15-3

15-4

Developing Web Applications with Microsoft Visual Studio 2010

Detailed Demo Steps


Demonstration: Creating the Silverlight Project Structure
In this demonstration you will see how to create the structure for a simple Silverlight project, consisting of
a Silverlight project and an ASP.NET Web application project, the host project.
1.

Open Microsoft Visual Studio 2010.

2.

3.

4.

Create a new Silverlight Application named SilverlightApp in the D:\Demofiles\CS or


D:\Demofiles\VB folder.
a.

In the Start Page Microsoft Visual Studio window, on the File menu, click New Project.

b.

In the New Project dialog box, in the left pane, click Visual C# or Visual Basic, in the
middle pane, click Silverlight Application, in the Name box, type SilverlightApp , in the
Location box, type D:\Demofiles\CS or D:\Demofiles\VB, and then click OK.

c.

In the New Silverlight Application dialog box, verify the following, and then click OK.

d.

Verify that Host the Silverlight Application in a new Web site is selected (the default).

e.

Specify the new web project name as SilverlightApp.Web.

f.

Specify the new web project type as ASP.Net Web Application Project.

Notice that two projects have been created.

SilverlightApp is the Silverlight Application project. It consists of XAML and the


associated code-behinds that make up the Silverlight Application.

The App.xaml file is used by the application to declare shared resources. Also, its codebehind file is used to handle global application level events like Startup and Exit, similar
to Global.asax in an ASP.NET application.

MainPage.xaml is the default Silverlight page in the application. This project is built
into a XAP file, and used by the Silverlight plug-in to download and run the application
in the users browser. The XAP file contains the compressed assemblies and resources
that are necessary to run the application.

SilverlightApp.Web is the hosting project. This project contains the web pages
which will host the Silverlight Application.

Notice the folder named ClientBin.

5.

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

The file SilverlightApp.xap is the Application Package for the SilverlightApp


application. Visual Studio will update this XAP file when the project is built.

Open SilverlightAppTestPage.aspx.

Switch to Source view. The object element is the container for the Silverlight application
SilverlightApp. It contains references to the Silverlight runtime, including a link to
download it, if it is not already installed in the users browser.

Developing Web Applications with Microsoft Visual Studio 2010

R-1

Send Us Your Feedback


You can search the Microsoft Knowledge Base for known issues at Microsoft Help and Support before
submitting feedback. Search using either the course number and revision, or the course title.

Note Not all training products will have a Knowledge Base article if that is the case, please ask your
instructor whether or not there are existing error log entries.

Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.

Reporting Errors
When providing feedback, include the training product name and number in the subject line of your email. When you provide comments or report bugs, please include the following:

Document or CD part number

Page number or location

Complete description of the error or suggested change

Please provide any details that are necessary to help us verify the issue.

Important All errors and suggestions are evaluated, but only those that are validated are added to the
product Knowledge Base article.

Você também pode gostar